content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package kotterknife import android.app.Activity import android.view.View import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty fun <V : View> Activity.bindView(id: Int): ReadOnlyProperty<Activity, V> = Lazy { _: Any?, desc -> findViewById<V>(id) ?: viewNotFound(id, desc) } private fun viewNotFound(id: Int, desc: KProperty<*>): Nothing = throw IllegalStateException("View ID $id for '${desc.name}' not found.") class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> { private var value: Any? = EMPTY override fun getValue(thisRef: T, property: KProperty<*>): V { if (value == EMPTY) { value = initializer(thisRef, property) } @Suppress("UNCHECKED_CAST") return value as V } companion object { private object EMPTY } }
app/src/main/java/kotterknife/Kotterknife.kt
3501003021
package br.ufpe.cin.android.threads import android.app.Activity import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Bundle import android.widget.Toast import kotlinx.android.synthetic.main.threads.* class ThreadViewPost : Activity() { private var mBitmap: Bitmap? = null private val mDelay = 5000 internal var toasts = 0 public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.threads) loadButton.setOnClickListener { loadIcon() } otherButton.setOnClickListener { toasts++ contadorToasts.text = getString(R.string.contador_de_toasts) + toasts Toast.makeText(applicationContext, "Estou trabalhando... ($toasts)", Toast.LENGTH_SHORT).show() } } private fun loadIcon() { Thread(Runnable { try { Thread.sleep(mDelay.toLong()) } catch (e: InterruptedException) { e.printStackTrace() } mBitmap = BitmapFactory.decodeResource(resources, R.drawable.painter) imageView.post { imageView.setImageBitmap(mBitmap) } }).start() } }
2019-08-28/Threads/app/src/main/java/br/ufpe/cin/android/threads/ThreadViewPost.kt
1841764023
package com.duopoints.android.fragments.relprofile import com.duopoints.android.Calls import com.duopoints.android.fragments.base.BasePresenter import com.duopoints.android.logistics.SessionManager import com.duopoints.android.rest.models.composites.CompositeRelationship import com.duopoints.android.rest.models.enums.rel.RelationshipBreakupRequestStatus import com.duopoints.android.rest.models.post.NewRelationshipBreakupRequest import com.duopoints.android.utils.ReactiveUtils import com.duopoints.android.utils.logging.LogLevel import com.duopoints.android.utils.logging.log import io.reactivex.Observable import io.reactivex.functions.Consumer import io.reactivex.functions.Function3 import org.joda.time.DateTime import org.joda.time.DateTimeZone import java.util.* class RelationshipProfilePresenter(relationshipProfileFrag: RelationshipProfileFrag) : BasePresenter<RelationshipProfileFrag>(relationshipProfileFrag) { fun observeNewPoints() { Observable.combineLatest( SessionManager.observePointsGivenWithDefault(), SessionManager.observeUserRelationshipWithDefault(), SessionManager.observeUserRelationshipBreakupRequestWithDefault(), Function3<Any?, Any?, Any?, Boolean> { _, _, _ -> true }) .skip(1) .compose(ReactiveUtils.commonObservableTransformation(view, true)) .subscribe({ view.reloadRelationshipData() }, { it.printStackTrace() }) } fun processRelationship(relationship: CompositeRelationship) { if (SessionManager.getUserRelationship()?.relationshipUuid == relationship.relationshipUuid) { // Get any BreakupRequest that might exist val breakupRequest = SessionManager.getUserRelationshipBreakupRequests() view.showingOwnRelationship(breakupRequest) breakupRequest?.let { val requestedByCurrentUser = SessionManager.getUser().userUuid == it.userUuid // Get the "must wait until" Datetime val waitUntil = DateTime(it.relationshipBreakupRequestWaitUntil, DateTimeZone.UTC) // If the time NOW is passed the Cool-Off period if (DateTime.now(DateTimeZone.UTC).isAfter(waitUntil)) { if (requestedByCurrentUser) { view.requestedUserCoolOffWaitPassed() } else { view.partnerCoolOffWaitPassed() } } else { if (requestedByCurrentUser) { view.requestedUserCoolOffNotWaitPassed(waitUntil) } else { view.partnerCoolOffNotWaitPassed(waitUntil) } } } } } fun loadFullRelationshipData(relationshipUuid: UUID) { Calls.relationshipService.getFullRelationshipData(relationshipUuid) .compose(ReactiveUtils.commonMaybeTransformation(view, true)) .subscribe(Consumer(view::relationshipLoaded), ReactiveUtils.notNotFound(view::errorLoadingRelationship)) } /******************** * BREAKUP REQUESTS ********************/ fun requestRelationshipBreakup() { val relationship = SessionManager.getUserRelationship() val breakupRequest = SessionManager.getUserRelationshipBreakupRequests() when { relationship == null -> javaClass.log(LogLevel.ERROR, "Session Relationship was null! Error!") breakupRequest != null -> javaClass.log(LogLevel.ERROR, "Session Breakup Request already exists! Error!") else -> { val newRequest = NewRelationshipBreakupRequest(SessionManager.getUser().userUuid, relationship.relationshipUuid, "Let us break up!") Calls.relationshipService.requestCompositeRelationshipBreakup(newRequest) .compose(ReactiveUtils.commonMaybeTransformation(view, true)) .subscribe({ SessionManager.syncRelationshipBreakup() }, Throwable::printStackTrace) } } } fun cancelRelationshipBreakup() { requestRelationshipStatus(RelationshipBreakupRequestStatus.CANCELLED) } fun acceptRelationshipBreakup() { requestRelationshipStatus(RelationshipBreakupRequestStatus.COMPLETED) } private fun requestRelationshipStatus(status: RelationshipBreakupRequestStatus) { val relationship = SessionManager.getUserRelationship() val breakupRequest = SessionManager.getUserRelationshipBreakupRequests() when { relationship == null -> javaClass.log(LogLevel.ERROR, "Session Relationship was null! Error!") breakupRequest == null -> javaClass.log(LogLevel.ERROR, "Session Breakup Request was null! Error!") relationship.relationshipUuid != breakupRequest.relationshipUuid -> javaClass.log(LogLevel.ERROR, "Session Relationship did not match Session Breakup Request! Error!") else -> { Calls.relationshipService.setFinalCompositeRelationshipBreakupRequestStatus(breakupRequest.relationshipBreakupRequestUuid, status) .compose(ReactiveUtils.commonMaybeTransformation(view, true)) .subscribe({ SessionManager.syncRelationship() SessionManager.syncRelationshipBreakup() }, Throwable::printStackTrace) } } } }
app/src/main/java/com/duopoints/android/fragments/relprofile/RelationshipProfilePresenter.kt
2889573079
package br.ufpe.cin.android.systemservices.alarm import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.util.Log import java.text.DateFormat import java.util.Date class AlarmLogReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { Log.i("ANDROID@CIn", "Alarme registrado em:" + DateFormat.getDateTimeInstance().format(Date())) } }
2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/alarm/AlarmLogReceiver.kt
665764134
package utils.parsertools.combinators.tree import utils.parsertools.ast.AstList import utils.parsertools.ast.AstNode import utils.parsertools.combinators.Bnf import utils.parsertools.combinators.Element import utils.parsertools.lex.Lexer /** * Created by liufengkai on 2017/4/24. */ class OneOrMore(private val parser: Bnf, private val onlyOne: Boolean) : Element { override fun parse(lexer: Lexer, nodes: MutableList<AstNode>) { while (parser.match(lexer)) { val node = parser.parse(lexer) // leaf or list if (node !is AstList || node.childCount() > 0) { nodes.add(node) } if (onlyOne) break } } override fun match(lexer: Lexer): Boolean { return parser.match(lexer) } }
src/utils/parsertools/combinators/tree/OneOrMore.kt
2328267582
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.modernstorage.storage import android.app.Activity import android.content.Intent class TestingActivity : Activity() { /** * Return activity result for any intent (used in tests) */ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) println(data?.data) if (resultCode == RESULT_OK) { // We persist the returned Uri to interact with it as the initial grant access will be // lost after finish() is called data?.data?.let { uri -> contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } } setResult(resultCode, data) finish() } }
storage/src/androidTest/java/com/google/modernstorage/storage/TestingActivity.kt
3787357429
package org.softlang.util /** * Skips [num] elements in the list. */ fun <E> List<E>.skip(num: Int) = subList(num, size) /** * Returns the tail of the list. */ fun <E> List<E>.tail() = skip(1) /** * Constructs a list from the first element and a list of remaining elements. */ infix fun <E> E.then(list: List<E>) = listOf(this) + list /** * Checks if list contains item, returns false if item is null and list is * not nullable. */ fun <E> List<E>.contains(item: E?) = if (item == null) false else contains(item) /** * Returns consecutive values of the list as pairs. */ val <E> List<E>.pairs: List<Pair<E, E>> get() = (1 until size) .map { get(it - 1) to get(it) } /** * Decomposes the list as head and tail for pair variable assignments. */ val <E> List<E>.decomposed: Pair<E, List<E>> get() = first() to tail()
src/main/kotlin/org/softlang/util/Lists.kt
2699092359
package com.ternaryop.photoshelf.adapter import android.util.SparseBooleanArray /** * Created by dave on 13/04/16. * Hold selection index state */ open class SelectionArray : Selection { private val items = SparseBooleanArray() override val itemCount: Int get() = items.size() override val selectedPositions: IntArray get() { val positions = IntArray(items.size()) for (i in 0 until items.size()) { positions[i] = items.keyAt(i) } return positions } override fun toggle(position: Int) { if (items.get(position, false)) { items.delete(position) } else { items.put(position, true) } } override fun isSelected(position: Int): Boolean { return items.get(position, false) } override fun setSelected(position: Int, selected: Boolean) { if (selected) { items.put(position, true) } else { items.delete(position) } } override fun clear() { items.clear() } override fun setSelectedRange(start: Int, end: Int, selected: Boolean) { for (i in start until end) { setSelected(i, selected) } } }
core/src/main/java/com/ternaryop/photoshelf/adapter/SelectionArray.kt
2071440593
/* * Copyright 2018-2021 Andrei Heidelbacher <andrei.heidelbacher@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.chronolens.core.repository import org.chronolens.core.model.AddNode import org.chronolens.core.model.EditType import org.chronolens.core.model.RemoveNode import org.chronolens.core.model.Type import org.junit.Test import java.time.Instant import kotlin.test.assertEquals import kotlin.test.assertFailsWith class TransactionTest { @Test fun `test transaction with empty id throws`() { assertFailsWith<IllegalArgumentException> { Transaction(revisionId = "", date = Instant.now(), author = "") } } @Test fun `test transaction with invalid characters in id throws`() { assertFailsWith<IllegalArgumentException> { Transaction(revisionId = "12aA_", date = Instant.now(), author = "") } } @Test fun `test change set`() { val expected = setOf("Main.java", "Test.java", "MainTest.java") val actual = Transaction( revisionId = "123", date = Instant.now(), author = "", edits = listOf( AddNode( id = "Main.java:Main:MainType", node = Type("MainType"), ), RemoveNode("Test.java:Test:TestType"), EditType("MainTest.java:MainTest") ) ).changeSet assertEquals(expected, actual) } }
chronolens-core/src/test/kotlin/org/chronolens/core/repository/TransactionTest.kt
1659531365
import io.mockk.verify import org.apollo.game.command.Command import org.apollo.game.model.World import org.apollo.game.model.entity.Player import org.apollo.game.model.entity.setting.PrivilegeLevel import org.apollo.game.plugin.testing.junit.ApolloTestingExtension import org.apollo.game.plugin.testing.junit.api.annotations.TestMock import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(ApolloTestingExtension::class) class BankCommandTests { @TestMock lateinit var world: World @TestMock lateinit var player: Player @Test fun `Opens bank when used`() { player.privilegeLevel = PrivilegeLevel.ADMINISTRATOR world.commandDispatcher.dispatch(player, Command("bank", emptyArray())) verify { player.openBank() } } }
game/plugin/cmd/test/BankCommandTests.kt
2020310741
package uk.co.ribot.androidboilerplate.ui.base /** * Every presenter in the app must either implement this interface or extend BasePresenter * indicating the MvpView type that wants to be attached with. */ interface Presenter<in V : MvpView> { fun attachView(view: V) fun detachView() }
app/src/main/kotlin/uk/co/ribot/androidboilerplate/ui/base/Presenter.kt
2289553848
package com.chibatching.kotpref.pref import android.annotation.SuppressLint import android.annotation.TargetApi import android.os.Build import android.os.SystemClock import com.chibatching.kotpref.KotprefModel import com.chibatching.kotpref.execute import kotlin.reflect.KProperty /** * Delegate string set shared preferences property. * @param default default string set value * @param key custom preferences key * @param commitByDefault commit this property instead of apply */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public fun KotprefModel.stringSetPref( default: Set<String> = LinkedHashSet(), key: String? = null, commitByDefault: Boolean = commitAllPropertiesByDefault ): AbstractStringSetPref = stringSetPref(key, commitByDefault) { default } /** * Delegate string set shared preferences property. * @param default default string set value * @param key custom preferences key resource id * @param commitByDefault commit this property instead of apply */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public fun KotprefModel.stringSetPref( default: Set<String> = LinkedHashSet(), key: Int, commitByDefault: Boolean = commitAllPropertiesByDefault ): AbstractStringSetPref = stringSetPref(context.getString(key), commitByDefault) { default } /** * Delegate string set shared preferences property. * @param key custom preferences key * @param commitByDefault commit this property instead of apply * @param default default string set value creation function */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public fun KotprefModel.stringSetPref( key: String? = null, commitByDefault: Boolean = commitAllPropertiesByDefault, default: () -> Set<String> ): AbstractStringSetPref = StringSetPref(default, key, commitByDefault) /** * Delegate string set shared preferences property. * @param key custom preferences key resource id * @param commitByDefault commit this property instead of apply * @param default default string set value */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public fun KotprefModel.stringSetPref( key: Int, commitByDefault: Boolean = commitAllPropertiesByDefault, default: () -> Set<String> ): AbstractStringSetPref = stringSetPref(context.getString(key), commitByDefault, default) @TargetApi(Build.VERSION_CODES.HONEYCOMB) internal class StringSetPref( val default: () -> Set<String>, override val key: String?, private val commitByDefault: Boolean ) : AbstractStringSetPref() { private var stringSet: MutableSet<String>? = null private var lastUpdate: Long = 0L override operator fun getValue( thisRef: KotprefModel, property: KProperty<*> ): MutableSet<String> { if (stringSet != null && lastUpdate >= thisRef.kotprefTransactionStartTime) { return stringSet!! } val prefSet = thisRef.kotprefPreference.getStringSet(preferenceKey, null) ?.let { HashSet(it) } stringSet = PrefMutableSet( thisRef, prefSet ?: default.invoke().toMutableSet(), preferenceKey ) lastUpdate = SystemClock.uptimeMillis() return stringSet!! } internal inner class PrefMutableSet( val kotprefModel: KotprefModel, val set: MutableSet<String>, val key: String ) : MutableSet<String> by set { init { addAll(set) } private var transactionData: MutableSet<String>? = null get() { field = field ?: set.toMutableSet() return field } internal fun syncTransaction() { synchronized(this) { transactionData?.let { set.clear() set.addAll(it) transactionData = null } } } @SuppressLint("CommitPrefEdits") override fun add(element: String): Boolean { if (kotprefModel.kotprefInTransaction) { val result = transactionData!!.add(element) kotprefModel.kotprefEditor!!.putStringSet(key, this) return result } val result = set.add(element) kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault) return result } @SuppressLint("CommitPrefEdits") override fun addAll(elements: Collection<String>): Boolean { if (kotprefModel.kotprefInTransaction) { val result = transactionData!!.addAll(elements) kotprefModel.kotprefEditor!!.putStringSet(key, this) return result } val result = set.addAll(elements) kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault) return result } @SuppressLint("CommitPrefEdits") override fun remove(element: String): Boolean { if (kotprefModel.kotprefInTransaction) { val result = transactionData!!.remove(element) kotprefModel.kotprefEditor!!.putStringSet(key, this) return result } val result = set.remove(element) kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault) return result } @SuppressLint("CommitPrefEdits") override fun removeAll(elements: Collection<String>): Boolean { if (kotprefModel.kotprefInTransaction) { val result = transactionData!!.removeAll(elements) kotprefModel.kotprefEditor!!.putStringSet(key, this) return result } val result = set.removeAll(elements) kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault) return result } @SuppressLint("CommitPrefEdits") override fun retainAll(elements: Collection<String>): Boolean { if (kotprefModel.kotprefInTransaction) { val result = transactionData!!.retainAll(elements) kotprefModel.kotprefEditor!!.putStringSet(key, this) return result } val result = set.retainAll(elements) kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault) return result } @SuppressLint("CommitPrefEdits") override fun clear() { if (kotprefModel.kotprefInTransaction) { val result = transactionData!!.clear() kotprefModel.kotprefEditor!!.putStringSet(key, this) return result } set.clear() kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault) } override fun contains(element: String): Boolean { if (kotprefModel.kotprefInTransaction) { return element in transactionData!! } return element in set } override fun containsAll(elements: Collection<String>): Boolean { if (kotprefModel.kotprefInTransaction) { return transactionData!!.containsAll(elements) } return set.containsAll(elements) } override fun iterator(): MutableIterator<String> { return if (kotprefModel.kotprefInTransaction) { kotprefModel.kotprefEditor!!.putStringSet(key, this@PrefMutableSet) KotprefMutableIterator(transactionData!!.iterator(), true) } else { KotprefMutableIterator(set.iterator(), false) } } override val size: Int get() { if (kotprefModel.kotprefInTransaction) { return transactionData!!.size } return set.size } private inner class KotprefMutableIterator( val baseIterator: MutableIterator<String>, val inTransaction: Boolean ) : MutableIterator<String> by baseIterator { @SuppressLint("CommitPrefEdits") override fun remove() { baseIterator.remove() if (!inTransaction) { kotprefModel.kotprefPreference.edit().putStringSet(key, set) .execute(commitByDefault) } } } } }
kotpref/src/main/kotlin/com/chibatching/kotpref/pref/StringSetPref.kt
3526642934
package net.nemerosa.ontrack.extension.oidc import net.nemerosa.ontrack.extension.casc.CascExtensionFeature import net.nemerosa.ontrack.extension.support.AbstractExtensionFeature import net.nemerosa.ontrack.model.extension.ExtensionFeatureOptions import org.springframework.stereotype.Component @Component class OIDCExtensionFeature( private val cascExtensionFeature: CascExtensionFeature, ) : AbstractExtensionFeature( "oidc", "OIDC", "Support for OIDC authentication", ExtensionFeatureOptions.DEFAULT .withDependency(cascExtensionFeature) .withGui(true) )
ontrack-extension-oidc/src/main/java/net/nemerosa/ontrack/extension/oidc/OIDCExtensionFeature.kt
4089187030
package net.nemerosa.ontrack.extension.general import net.nemerosa.ontrack.model.exceptions.InputException import net.nemerosa.ontrack.model.structure.ProjectEntity import net.nemerosa.ontrack.model.structure.PromotionLevel class PreviousPromotionRequiredException( previousPromotion: PromotionLevel, promotion: PromotionLevel, entity: ProjectEntity ) : InputException( """ The "Previous Promotion Condition" setup in ${entity.entityDisplayName} prevents the ${promotion.name} to be granted because the ${previousPromotion.name} promotion has not been granted. """.trimIndent() )
ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/PreviousPromotionRequiredException.kt
2878168733
package org.tvheadend.tvhclient.util.worker import android.app.PendingIntent import android.content.Context import android.content.Intent import androidx.core.app.NotificationManagerCompat import androidx.work.Worker import androidx.work.WorkerParameters import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.service.ConnectionService import org.tvheadend.tvhclient.ui.common.getNotificationBuilder import timber.log.Timber import java.text.SimpleDateFormat import java.util.* class RecordingNotificationWorker(val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { companion object { const val WORK_NAME = "RecordingNotificationWorker" } override fun doWork(): Result { val dvrTitle = inputData.getString("dvrTitle") val dvrId = inputData.getInt("dvrId", 0) val startTime = inputData.getLong("start", 0) Timber.d("Received notification broadcast for recording $dvrTitle") // Create the intent that handles the cancelling of the scheduled recording val recordIntent = Intent(context, ConnectionService::class.java) recordIntent.action = "cancelDvrEntry" recordIntent.putExtra("id", dvrId) val cancelRecordingPendingIntent = PendingIntent.getService(context, 0, recordIntent, PendingIntent.FLAG_UPDATE_CURRENT) // Create the title of the notification. // The text below the title will be the recording name val sdf = SimpleDateFormat("HH:mm", Locale.US) val title = "Recording starts at ${sdf.format(startTime)} in ${(startTime - Date().time) / 1000 / 60} minutes." val builder = getNotificationBuilder(context) builder.setContentTitle(title) .setContentText(dvrTitle) .addAction(R.attr.ic_menu_record_cancel, context.getString(R.string.record_cancel), cancelRecordingPendingIntent) NotificationManagerCompat.from(context).notify(dvrId, builder.build()) return Result.success() } }
app/src/main/java/org/tvheadend/tvhclient/util/worker/RecordingNotificationWorker.kt
3982022216
@file:JvmName("ContactUtils") package com.hackedcube.kontact import android.content.Context import android.database.Cursor import android.net.Uri import android.provider.ContactsContract fun Context.queryAllContacts(): List<Kontact> { contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null).use { return generateSequence { if (it.moveToNext()) it else null } .map { kontactFromCursor(this, it) } .toList() } } fun Context.getContactFromId(uri: Uri): Kontact? { contentResolver.query(uri, null, null, null, null).use { cursorContact -> cursorContact.moveToFirst() return kontactFromCursor(this, cursorContact) } } private fun kontactFromCursor(context: Context, cursor: Cursor): Kontact { var kontact = Kontact.create(cursor) // Fetch Phone Numbers if (kontact.hasPhoneNumber()) { context.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", arrayOf(kontact.id()), null).use { phoneCursor -> val phoneNumbers = phoneCursor.toSequence() .map { PhoneNumber.create(it) } .toList() kontact = kontact.withPhoneNumbers(phoneNumbers) } } // Fetch Email addresses context.contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", arrayOf(kontact.id()), null).use { emailCursor -> val emailAddresses = emailCursor.toSequence() .map { EmailAddress.create(it) } .toList() kontact = kontact.withEmailAddresses(emailAddresses) } val select = arrayOf(ContactsContract.Data.MIMETYPE, "data1", "data2", "data3", "data4", "data5", "data6", "data7", "data8", "data9", "data10", "data11", "data12", "data13", "data14", "data15") // Fetch additional info val where = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} IN (?, ?, ?, ?)" val whereParams = arrayOf( kontact.id(), ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE ) context.contentResolver.query(ContactsContract.Data.CONTENT_URI, select, where, whereParams, null).use { dataCursor -> val data = dataCursor.toSequence() .map { val columnType = it.getString(it.getColumnIndex(ContactsContract.Data.MIMETYPE)) when(columnType) { ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE -> columnType to Event.create(it) ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE -> columnType to Nickname.create(it) ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE -> columnType to Relation.create(it) ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE -> columnType to PostalAddress.create(it) else -> columnType to null } } .groupBy({it.first}, {it.second}) kontact = kontact.toBuilder() .events(data[ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE] as MutableList<Event>?) .nicknames(data[ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE] as MutableList<Nickname>?) .postalAddresses(data[ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE] as MutableList<PostalAddress>?) .relations(data[ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE] as MutableList<Relation>?) .build() } return kontact }
kontact/src/main/kotlin/com/hackedcube/kontact/ContactUtils.kt
1384671678
package clInterface.executor import SonarRequest import objects.Car import objects.Environment import java.net.ConnectException import java.util.* import java.util.concurrent.TimeUnit class Sonar : CommandExecutor { private val SONAR_REGEX = Regex("sonar [0-9]{1,10}") override fun execute(command: String) { if (!SONAR_REGEX.matches(command)) { println("incorrect args of command sonar.") return } val id: Int try { id = command.split(" ")[1].toInt() } catch (e: NumberFormatException) { e.printStackTrace() println("error in converting id to int type") return } val car: Car? = synchronized(Environment, { Environment.map[id] }) if (car == null) { println("car with id=$id not found") return } val angles = getRequiredAngles() ?: return try { val sonarResult = car.scan(angles, 5, 3, SonarRequest.Smoothing.MEDIAN) val distances = sonarResult.get(2, TimeUnit.MINUTES) println("angles : ${Arrays.toString(angles)}") println("distances: ${Arrays.toString(distances)}") } catch (e: ConnectException) { synchronized(Environment, { Environment.map.remove(id) }) } } private fun getRequiredAngles(): IntArray? { println("print angles, after printing all angles print done") val angles = arrayListOf<Int>() while (true) { val command = readLine()!!.toLowerCase() when (command) { "reset" -> return null "done" -> { return angles.toIntArray() } else -> { try { val angle = command.toInt() if (angle < 0 || angle > 180) { println("incorrect angle $angle. angle must be in [0,180] and div on 4") } else { angles.add(angle) } } catch (e: NumberFormatException) { println("error in converting angle to int. try again") } } } } } }
server/src/main/java/clInterface/executor/Sonar.kt
1883186777
/* * This file is part of BOINC. * http://boinc.berkeley.edu * Copyright (C) 2020 University of California * * BOINC is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * BOINC is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with BOINC. If not, see <http://www.gnu.org/licenses/>. */ package edu.berkeley.boinc.rpc import android.os.Parcel import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @RunWith(RobolectricTestRunner::class) class TransferParcelableTest { @Test fun `Test Creator createFromParcel()`() { val expected = Transfer() val parcel = Parcel.obtain() expected.writeToParcel(parcel, expected.describeContents()) // Reset parcel for reading. parcel.setDataPosition(0) val actual = Transfer.CREATOR.createFromParcel(parcel) Assert.assertEquals(expected, actual) } @Test fun `Test Creator newArray()`() { val array = Transfer.CREATOR.newArray(2) Assert.assertNotNull(array) Assert.assertEquals(2, array.size) } }
android/BOINC/app/src/test/java/edu/berkeley/boinc/rpc/TransferParcelableTest.kt
3187289487
package tornadofx import com.sun.javafx.tk.Toolkit import javafx.application.Platform import javafx.beans.property.* import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import javafx.concurrent.Task import javafx.scene.Node import javafx.scene.control.Labeled import javafx.scene.control.ProgressIndicator import javafx.scene.layout.BorderPane import javafx.scene.layout.Region import javafx.util.Duration import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.ThreadFactory import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicLong import java.util.logging.Level import java.util.logging.Logger internal val log = Logger.getLogger("tornadofx.async") internal val dummyUncaughtExceptionHandler = Thread.UncaughtExceptionHandler { t, e -> log.log(Level.WARNING, e) { "Exception in ${t?.name ?: "?"}: ${e?.message ?: "?"}" } } internal val tfxThreadPool = Executors.newCachedThreadPool(object : ThreadFactory { private val threadCounter = AtomicLong(0L) override fun newThread(runnable: Runnable?) = Thread(runnable, "tornadofx-thread-${threadCounter.incrementAndGet()}") }) fun <T> task(taskStatus: TaskStatus? = null, func: FXTask<*>.() -> T): Task<T> = FXTask(taskStatus, func = func).apply { setOnFailed({ (Thread.getDefaultUncaughtExceptionHandler() ?: dummyUncaughtExceptionHandler).uncaughtException(Thread.currentThread(), exception) }) tfxThreadPool.execute(this) } fun <T> runAsync(status: TaskStatus? = null, func: FXTask<*>.() -> T) = task(status, func) infix fun <T> Task<T>.ui(func: (T) -> Unit) = success(func) infix fun <T> Task<T>.success(func: (T) -> Unit) = apply { Platform.runLater { setOnSucceeded { func(value) } } } infix fun <T> Task<T>.fail(func: (Throwable) -> Unit) = apply { Platform.runLater { setOnFailed { func(exception) } } } /** * Run the specified Runnable on the JavaFX Application Thread at some * unspecified time in the future. */ fun runLater(op: () -> Unit) = Platform.runLater(op) /** * Run the specified Runnable on the JavaFX Application Thread after a * specified delay. * * runLater(10.seconds) { * // Do something on the application thread * } * * This function returns a TimerTask which includes a runningProperty as well as the owning timer. * You can cancel the task before the time is up to abort the execution. */ fun runLater(delay: Duration, op: () -> Unit): FXTimerTask { val timer = Timer(true) val task = FXTimerTask(op, timer) timer.schedule(task, delay.toMillis().toLong()) return task } /** * Wait on the UI thread until a certain value is available on this observable. * * This method does not block the UI thread even though it halts further execution until the condition is met. */ fun <T> ObservableValue<T>.awaitUntil(condition: (T) -> Boolean) { if (!Toolkit.getToolkit().canStartNestedEventLoop()) { throw IllegalStateException("awaitUntil is not allowed during animation or layout processing") } val changeListener = object : ChangeListener<T> { override fun changed(observable: ObservableValue<out T>?, oldValue: T, newValue: T) { if (condition(value)) { runLater { Toolkit.getToolkit().exitNestedEventLoop(this@awaitUntil, null) removeListener(this) } } } } changeListener.changed(this, value, value) addListener(changeListener) Toolkit.getToolkit().enterNestedEventLoop(this) } /** * Wait on the UI thread until this observable value is true. * * This method does not block the UI thread even though it halts further execution until the condition is met. */ fun ObservableValue<Boolean>.awaitUntil() { this.awaitUntil { it } } /** * Replace this node with a progress node while a long running task * is running and swap it back when complete. * * If this node is Labeled, the graphic property will contain the progress bar instead while the task is running. * * The default progress node is a ProgressIndicator that fills the same * client area as the parent. You can swap the progress node for any Node you like. * * For latch usage see [runAsyncWithOverlay] */ fun Node.runAsyncWithProgress(latch: CountDownLatch, timeout: Duration? = null, progress: Node = ProgressIndicator()): Task<Boolean> { return if(timeout == null) { runAsyncWithProgress(progress) { latch.await(); true } } else { runAsyncWithOverlay(progress) { latch.await(timeout.toMillis().toLong(), TimeUnit.MILLISECONDS) } } } /** * Replace this node with a progress node while a long running task * is running and swap it back when complete. * * If this node is Labeled, the graphic property will contain the progress bar instead while the task is running. * * The default progress node is a ProgressIndicator that fills the same * client area as the parent. You can swap the progress node for any Node you like. */ fun <T : Any> Node.runAsyncWithProgress(progress: Node = ProgressIndicator(), op: () -> T): Task<T> { if (this is Labeled) { val oldGraphic = graphic (progress as? Region)?.setPrefSize(16.0, 16.0) graphic = progress return task { try { op() } finally { runLater { this@runAsyncWithProgress.graphic = oldGraphic } } } } else { val paddingHorizontal = (this as? Region)?.paddingHorizontal?.toDouble() ?: 0.0 val paddingVertical = (this as? Region)?.paddingVertical?.toDouble() ?: 0.0 (progress as? Region)?.setPrefSize(boundsInParent.width - paddingHorizontal, boundsInParent.height - paddingVertical) val children = requireNotNull(parent.getChildList()){"This node has no child list, and cannot contain the progress node"} val index = children.indexOf(this) children.add(index, progress) removeFromParent() return task { val result = op() runLater { children.add(index, this@runAsyncWithProgress) progress.removeFromParent() } result } } } /** * Covers node with overlay (by default - an instance of [MaskPane]) until [latch] is released by another thread. * It's useful when more control over async execution is needed, like: * * A task already have its thread and overlay should be visible until some callback is invoked (it should invoke * [CountDownLatch.countDown] or [Latch.release]) in order to unlock UI. Keep in mind that if [latch] is not released * and [timeout] is not set, overlay may never get removed. * * An overlay should be removed after some time, even if task is getting unresponsive (use [timeout] for this). * Keep in mind that this timeout applies to overlay only, not the latch itself. * * In addition to masking UI, you need an access to property indicating if background process is running; * [Latch.lockedProperty] serves exactly that purpose. * * More threads are involved in task execution. You can create a [CountDownLatch] for number of workers, call * [CountDownLatch.countDown] from each of them when it's done and overlay will stay visible until all workers finish * their jobs. * * @param latch an instance of [CountDownLatch], usage of [Latch] is recommended. * @param timeout timeout after which overlay will be removed anyway. Can be `null` (which means no timeout). * @param overlayNode optional custom overlay node. For best effect set transparency. * * # Example 1 * The simplest case: overlay is visible for two seconds - until latch release. Replace [Thread.sleep] with any * blocking action. Manual thread creation is for the sake of the example only. * * ```kotlin * val latch = Latch() * root.runAsyncWithOverlay(latch) ui { * //UI action * } * * Thread({ * Thread.sleep(2000) * latch.release() * }).start() * ``` * * # Example 2 * The latch won't be released until both workers are done. In addition, until workers are done, button will stay * disabled. New latch has to be created and rebound every time. * * ```kotlin * val latch = Latch(2) * root.runAsyncWithOverlay(latch) * button.disableWhen(latch.lockedProperty()) * runAsync(worker1.work(); latch.countDown()) * runAsync(worker2.work(); latch.countDown()) */ @JvmOverloads fun Node.runAsyncWithOverlay(latch: CountDownLatch, timeout: Duration? = null, overlayNode: Node = MaskPane()): Task<Boolean> { return if(timeout == null) { runAsyncWithOverlay(overlayNode) { latch.await(); true } } else { runAsyncWithOverlay(overlayNode) { latch.await(timeout.toMillis().toLong(), TimeUnit.MILLISECONDS) } } } /** * Runs given task in background thread, covering node with overlay (default one is [MaskPane]) until task is done. * * # Example * * ```kotlin * root.runAsyncWithOverlay { * Thread.sleep(2000) * } ui { * //UI action * } * ``` * * @param overlayNode optional custom overlay node. For best effect set transparency. */ @JvmOverloads fun <T : Any> Node.runAsyncWithOverlay(overlayNode: Node = MaskPane(), op: () -> T): Task<T> { val overlayContainer = stackpane { add(overlayNode) } replaceWith(overlayContainer) overlayContainer.children.add(0,this) return task { try { op() } finally { runLater { overlayContainer.replaceWith(this@runAsyncWithOverlay) } } } } /** * A basic mask pane, intended for blocking gui underneath. Styling example: * * ```css * .mask-pane { * -fx-background-color: rgba(0,0,0,0.5); * -fx-accent: aliceblue; * } * * .mask-pane > .progress-indicator { * -fx-max-width: 300; * -fx-max-height: 300; * } * ``` */ class MaskPane : BorderPane() { init { addClass("mask-pane") center = progressindicator() } override fun getUserAgentStylesheet() = MaskPane::class.java.getResource("maskpane.css").toExternalForm()!! } /** * Adds some superpowers to good old [CountDownLatch], like exposed [lockedProperty] or ability to release latch * immediately. * * All documentation of superclass applies here. Default behavior has not been altered. */ class Latch(count: Int) : CountDownLatch(count) { /** * Initializes latch with count of `1`, which means that the first invocation of [countDown] will allow all * waiting threads to proceed. */ constructor() : this(1) private val lockedProperty by lazy { ReadOnlyBooleanWrapper(locked) } /** * Locked state of this latch exposed as a property. Keep in mind that latch instance can be used only once, so * this property has to rebound every time. */ fun lockedProperty() : ReadOnlyBooleanProperty = lockedProperty.readOnlyProperty /** * Locked state of this latch. `true` if and only if [CountDownLatch.getCount] is greater than `0`. * Once latch is released it changes to `false` permanently. */ val locked get() = count > 0L /** * Releases latch immediately and allows waiting thread(s) to proceed. Can be safely used if this latch has been * initialized with `count` of `1`, should be used with care otherwise - [countDown] invocations ar preferred in * such cases. */ fun release() = (1..count).forEach { countDown() } //maybe not the prettiest way, but works fine override fun countDown() { super.countDown() lockedProperty.set(locked) } } class FXTimerTask(val op: () -> Unit, val timer: Timer) : TimerTask() { private val internalRunning = ReadOnlyBooleanWrapper(false) val runningProperty: ReadOnlyBooleanProperty get() = internalRunning.readOnlyProperty val running: Boolean get() = runningProperty.value private val internalCompleted = ReadOnlyBooleanWrapper(false) val completedProperty: ReadOnlyBooleanProperty get() = internalCompleted.readOnlyProperty val completed: Boolean get() = completedProperty.value override fun run() { internalRunning.value = true Platform.runLater { try { op() } finally { internalRunning.value = false internalCompleted.value = true } } } } class FXTask<T>(val status: TaskStatus? = null, val func: FXTask<*>.() -> T) : Task<T>() { private var internalCompleted = ReadOnlyBooleanWrapper(false) val completedProperty: ReadOnlyBooleanProperty get() = internalCompleted.readOnlyProperty val completed: Boolean get() = completedProperty.value override fun call() = func(this) init { status?.item = this } override fun succeeded() { internalCompleted.value = true } override fun failed() { internalCompleted.value = true } override fun cancelled() { internalCompleted.value = true } override public fun updateProgress(workDone: Long, max: Long) { super.updateProgress(workDone, max) } override public fun updateProgress(workDone: Double, max: Double) { super.updateProgress(workDone, max) } @Suppress("UNCHECKED_CAST") fun value(v: Any) { super.updateValue(v as T) } override public fun updateTitle(t: String?) { super.updateTitle(t) } override public fun updateMessage(m: String?) { super.updateMessage(m) } } open class TaskStatus : ItemViewModel<FXTask<*>>() { val running: ReadOnlyBooleanProperty = bind { SimpleBooleanProperty().apply { if (item != null) bind(item.runningProperty()) } } val completed: ReadOnlyBooleanProperty = bind { SimpleBooleanProperty().apply { if (item != null) bind(item.completedProperty) } } val message: ReadOnlyStringProperty = bind { SimpleStringProperty().apply { if (item != null) bind(item.messageProperty()) } } val title: ReadOnlyStringProperty = bind { SimpleStringProperty().apply { if (item != null) bind(item.titleProperty()) } } val progress: ReadOnlyDoubleProperty = bind { SimpleDoubleProperty().apply { if (item != null) bind(item.progressProperty()) } } }
src/main/java/tornadofx/Async.kt
2468943313
package org.rust.ide.inspections /** * Tests for Missing Else inspection. */ class RsMissingElseInspectionTest : RsInspectionsTestBase(RsMissingElseInspection()) { fun testSimple() = checkByText(""" fn main() { if true { }<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>true { } } """) fun testNoSpaces() = checkByText(""" fn main() { let a = 10; if true { }<warning descr="Suspicious if. Did you mean `else if`?">if</warning>(a > 10){ } } """) fun testWideSpaces() = checkByText(""" fn main() { let a = 10; if true { }<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>(a > 10) { } } """) fun testComments() = checkByText(""" fn main() { let a = 10; if true { }<warning descr="Suspicious if. Did you mean `else if`?"> /* commented */ /* else */ if </warning>a > 10 { } } """) fun testNotLastExpr() = checkByText(""" fn main() { let a = 10; if a > 5 { }<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>a > 10{ } let b = 20; } """) fun testHandlesBlocksWithNoSiblingsCorrectly() = checkByText(""" fn main() {if true {}} """) fun testNotAppliedWhenLineBreakExists() = checkByText(""" fn main() { if true {} if true {} } """) fun testNotAppliedWhenTheresNoSecondIf() = checkByText(""" fn main() { if { 92; } {} } """) fun testFix() = checkFixByText("Change to `else if`", """ fn main() { let a = 10; if a > 7 { }<warning descr="Suspicious if. Did you mean `else if`?"> i<caret>f </warning>a > 14 { } } """, """ fn main() { let a = 10; if a > 7 { } else if a > 14 { } } """) fun testFixPreservesComments() = checkFixByText("Change to `else if`", """ fn main() { let a = 10; if a > 7 { }<warning descr="Suspicious if. Did you mean `else if`?"> /* comment */<caret> if /* ! */ </warning>a > 14 { } } """, """ fn main() { let a = 10; if a > 7 { } /* comment */ else if /* ! */ a > 14 { } } """) }
src/test/kotlin/org/rust/ide/inspections/RsMissingElseInspectionTest.kt
481107275
package br.com.germanno.keural import br.com.germanno.keural.activation_functions.HyperbolicTangent import org.junit.Assert import org.junit.Test /** * @author Germanno Domingues - germanno.domingues@gmail.com * @since 1/30/17 3:10 AM */ class KeuralManagerTest { private val wordsDatabase = arrayOf( "banana", "sorteio", "carvalho", "montanha", "frasco" ) private val inputSize = wordsDatabase.maxBy { it.length }!!.length * 8 private val keuralManager by lazy { object : KeuralManager<String, String>( inputSize, wordsDatabase.size, activationFunction = HyperbolicTangent(), debugMode = true ) { override val inputToDoubleArray: (String) -> DoubleArray = { string -> val bitsInString = string.length * 8 val initialArray = DoubleArray(inputSize - bitsInString) { 0.0 } string.reversed().fold(initialArray) { array, c -> array + c.toBitArray() } } override val doubleArrayToOutput: (DoubleArray) -> String = { doubleArray -> with(doubleArray) { wordsDatabase[indexOf(max()!!)] } } override val outputToDoubleArray: (String) -> DoubleArray = { string -> wordsDatabase.map { if (it == string) 1.0 else 0.0 }.toDoubleArray() } }.apply { trainNetwork(wordsDatabase, wordsDatabase, 100000) } } @Test fun recognize() { val enteredWords = arrayOf( "batata", "sorvete", "carrasco", "montando", "frescor" ) enteredWords.forEachIndexed { i, s -> Assert.assertEquals(wordsDatabase[i], keuralManager.recognize(s)) } } }
src/test/kotlin/br/com/germanno/keural/KeuralManagerTest.kt
2719102152
class Outer() { class Nested(var i: Int) { fun test(): Int { this.i = 5 return this.i } } } fun nested_test_1(k: Int): Int { val j = Outer.Nested(k - 1) j.i = k return j.i } fun nested_test_2(k: Int): Int { val j = Outer.Nested(k - 1) return j.test() }
translator/src/test/kotlin/tests/nested_classes/nested_classes.kt
3874320737
package com.hewking.custom import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.util.Log import android.view.MotionEvent import android.view.View import com.hewking.custom.util.dp2px /** * 类的描述: * 创建人员:hewking * 创建时间:2018/3/16 * 修改人员:hewking * 修改时间:2018/3/16 * 修改备注: * Version: 1.0.0 */ class SectionSeekBar(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) { /** * 未选中的圆和线的颜色 */ private var mUnselectColor = 0 /** * 已选中的圆和半径 */ private var mSelectColor = 0 /** * 小圆的半径 */ private var mRadius = 0f /** * 选中的园的半径 */ private var mSelectRadius = 0f /** * 线的宽度 */ private var mLineWidth = 0f /** * 需要的section 数量 */ private var sectionCount = 0 /** * 当前选中的位置 */ private var mCurPosition = -1 /** * 是否支持拖动进度 */ private var canDrag = true private val mLinePaint by lazy { Paint().apply { isAntiAlias = true strokeWidth = mLineWidth style = Paint.Style.FILL color = mUnselectColor } } private val mSectionPaint by lazy { Paint().apply { isAntiAlias = true style = Paint.Style.FILL color = mUnselectColor } } private var mOnSectionChangeListener : OnSectionChangeListener? = null init { val attrs = ctx.obtainStyledAttributes(attrs, R.styleable.SectionSeekBar) mRadius = attrs.getDimensionPixelSize(R.styleable.SectionSeekBar_section_radius, dp2px(4f)).toFloat() mSelectRadius = attrs.getDimensionPixelSize(R.styleable.SectionSeekBar_section_select_radus, (mRadius * 1.5f).toInt()).toFloat() mSelectColor = attrs.getColor(R.styleable.SectionSeekBar_section_select_colorr, Color.BLUE) mUnselectColor = attrs.getColor(R.styleable.SectionSeekBar_section_unselect_colro, Color.GRAY) sectionCount = attrs.getInteger(R.styleable.SectionSeekBar_section_section_count, 5) mCurPosition = attrs.getInteger(R.styleable.SectionSeekBar_section_cur_position, 0) mLineWidth = attrs.getDimensionPixelSize(R.styleable.SectionSeekBar_section_line_width, dp2px(1f)).toFloat() attrs.recycle() // 初始化画笔 mLinePaint mSectionPaint if (BuildConfig.DEBUG) { mOnSectionChangeListener = object : OnSectionChangeListener{ override fun onCurrentSectionChange(curPos: Int, oldPos: Int) { Log.d(SectionSeekBar::class.java.simpleName,"curPos : ${curPos} oldPos : ${oldPos}") } } } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSpecSize = MeasureSpec.getSize(heightMeasureSpec) if (heightMode == MeasureSpec.AT_MOST) { val mHeight = paddingTop + paddingBottom + 2 * mSelectRadius setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mHeight.toInt()) } } private var mLastX = 0f override fun onTouchEvent(event: MotionEvent?): Boolean { if (canDrag) { when(event?.action) { MotionEvent.ACTION_DOWN -> { mLastX = event?.x } MotionEvent.ACTION_MOVE -> { mLastX = event?.x invalidate() } MotionEvent.ACTION_UP -> { /** * 计算当前 up 事件所在的点 */ mLastX = calcDstX(event?.x) // 动画过渡 增强体验 smoothToTarget(event?.x,mLastX) // invalidate() } } return true } else { return super.onTouchEvent(event) } } private fun smoothToTarget(x: Float, lastX: Float) { ValueAnimator.ofFloat(x,lastX) .apply { duration = 300 addUpdateListener { mLastX = (it.animatedValue as Float) postInvalidateOnAnimation() } start() } } override fun onDetachedFromWindow() { super.onDetachedFromWindow() // 取消动画 } /** * 计算当前点 x 坐标 距离 那个section 坐标绝对值最近 并返回 * section 点 圆心 x坐标 */ private fun calcDstX(x: Float): Float { val maxX = width - paddingRight - mSelectRadius val minX = paddingLeft + mSelectRadius val targetX = Math.max(minX,Math.min(x,maxX)) val sectionWidth = (width - paddingLeft - paddingRight - 2 * mSelectRadius) / (sectionCount - 1) val sectionRound = Math.round((targetX - minX) / sectionWidth) Log.d(SectionSeekBar::class.java.simpleName,"sectionRound : ${sectionRound} sectionWidth : ${sectionWidth} targetX : ${targetX}") val calcX = Math.min(sectionWidth * sectionRound + minX,maxX) val oldPos = mCurPosition // 判断是否当前section选中改变 mCurPosition = (calcX / sectionWidth).toInt() if (oldPos != mCurPosition) { mOnSectionChangeListener?.onCurrentSectionChange(mCurPosition,oldPos) } return calcX } override fun onDraw(canvas: Canvas?) { drawBg(canvas) drawSection(canvas) drawProgress(canvas) } /** * 画圆圈 */ private fun drawSection(canvas: Canvas?) { val sectionWidth = (width - paddingLeft - paddingRight - 2 * mSelectRadius) / (sectionCount - 1) val cy = paddingTop.toFloat() + mSelectRadius var cx = 0f var startX = paddingLeft.toFloat() + mSelectRadius for (index in 0..sectionCount - 1) { cx = index * sectionWidth.toFloat() + startX if (cx <= mLastX) { mSectionPaint.color = mSelectColor } else { mSectionPaint.color = mUnselectColor } canvas?.drawCircle(cx, cy, mRadius, mSectionPaint) } } /** * 画进度 */ private fun drawProgress(canvas: Canvas?) { mLinePaint.color = mSelectColor val maxX = width - paddingRight - mSelectRadius val minX = paddingLeft + mSelectRadius val targetX = Math.max(minX,Math.min(mLastX,maxX)) val rect = RectF(minX, paddingTop + mSelectRadius, targetX, paddingTop + mSelectRadius + mLineWidth) canvas?.drawRect(rect, mLinePaint) val cy = paddingTop.toFloat() + mSelectRadius // 绘制当前进度所在的园 if (mLastX >= minX) { mSectionPaint.color = mSelectColor canvas?.drawCircle(targetX,cy,mSelectRadius,mSectionPaint) } Log.d(SectionSeekBar::class.java.simpleName,"mLastx : ${mLastX}") } /** * 画默认进度条 */ private fun drawBg(canvas: Canvas?) { mLinePaint.color = mUnselectColor val rect = RectF(paddingLeft + mSelectRadius, paddingTop + mSelectRadius, width - paddingRight - mSelectRadius, paddingTop + mSelectRadius + mLineWidth) canvas?.drawRect(rect, mLinePaint) } interface OnSectionChangeListener{ fun onCurrentSectionChange(curPos : Int, oldPos : Int) } }
app/src/main/java/com/hewking/custom/SectionSeekBar.kt
3841883910
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.toml import com.intellij.codeInsight.completion.InsertHandler import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElement import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiTreeUtil import org.toml.lang.psi.TomlElementTypes import org.toml.lang.psi.TomlKeyValue import org.toml.lang.psi.TomlLiteral import org.toml.lang.psi.TomlValue import org.toml.lang.psi.ext.elementType /** Inserts `=` between key and value if missed and wraps inserted string with quotes if needed */ class TomlStringValueInsertionHandler(private val keyValue: TomlKeyValue) : InsertHandler<LookupElement> { override fun handleInsert(context: InsertionContext, item: LookupElement) { var startOffset = context.startOffset val value = context.getElementOfType<TomlValue>() val hasEq = keyValue.children.any { it.elementType == TomlElementTypes.EQ } val hasQuotes = value != null && (value !is TomlLiteral || value.firstChild.elementType != TomlElementTypes.NUMBER) if (!hasEq) { context.document.insertString(startOffset - if (hasQuotes) 1 else 0, "= ") PsiDocumentManager.getInstance(context.project).commitDocument(context.document) startOffset += 2 } if (!hasQuotes) { context.document.insertString(startOffset, "\"") context.document.insertString(context.selectionEndOffset, "\"") } } } inline fun <reified T : PsiElement> InsertionContext.getElementOfType(strict: Boolean = false): T? = PsiTreeUtil.findElementOfClassAtOffset(file, tailOffset - 1, T::class.java, strict)
src/main/kotlin/toml/TomlStringValueInsertionHandler.kt
1469252960
package com.engineer.imitate.ui.fragments.di import dagger.Component import dagger.Module import dagger.Provides import javax.inject.Inject @Component(modules = [NetworkModule::class]) interface ApplicationComponent { fun inject(diFragment: DIFragment) } class LoginViewModel @Inject constructor( private val userRepository: UserRepository ) { fun request(block: (String) -> Unit) { block(userRepository.getData()) } } // @Module informs Dagger that this class is a Dagger Module @Module class NetworkModule { // @Provides tell Dagger how to create instances of the type that this function // returns (i.e. LoginRetrofitService). // Function parameters are the dependencies of this type. @Provides fun provideLoginRetrofitService(): LoginRetrofitService { // Whenever Dagger needs to provide an instance of type LoginRetrofitService, // this code (the one inside the @Provides method) is run. // return Retrofit.Builder() // .baseUrl("https://example.com") // .build() // .create(LoginService::class.java) return object : LoginService { override fun provideData(): String { return "I came from dagger" } } } } // ///************************************************************************************/ open interface LoginRetrofitService { fun provideData(): String } interface LoginService : LoginRetrofitService { } // @Inject lets Dagger know how to create instances of these objects class UserLocalDataSource @Inject constructor() {} class UserRemoteDataSource @Inject constructor(private val loginService: LoginRetrofitService) { fun getData(): String { return loginService.provideData() } } // @Inject lets Dagger know how to create instances of this object class UserRepository @Inject constructor( private val localDataSource: UserLocalDataSource, private val remoteDataSource: UserRemoteDataSource ) { fun getData(): String { return remoteDataSource.getData() } } // // @Component makes Dagger create a graph of dependencies @Component(modules = [NetworkModule::class]) interface ApplicationGraph { // The return type of functions inside the component interface is // what can be provided from the container fun repository(): UserRepository }
imitate/src/main/java/com/engineer/imitate/ui/fragments/di/DaggerHelper.kt
3644935917
package de.axelrindle.broadcaster.model import de.axelrindle.broadcaster.plugin import org.bukkit.configuration.ConfigurationSection import java.io.File import java.util.* /** * Utility class for mapping entries in the `messages.yml` file to [Message] objects. */ object MessageMapper { /** * Defines supported types of messages that are not of type [String]. */ private enum class ExtraSupportedMessageTypes { JSON } /** * Tries to map an entry from the `messages.yml` file. * * @param entry The entry object from [ConfigurationSection.getList] */ fun mapConfigEntry(entry: Any?): Message? { return when (entry) { is String -> SimpleMessage(entry) is LinkedHashMap<*, *> -> mapEntryPerType(entry) else -> null } } /** * Maps config entries that are not plain string entries. For a list of supported types * see [ExtraSupportedMessageTypes]. * * @param entry A [LinkedHashMap] defining the `Type` and the `Definition` file. */ private fun mapEntryPerType(entry: LinkedHashMap<*, *>): Message? { if (entry.containsKey("Type").not() || entry.containsKey("Definition").not()) { plugin.logger.warning("Invalid message definition found! ($entry)") } val type = entry["Type"].toString().uppercase(Locale.ENGLISH) val definitionFile = entry["Definition"].toString() // check for supported message type try { when (ExtraSupportedMessageTypes.valueOf(type)) { ExtraSupportedMessageTypes.JSON -> { val content = File(plugin.dataFolder, "json/$definitionFile.json").readText() return JsonMessage(content) } } } catch (e: ClassNotFoundException) { plugin.logger.warning("Please make sure you're using Spigot or a fork of it!") } catch (e: IllegalArgumentException) { plugin.logger.warning("Invalid message type \"$type\"! " + "Currently only \"${ExtraSupportedMessageTypes.values().joinToString(", ")}\" are supported.") } catch (e: NullPointerException) { plugin.logger.warning("Unsupported message definition in \"json/$definitionFile.json\"! " + "Make sure your Spigot version is compatible.") } return null } }
src/main/kotlin/de/axelrindle/broadcaster/model/MessageMapper.kt
2255413066
package com.natpryce.hamkrest.assertion import com.natpryce.hamkrest.equalTo import com.natpryce.hamkrest.matches import org.junit.Test import kotlin.text.RegexOption.DOT_MATCHES_ALL import kotlin.text.RegexOption.MULTILINE class AssertOutput { @Test fun produces_ide_friendly_error_message() { try { assertThat("foo", equalTo("bar")) } catch (e: AssertionError) { assertThat(e.message!!, matches(Regex("expected: .*but was: .*", setOf(MULTILINE, DOT_MATCHES_ALL)))) } } }
src/test/kotlin/com/natpryce/hamkrest/assertion/assert_tests.kt
3113406097
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko import android.view.* import java.util.* inline fun ViewGroup.forEachChild(f: (View) -> Unit) { for (i in 0..childCount - 1) { f(getChildAt(i)) } } inline fun ViewGroup.forEachChildWithIndex(f: (Int, View) -> Unit) { for (i in 0..childCount - 1) { f(i, getChildAt(i)) } } inline fun ViewGroup.firstChild(predicate: (View) -> Boolean): View { for (i in 0..childCount - 1) { val child = getChildAt(i) if (predicate(child)) { return child } } throw NoSuchElementException("No element matching predicate was found.") } inline fun ViewGroup.firstChildOrNull(predicate: (View) -> Boolean): View? { for (i in 0..childCount - 1) { val child = getChildAt(i) if (predicate(child)) { return child } } return null } fun View.childrenSequence(): Sequence<View> = ViewChildrenSequence(this) fun View.childrenRecursiveSequence(): Sequence<View> = ViewChildrenRecursiveSequence(this) private class ViewChildrenSequence(private val view: View) : Sequence<View> { override fun iterator(): Iterator<View> { if (view !is ViewGroup) return emptyList<View>().iterator() return ViewIterator(view) } private class ViewIterator(private val view: ViewGroup) : Iterator<View> { private var index = 0 private val count = view.childCount override fun next(): View { if (!hasNext()) throw NoSuchElementException() return view.getChildAt(index++) } override fun hasNext(): Boolean { checkCount() return index < count } private fun checkCount() { if (count != view.childCount) throw ConcurrentModificationException() } } } private class ViewChildrenRecursiveSequence(private val view: View) : Sequence<View> { override fun iterator() = RecursiveViewIterator(view) private class RecursiveViewIterator(private val view: View) : Iterator<View> { private val sequences = arrayListOf(sequenceOf(view)) private var itemIterator: Iterator<View>? = null override fun next(): View { initItemIterator() val iterator = itemIterator ?: throw NoSuchElementException() val view = iterator.next() if (view is ViewGroup && view.childCount > 0) { sequences.add(view.childrenSequence()) } return view } override fun hasNext(): Boolean { initItemIterator() val iterator = itemIterator ?: return false return iterator.hasNext() } private fun initItemIterator() { val seqs = sequences val iterator = itemIterator if (iterator == null || (!iterator.hasNext() && seqs.isNotEmpty())) { itemIterator = seqs.removeLast()?.iterator() } else { itemIterator = null } } @Suppress("NOTHING_TO_INLINE") private inline fun <T: Any> MutableList<T>.removeLast(): T? { if (isEmpty()) return null return removeAt(size - 1) } } }
dsl/static/src/common/viewChildrenSequences.kt
2038759173
/* * 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.example.healthconnectsample.presentation.navigation import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.healthconnectsample.presentation.theme.HealthConnectTheme /** * An item in the side navigation drawer. */ @Composable fun DrawerItem( item: Screen, selected: Boolean, onItemClick: (Screen) -> Unit ) { Row( modifier = Modifier .fillMaxWidth() .clickable(onClick = { onItemClick(item) }) .height(48.dp) .padding(start = 16.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = stringResource(item.titleId), style = MaterialTheme.typography.h5, color = if (selected) { MaterialTheme.colors.primary } else { MaterialTheme.colors.onBackground } ) } } @Preview @Composable fun DrawerItemPreview() { HealthConnectTheme { DrawerItem( item = Screen.ExerciseSessions, selected = true, onItemClick = {} ) } }
health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/navigation/DrawerItem.kt
3076515508
package org.wikipedia.page import org.wikipedia.dataclient.WikiSite import org.wikipedia.language.AppLanguageLookUpTable import org.wikipedia.model.EnumCode import org.wikipedia.model.EnumCodeMap import org.wikipedia.staticdata.* import java.util.* /** An enumeration describing the different possible namespace codes. Do not attempt to use this * class to preserve URL path information such as Talk: or User: or localization. * @see [Wikipedia:Namespace](https://en.wikipedia.org/wiki/Wikipedia:Namespace) * @see [Extension default namespaces](https://www.mediawiki.org/wiki/Extension_default_namespaces) * @see [Manual:Namespace](https://www.mediawiki.org/wiki/Manual:Namespace.Built-in_namespaces) * @see [Namespaces reported by API](https://en.wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespaces|namespacealiases) */ @Suppress("unused") enum class Namespace(private val code: Int) : EnumCode { MEDIA(-2), SPECIAL(-1) { override fun talk(): Boolean { return false } }, MAIN(0), TALK(1), USER(2), USER_TALK(3), PROJECT(4), PROJECT_TALK(5), FILE(6), FILE_TALK(7), MEDIAWIKI(8), MEDIAWIKI_TALK(9), TEMPLATE(10), TEMPLATE_TALK(11), HELP(12), HELP_TALK(13), CATEGORY(14), CATEGORY_TALK(15), THREAD(90), THREAD_TALK(91), SUMMARY(92), SUMMARY_TALK(93), PORTAL(100), PORTAL_TALK(101), PROPERTY(102), PROPERTY_TALK(103), TYPE(104), TYPE_TALK(105), FORM(106), FORM_TALK(107), BOOK(108), BOOK_TALK(109), FORUM(110), FORUM_TALK(111), DRAFT(118), DRAFT_TALK(119), USER_GROUP(160), ACL(162), FILTER(170), FILTER_TALK(171), USER_WIKI(200), USER_WIKI_TALK(201), USER_PROFILE(202), USER_PROFILE_TALK(203), ANNOTATION(248), ANNOTATION_TALK(249), PAGE(250), PAGE_TALK(251), INDEX(252), INDEX_TALK(253), MATH(262), MATH_TALK(263), WIDGET(274), WIDGET_TALK(275), JS_APPLET(280), JS_APPLET_TALK(281), POLL(300), POLL_TALK(301), COURSE(350), COURSE_TALK(351), MAPS_LAYER(420), MAPS_LAYER_TALK(421), QUIZ(430), QUIZ_TALK(431), EDUCATION_PROGRAM(446), EDUCATION_PROGRAM_TALK(447), BOILERPLATE(450), BOILERPLATE_TALK(451), CAMPAIGN(460), CAMPAIGN_TALK(461), SCHEMA(470), SCHEMA_TALK(471), JSON_CONFIG(482), JSON_CONFIG_TALK(483), GRAPH(484), GRAPH_TALK(485), JSON_DATA(486), JSON_DATA_TALK(487), NOVA_RESOURCE(488), NOVA_RESOURCE_TALK(489), GW_TOOLSET(490), GW_TOOLSET_TALK(491), BLOG(500), BLOG_TALK(501), USER_BOX(600), USER_BOX_TALK(601), LINK(700), LINK_TALK(701), TIMED_TEXT(710), TIMED_TEXT_TALK(711), GIT_ACCESS_ROOT(730), GIT_ACCESS_ROOT_TALK(731), INTERPRETATION(800), INTERPRETATION_TALK(801), MUSTACHE(806), MUSTACHE_TALK(807), JADE(810), JADE_TALK(811), R(814), R_TALK(815), MODULE(828), MODULE_TALK(829), SECURE_POLL(830), SECURE_POLL_TALK(831), COMMENT_STREAM(844), COMMENT_STREAM_TALK(845), CN_BANNER(866), CN_BANNER_TALK(867), GRAM(1024), GRAM_TALK(1025), TRANSLATIONS(1198), TRANSLATIONS_TALK(1199), GADGET(2300), GADGET_TALK(2301), GADGET_DEFINITION(2302), GADGET_DEFINITION_TALK(2303), TOPIC(2600); override fun code(): Int { return code } fun special(): Boolean { return this === SPECIAL } fun user(): Boolean { return this === USER } fun userTalk(): Boolean { return this === USER_TALK } fun main(): Boolean { return this === MAIN } fun file(): Boolean { return this === FILE } open fun talk(): Boolean { return code and TALK_MASK == TALK_MASK } companion object { private const val TALK_MASK = 0x1 private val MAP = EnumCodeMap(Namespace::class.java) @JvmStatic fun fromLegacyString(wiki: WikiSite, name: String?): Namespace { if (FileAliasData.valueFor(wiki.languageCode).equals(name, true) || FileAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) { return FILE } if (SpecialAliasData.valueFor(wiki.languageCode).equals(name, true) || SpecialAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) { return SPECIAL } if (TalkAliasData.valueFor(wiki.languageCode).equals(name, true) || TalkAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) { return TALK } if (UserAliasData.valueFor(wiki.languageCode).equals(name, true) || UserAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) { return USER } return if (UserTalkAliasData.valueFor(wiki.languageCode).equals(name, true) || UserTalkAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) { USER_TALK } else MAIN } @JvmStatic fun of(code: Int): Namespace { return MAP[code] } } }
app/src/main/java/org/wikipedia/page/Namespace.kt
3630226529
package org.wikipedia.edit.richtext import android.text.TextPaint import android.text.style.MetricAffectingSpan class SuperscriptSpanEx(override var start: Int, override var syntaxRule: SyntaxRule) : MetricAffectingSpan(), SpanExtents { override var end = 0 override fun updateDrawState(tp: TextPaint) { tp.textSize = tp.textSize * 0.8f tp.baselineShift += (tp.ascent() / 4).toInt() } override fun updateMeasureState(tp: TextPaint) { tp.textSize = tp.textSize * 0.8f tp.baselineShift += (tp.ascent() / 4).toInt() } }
app/src/main/java/org/wikipedia/edit/richtext/SuperscriptSpanEx.kt
708503758
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <mail@vanit.as> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.adapter import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import com.bumptech.glide.RequestManager import org.mariotaku.kpreferences.get import org.mariotaku.ktextension.contains import de.vanita5.twittnuker.R import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter.Companion.ITEM_VIEW_TYPE_LOAD_INDICATOR import de.vanita5.twittnuker.adapter.iface.IUserListsAdapter import de.vanita5.twittnuker.constant.nameFirstKey import de.vanita5.twittnuker.model.ParcelableUserList import de.vanita5.twittnuker.view.holder.LoadIndicatorViewHolder import de.vanita5.twittnuker.view.holder.UserListViewHolder class ParcelableUserListsAdapter( context: Context, requestManager: RequestManager ) : LoadMoreSupportAdapter<RecyclerView.ViewHolder>(context, requestManager), IUserListsAdapter<List<ParcelableUserList>> { override val showAccountsColor: Boolean = false override val nameFirst: Boolean = preferences[nameFirstKey] override var userListClickListener: IUserListsAdapter.UserListClickListener? = null private val inflater: LayoutInflater = LayoutInflater.from(context) private var data: List<ParcelableUserList>? = null fun getData(): List<ParcelableUserList>? { return data } override fun setData(data: List<ParcelableUserList>?): Boolean { this.data = data notifyDataSetChanged() return true } private fun bindUserList(holder: UserListViewHolder, position: Int) { holder.display(getUserList(position)!!) } override fun getItemCount(): Int { val position = loadMoreIndicatorPosition var count = userListsCount if (position and ILoadMoreSupportAdapter.START != 0L) { count++ } if (position and ILoadMoreSupportAdapter.END != 0L) { count++ } return count } override fun getUserList(position: Int): ParcelableUserList? { if (position == userListsCount) return null return data!![position] } override fun getUserListId(position: Int): String? { if (position == userListsCount) return null return data!![position].id } override val userListsCount: Int get() { if (data == null) return 0 return data!!.size } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { when (viewType) { ITEM_VIEW_TYPE_USER_LIST -> { return createUserListViewHolder(this, inflater, parent) } ITEM_VIEW_TYPE_LOAD_INDICATOR -> { val view = inflater.inflate(R.layout.list_item_load_indicator, parent, false) return LoadIndicatorViewHolder(view) } } throw IllegalStateException("Unknown view type " + viewType) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder.itemViewType) { ITEM_VIEW_TYPE_USER_LIST -> { bindUserList(holder as UserListViewHolder, position) } } } override fun getItemViewType(position: Int): Int { if (position == 0 && ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition) { return ITEM_VIEW_TYPE_LOAD_INDICATOR } if (position == userListsCount) { return ITEM_VIEW_TYPE_LOAD_INDICATOR } return ITEM_VIEW_TYPE_USER_LIST } companion object { val ITEM_VIEW_TYPE_USER_LIST = 2 fun createUserListViewHolder(adapter: IUserListsAdapter<*>, inflater: LayoutInflater, parent: ViewGroup): UserListViewHolder { val view = inflater.inflate(R.layout.list_item_user_list, parent, false) val holder = UserListViewHolder(view, adapter) holder.setOnClickListeners() holder.setupViewOptions() return holder } } }
twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/ParcelableUserListsAdapter.kt
653332580
package com.popalay.cardme.utils.extensions import android.arch.lifecycle.ViewModelProvider import android.arch.lifecycle.ViewModelProviders import android.content.ComponentName import android.content.Context import android.content.Intent import android.databinding.DataBindingUtil import android.databinding.ViewDataBinding import android.net.Uri import android.nfc.NdefMessage import android.nfc.NdefRecord import android.support.annotation.LayoutRes import android.support.annotation.StringRes import android.support.customtabs.CustomTabsIntent import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.support.v4.app.ShareCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AppCompatActivity import android.view.LayoutInflater import android.view.ViewGroup import com.popalay.cardme.R import com.popalay.cardme.presentation.base.BaseViewModel fun FragmentActivity.currentFragment() = supportFragmentManager.fragments?.filter { it.isVisible }?.firstOrNull() inline fun <reified T : Fragment> AppCompatActivity.findFragmentByType() = supportFragmentManager.fragments ?.filter { it is T } ?.map { it as T } ?.firstOrNull() fun FragmentActivity.openShareChooser(@StringRes title: Int, text: String) { val intent = ShareCompat.IntentBuilder.from(this) .setChooserTitle(title) .setType("text/plain") .setText(text) .createChooserIntent() if (intent.resolveActivity(this.packageManager) != null) { this.startActivity(intent) } } fun FragmentActivity.shareUsingNfc(@StringRes title: Int, text: String) { val targetShareIntents = mutableListOf<Intent>() val shareIntent = Intent() shareIntent.action = Intent.ACTION_SEND shareIntent.type = "text/plain" val resInfos = packageManager.queryIntentActivities(shareIntent, 0) if (!resInfos.isEmpty()) { for (resInfo in resInfos) { val packageName = resInfo.activityInfo.packageName if (packageName.contains("nfc")) { val intent = Intent() intent.component = ComponentName(packageName, resInfo.activityInfo.name) intent.action = Intent.ACTION_SEND intent.type = "text/plain" intent.putExtra(Intent.EXTRA_TEXT, text) intent.`package` = packageName targetShareIntents.add(intent) } } if (!targetShareIntents.isEmpty()) { val chooserIntent = Intent.createChooser(targetShareIntents.removeAt(0), getString(title)) chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetShareIntents.toTypedArray()) startActivity(chooserIntent) } } } fun <T : ViewDataBinding> FragmentActivity.getDataBinding(@LayoutRes layoutId: Int ): T = DataBindingUtil.setContentView<T>(this, layoutId) fun <T : ViewDataBinding> Fragment.getDataBinding( inflater: LayoutInflater?, @LayoutRes layoutId: Int, container: ViewGroup? ): T = DataBindingUtil.inflate(inflater, layoutId, container, false) inline fun <reified T : BaseViewModel> FragmentActivity.getViewModel( factory: ViewModelProvider.Factory = ViewModelProviders.DefaultFactory(application) ): T = ViewModelProviders.of(this, factory).get(T::class.java) inline fun <reified T : BaseViewModel> Fragment.getViewModel( factory: ViewModelProvider.Factory = ViewModelProviders.DefaultFactory(activity.application) ): T = ViewModelProviders.of(this, factory).get(T::class.java) fun Context.createNdefMessage(byteArray: ByteArray): NdefMessage { return NdefMessage(arrayOf(NdefRecord.createMime("application/" + packageName, byteArray), NdefRecord.createApplicationRecord(packageName))) } fun Fragment.openShareChooser(@StringRes title: Int, text: String) = activity.openShareChooser(title, text) fun Context.openLink(url: Uri) { val builder = CustomTabsIntent.Builder() builder.setToolbarColor(ContextCompat.getColor(this, R.color.primary)) val customTabsIntent = builder.build() customTabsIntent.launchUrl(this, url) } fun Context.openLink(url: String) = openLink(Uri.parse(url)) fun Boolean.ifTrue(block: () -> Unit) { if (this) { block() } } fun Boolean.ifFalse(block: () -> Unit) { if (!this) { block() } }
presentation/src/main/kotlin/com/popalay/cardme/utils/extensions/CommonExt.kt
780338871
package com.stripe.android.paymentsheet.utils import com.stripe.android.paymentsheet.forms.PaymentMethodRequirements import com.stripe.android.ui.core.R import com.stripe.android.ui.core.elements.LayoutSpec import com.stripe.android.ui.core.forms.resources.LpmRepository object MockPaymentMethodsFactory { fun create(): List<LpmRepository.SupportedPaymentMethod> { return listOf( mockPaymentMethod( code = "card", displayNameResource = R.string.stripe_paymentsheet_payment_method_card, iconResource = R.drawable.stripe_ic_paymentsheet_pm_card, tintIconOnSelection = true ), mockPaymentMethod( code = "klarna", displayNameResource = R.string.stripe_paymentsheet_payment_method_klarna, iconResource = R.drawable.stripe_ic_paymentsheet_pm_klarna ), mockPaymentMethod( code = "affirm", displayNameResource = R.string.stripe_paymentsheet_payment_method_affirm, iconResource = R.drawable.stripe_ic_paymentsheet_pm_affirm ), mockPaymentMethod( code = "paypal", displayNameResource = R.string.stripe_paymentsheet_payment_method_paypal, iconResource = R.drawable.stripe_ic_paymentsheet_pm_paypal ) ) } private fun mockPaymentMethod( code: String, displayNameResource: Int, iconResource: Int, tintIconOnSelection: Boolean = false ): LpmRepository.SupportedPaymentMethod { return LpmRepository.SupportedPaymentMethod( code, requiresMandate = false, displayNameResource = displayNameResource, iconResource = iconResource, tintIconOnSelection = tintIconOnSelection, requirement = PaymentMethodRequirements( piRequirements = emptySet(), siRequirements = emptySet(), confirmPMFromCustomer = true ), formSpec = LayoutSpec(items = emptyList()) ) } }
paymentsheet/src/androidTest/java/com/stripe/android/paymentsheet/utils/MockPaymentMethodsFactory.kt
1155941290
/** * ownCloud Android client application * * @author masensio * @author David A. Velasco * @author Christian Schabesberger * @author David González Verdugo * Copyright (C) 2020 ownCloud GmbH. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>. */ package com.owncloud.android.presentation.ui.sharing.fragments import android.accounts.Account import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.CheckBox import android.widget.CompoundButton import androidx.appcompat.widget.SwitchCompat import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import com.owncloud.android.R import com.owncloud.android.databinding.EditShareLayoutBinding import com.owncloud.android.datamodel.OCFile import com.owncloud.android.domain.sharing.shares.model.OCShare import com.owncloud.android.domain.sharing.shares.model.ShareType import com.owncloud.android.domain.utils.Event.EventObserver import com.owncloud.android.extensions.parseError import com.owncloud.android.lib.resources.shares.RemoteShare import com.owncloud.android.lib.resources.shares.SharePermissionsBuilder import com.owncloud.android.presentation.UIResult import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel import com.owncloud.android.utils.PreferenceUtils import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.core.parameter.parametersOf import timber.log.Timber /** * Required empty public constructor */ class EditPrivateShareFragment : DialogFragment() { /** Share to show & edit, received as a parameter in construction time */ private var share: OCShare? = null /** File bound to share, received as a parameter in construction time */ private var file: OCFile? = null /** OC account holding the shared file, received as a parameter in construction time */ private var account: Account? = null /** * Reference to parent listener */ private var listener: ShareFragmentListener? = null /** Listener for changes on privilege checkboxes */ private var onPrivilegeChangeListener: CompoundButton.OnCheckedChangeListener? = null private val ocShareViewModel: OCShareViewModel by viewModel { parametersOf( file?.remotePath, account?.name ) } private var _binding: EditShareLayoutBinding? = null private val binding get() = _binding!! /** * {@inheritDoc} */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Timber.v("onCreate") if (arguments != null) { file = arguments?.getParcelable(ARG_FILE) account = arguments?.getParcelable(ARG_ACCOUNT) share = savedInstanceState?.getParcelable(ARG_SHARE) ?: arguments?.getParcelable(ARG_SHARE) Timber.d("Share has id ${share?.id} remoteId ${share?.remoteId}") } setStyle(STYLE_NO_TITLE, 0) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) Timber.v("onActivityCreated") // To observe the changes in a just updated share refreshPrivateShare(share?.remoteId!!) observePrivateShareToEdit() observePrivateShareEdition() } /** * {@inheritDoc} */ override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = EditShareLayoutBinding.inflate(inflater, container, false) return binding.root.apply { // Allow or disallow touches with other visible windows filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(context) } } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding.editShareTitle.text = resources.getString(R.string.share_with_edit_title, share?.sharedWithDisplayName) // Setup layout refreshUiFromState() binding.closeButton.setOnClickListener { dismiss() } } override fun onAttach(context: Context) { super.onAttach(context) try { listener = activity as ShareFragmentListener? } catch (e: IllegalStateException) { throw IllegalStateException(requireActivity().toString() + " must implement OnShareFragmentInteractionListener") } } override fun onDetach() { super.onDetach() listener = null } /** * Updates the UI with the current permissions in the edited [RemoteShare] * */ private fun refreshUiFromState() { setPermissionsListening(false) val sharePermissions = share!!.permissions binding.canShareSwitch.isChecked = sharePermissions and RemoteShare.SHARE_PERMISSION_FLAG > 0 val anyUpdatePermission = RemoteShare.CREATE_PERMISSION_FLAG or RemoteShare.UPDATE_PERMISSION_FLAG or RemoteShare.DELETE_PERMISSION_FLAG val canEdit = sharePermissions and anyUpdatePermission > 0 binding.canEditSwitch.isChecked = canEdit if (file?.isFolder == true) { /// TODO change areEditOptionsAvailable in order to delete !isFederated // from checking when iOS is ready binding.canEditCreateCheckBox.apply { isChecked = sharePermissions and RemoteShare.CREATE_PERMISSION_FLAG > 0 isVisible = canEdit } binding.canEditChangeCheckBox.apply { isChecked = sharePermissions and RemoteShare.UPDATE_PERMISSION_FLAG > 0 isVisible = canEdit } binding.canEditDeleteCheckBox.apply { isChecked = sharePermissions and RemoteShare.DELETE_PERMISSION_FLAG > 0 isVisible = canEdit } } setPermissionsListening(true) } /** * Binds or unbinds listener for user actions to enable or disable a permission on the edited share * to the views receiving the user events. * * @param enable When 'true', listener is bound to view; when 'false', it is unbound. */ private fun setPermissionsListening(enable: Boolean) { if (enable && onPrivilegeChangeListener == null) { onPrivilegeChangeListener = OnPrivilegeChangeListener() } val changeListener = if (enable) onPrivilegeChangeListener else null binding.canShareSwitch.setOnCheckedChangeListener(changeListener) binding.canEditSwitch.setOnCheckedChangeListener(changeListener) if (file?.isFolder == true) { binding.canEditCreateCheckBox.setOnCheckedChangeListener(changeListener) binding.canEditChangeCheckBox.setOnCheckedChangeListener(changeListener) binding.canEditDeleteCheckBox.setOnCheckedChangeListener(changeListener) } } /** * Listener for user actions that enable or disable a privilege */ private inner class OnPrivilegeChangeListener : CompoundButton.OnCheckedChangeListener { /** * Called by every [SwitchCompat] and [CheckBox] in the fragment to update * the state of its associated permission. * * @param compound [CompoundButton] toggled by the user * @param isChecked New switch state. */ override fun onCheckedChanged(compound: CompoundButton, isChecked: Boolean) { if (!isResumed) { // very important, setCheched(...) is called automatically during // Fragment recreation on device rotations return } /// else, getView() cannot be NULL var subordinate: CompoundButton when (compound.id) { R.id.canShareSwitch -> { Timber.v("canShareCheckBox toggled to $isChecked") updatePermissionsToShare() } R.id.canEditSwitch -> { Timber.v("canEditCheckBox toggled to $isChecked") /// sync subordinate CheckBoxes val isFederated = share?.shareType == ShareType.FEDERATED if (file?.isFolder == true) { if (isChecked) { if (!isFederated) { /// not federated shares -> enable all the subpermisions for (i in sSubordinateCheckBoxIds.indices) { //noinspection ConstantConditions, prevented in the method beginning subordinate = view!!.findViewById(sSubordinateCheckBoxIds[i]) if (!isFederated) { // TODO delete when iOS is ready subordinate.visibility = View.VISIBLE } if (!subordinate.isChecked && !file!!.isSharedWithMe) { // see (1) toggleDisablingListener(subordinate) } } } else { /// federated share -> enable delete subpermission, as server side; TODO why? //noinspection ConstantConditions, prevented in the method beginning subordinate = binding.canEditDeleteCheckBox if (!subordinate.isChecked) { toggleDisablingListener(subordinate) } } } else { for (i in sSubordinateCheckBoxIds.indices) { //noinspection ConstantConditions, prevented in the method beginning subordinate = view!!.findViewById(sSubordinateCheckBoxIds[i]) subordinate.visibility = View.GONE if (subordinate.isChecked) { toggleDisablingListener(subordinate) } } } } if (!(file?.isFolder == true && isChecked && file?.isSharedWithMe == true) || // see (1) isFederated ) { updatePermissionsToShare() } } R.id.canEditCreateCheckBox -> { Timber.v("canEditCreateCheckBox toggled to $isChecked") syncCanEditSwitch(compound, isChecked) updatePermissionsToShare() } R.id.canEditChangeCheckBox -> { Timber.v("canEditChangeCheckBox toggled to $isChecked") syncCanEditSwitch(compound, isChecked) updatePermissionsToShare() } R.id.canEditDeleteCheckBox -> { Timber.v("canEditDeleteCheckBox toggled to $isChecked") syncCanEditSwitch(compound, isChecked) updatePermissionsToShare() } } // updatePermissionsToShare() // see (1) // (1) These modifications result in an exceptional UI behaviour for the case // where the switch 'can edit' is enabled for a *reshared folder*; if the same // behaviour was applied than for owned folder, and the user did not have full // permissions to update the folder, an error would be reported by the server // and the children checkboxes would be automatically hidden again } /** * Sync value of "can edit" [SwitchCompat] according to a change in one of its subordinate checkboxes. * * If all the subordinates are disabled, "can edit" has to be disabled. * * If any subordinate is enabled, "can edit" has to be enabled. * * @param subordinateCheckBoxView Subordinate [CheckBox] that was changed. * @param isChecked 'true' iif subordinateCheckBoxView was checked. */ private fun syncCanEditSwitch(subordinateCheckBoxView: View, isChecked: Boolean) { val canEditCompound = binding.canEditSwitch if (isChecked) { if (!canEditCompound.isChecked) { toggleDisablingListener(canEditCompound) } } else { var allDisabled = true run { var i = 0 while (allDisabled && i < sSubordinateCheckBoxIds.size) { allDisabled = allDisabled and (sSubordinateCheckBoxIds[i] == subordinateCheckBoxView.id || !(view?.findViewById<View>( sSubordinateCheckBoxIds[i] ) as CheckBox).isChecked) i++ } } if (canEditCompound.isChecked && allDisabled) { toggleDisablingListener(canEditCompound) for (i in sSubordinateCheckBoxIds.indices) { view?.findViewById<View>(sSubordinateCheckBoxIds[i])?.visibility = View.GONE } } } } /** * Toggle value of received [CompoundButton] granting that its change listener is not called. * * @param compound [CompoundButton] (switch or checkBox) to toggle without reporting to * the change listener */ private fun toggleDisablingListener(compound: CompoundButton) { compound.setOnCheckedChangeListener(null) compound.toggle() compound.setOnCheckedChangeListener(this) } } private fun observePrivateShareToEdit() { ocShareViewModel.privateShare.observe( this, EventObserver { uiResult -> when (uiResult) { is UIResult.Success -> { updateShare(uiResult.data) } is UIResult.Error -> {} is UIResult.Loading -> {} } } ) } private fun observePrivateShareEdition() { ocShareViewModel.privateShareEditionStatus.observe( this, EventObserver { uiResult -> when (uiResult) { is UIResult.Error -> { showError(getString(R.string.update_link_file_error), uiResult.error) listener?.dismissLoading() } is UIResult.Loading -> { listener?.showLoading() } is UIResult.Success -> {} } } ) } /** * Updates the permissions of the [RemoteShare] according to the values set in the UI */ private fun updatePermissionsToShare() { binding.privateShareErrorMessage.isVisible = false val sharePermissionsBuilder = SharePermissionsBuilder().apply { setSharePermission(binding.canShareSwitch.isChecked) if (file?.isFolder == true) { setUpdatePermission(binding.canEditChangeCheckBox.isChecked) setCreatePermission(binding.canEditCreateCheckBox.isChecked) setDeletePermission(binding.canEditDeleteCheckBox.isChecked) } else { setUpdatePermission(binding.canEditSwitch.isChecked) } } val permissions = sharePermissionsBuilder.build() ocShareViewModel.updatePrivateShare(share?.remoteId!!, permissions, account?.name!!) } private fun refreshPrivateShare(remoteId: String) { ocShareViewModel.refreshPrivateShare(remoteId) } /** * Updates the UI after the result of an update operation on the edited [RemoteShare] permissions. * */ private fun updateShare(updatedShare: OCShare?) { share = updatedShare refreshUiFromState() } /** * Show error when updating the private share, if any */ private fun showError(genericErrorMessage: String, throwable: Throwable?) { binding.privateShareErrorMessage.apply { text = throwable?.parseError(genericErrorMessage, resources) isVisible = true } } companion object { /** The fragment initialization parameters */ private const val ARG_SHARE = "SHARE" private const val ARG_FILE = "FILE" private const val ARG_ACCOUNT = "ACCOUNT" /** Ids of CheckBoxes depending on R.id.canEdit CheckBox */ private val sSubordinateCheckBoxIds = intArrayOf(R.id.canEditCreateCheckBox, R.id.canEditChangeCheckBox, R.id.canEditDeleteCheckBox) /** * Public factory method to create new EditPrivateShareFragment instances. * * @param shareToEdit An [OCShare] to show and edit in the fragment * @param sharedFile The [OCFile] bound to 'shareToEdit' * @param account The ownCloud account holding 'sharedFile' * @return A new instance of fragment EditPrivateShareFragment. */ fun newInstance(shareToEdit: OCShare, sharedFile: OCFile, account: Account): EditPrivateShareFragment { val args = Bundle().apply { putParcelable(ARG_SHARE, shareToEdit) putParcelable(ARG_FILE, sharedFile) putParcelable(ARG_ACCOUNT, account) } return EditPrivateShareFragment().apply { arguments = args } } } }
owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt
3809463759
package com.vimeo.networking2.functions class PrivateFunctionContainer { private fun privateFunction(): String = "Hello World" }
model-generator/integrations/models-input/src/main/java/com/vimeo/networking2/functions/PrivateFunctionContainer.kt
1623022222
package com.github.kittinunf.fuel.toolbox import com.github.kittinunf.fuel.core.Client import com.github.kittinunf.fuel.core.FuelError import com.github.kittinunf.fuel.core.FuelManager import com.github.kittinunf.fuel.core.HeaderName import com.github.kittinunf.fuel.core.Headers import com.github.kittinunf.fuel.core.Method import com.github.kittinunf.fuel.core.Request import com.github.kittinunf.fuel.core.Response import com.github.kittinunf.fuel.core.requests.DefaultBody import com.github.kittinunf.fuel.core.requests.isCancelled import com.github.kittinunf.fuel.toolbox.extensions.forceMethod import com.github.kittinunf.fuel.util.ProgressInputStream import com.github.kittinunf.fuel.util.ProgressOutputStream import com.github.kittinunf.fuel.util.decode import java.io.ByteArrayInputStream import java.io.IOException import java.io.InputStream import java.lang.ref.WeakReference import java.net.HttpURLConnection import java.net.Proxy import javax.net.ssl.HttpsURLConnection import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine import kotlin.math.max class HttpClient( private val proxy: Proxy? = null, var useHttpCache: Boolean = true, var decodeContent: Boolean = true, var hook: Client.Hook ) : Client { override fun executeRequest(request: Request): Response { return try { doRequest(request) } catch (ioe: IOException) { hook.httpExchangeFailed(request, ioe) throw FuelError.wrap(ioe, Response(request.url)) } catch (interrupted: InterruptedException) { throw FuelError.wrap(interrupted, Response(request.url)) } finally { // As per Android documentation, a connection that is not explicitly disconnected // will be pooled and reused! So, don't close it as we need inputStream later! // connection.disconnect() } } @Throws(InterruptedException::class) private fun ensureRequestActive(request: Request, connection: HttpURLConnection?) { val cancelled = request.isCancelled if (!cancelled && !Thread.currentThread().isInterrupted) { return } // Flush all the pipes. This is necessary because we don't want the other end to wait for a timeout or hang. // This interrupts the connection correctly and makes the connection available later. This does break any // keep-alive on this particular connection connection?.disconnect() throw InterruptedException("[HttpClient] could not ensure Request was active: cancelled=$cancelled") } override suspend fun awaitRequest(request: Request): Response = suspendCoroutine { continuation -> try { continuation.resume(doRequest(request)) } catch (ioe: IOException) { hook.httpExchangeFailed(request, ioe) continuation.resumeWithException(FuelError.wrap(ioe, Response(request.url))) } catch (interrupted: InterruptedException) { continuation.resumeWithException(FuelError.wrap(interrupted, Response(request.url))) } } @Throws(IOException::class, InterruptedException::class) private fun doRequest(request: Request): Response { val connection = establishConnection(request) sendRequest(request, connection) return retrieveResponse(request, connection) } @Throws(IOException::class, InterruptedException::class) private fun sendRequest(request: Request, connection: HttpURLConnection) { ensureRequestActive(request, connection) connection.apply { connectTimeout = max(request.executionOptions.timeoutInMillisecond, 0) readTimeout = max(request.executionOptions.timeoutReadInMillisecond, 0) if (this is HttpsURLConnection) { sslSocketFactory = request.executionOptions.socketFactory hostnameVerifier = request.executionOptions.hostnameVerifier } if (request.executionOptions.forceMethods) { forceMethod(request.method) // If setting method via reflection failed, invoke "coerceMethod" // and set "X-HTTP-Method-Override" header if (this.requestMethod !== request.method.value) { this.requestMethod = coerceMethod(request.method).value this.setRequestProperty("X-HTTP-Method-Override", request.method.value) } } else { requestMethod = coerceMethod(request.method).value if (request.method.value == "PATCH") { setRequestProperty("X-HTTP-Method-Override", request.method.value) } } doInput = true useCaches = request.executionOptions.useHttpCache ?: useHttpCache instanceFollowRedirects = false request.headers.transformIterate( { key, values -> setRequestProperty(key, values) }, { key, value -> addRequestProperty(key, value) } ) // By default, the Android implementation of HttpURLConnection requests that servers use gzip compression // and it automatically decompresses the data for callers of URLConnection.getInputStream(). // The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can // be disabled by setting the acceptable encodings in the request header: // // .header(Headers.ACCEPT_ENCODING, "identity") // // However, on the JVM, this behaviour might be different. Content-Encoding SHOULD NOT be used, in HTTP/1x // to act as Transfer Encoding. In HTTP/2, Transfer-Encoding is not part of the Connection field and should // not be injected here. HttpURLConnection is only HTTP/1x, whereas Java 9 introduces a new HttpClient for // HTTP/2. // // This adds the TE header for HTTP/1 connections, and automatically decodes it using decodeTransfer. // The TE (Accept Transfer Encoding) can only be one of these, should match decodeTransfer. setRequestProperty( Headers.ACCEPT_TRANSFER_ENCODING, Headers.collapse(HeaderName(Headers.ACCEPT_TRANSFER_ENCODING), SUPPORTED_DECODING) ) hook.preConnect(connection, request) setDoOutput(connection, request.method) setBodyIfDoOutput(connection, request) } // Ensure that we are connected after this point. Note that getOutputStream above will // also connect and exchange HTTP messages. connection.connect() } @Throws(IOException::class, InterruptedException::class) private fun retrieveResponse(request: Request, connection: HttpURLConnection): Response { ensureRequestActive(request, connection) hook.postConnect(request) val headers = Headers.from(connection.headerFields) val transferEncoding = headers[Headers.TRANSFER_ENCODING].flatMap { it.split(',') }.map { it.trim() } val contentEncoding = headers[Headers.CONTENT_ENCODING].lastOrNull() var contentLength = headers[Headers.CONTENT_LENGTH].lastOrNull()?.toLong() val shouldDecode = (request.executionOptions.decodeContent ?: decodeContent) && contentEncoding != null && contentEncoding != "identity" if (shouldDecode) { // `decodeContent` decodes the response, so the final response has no more `Content-Encoding` headers.remove(Headers.CONTENT_ENCODING) // URLConnection.getContentLength() returns the number of bytes transmitted and cannot be used to predict // how many bytes can be read from URLConnection.getInputStream() for compressed streams. Therefore if the // stream will be decoded, the length becomes unknown // headers.remove(Headers.CONTENT_LENGTH) contentLength = null } // `decodeTransfer` decodes the response, so the final response has no more Transfer-Encoding headers.remove(Headers.TRANSFER_ENCODING) // [RFC 7230, 3.3.2](https://tools.ietf.org/html/rfc7230#section-3.3.2) // // When a message does not have a Transfer-Encoding header field, a // Content-Length header field can provide the anticipated size, as a // decimal number of octets, for a potential payload body. // // A sender MUST NOT send a Content-Length header field in any message // that contains a Transfer-Encoding header field. // // [RFC 7230, 3.3.3](https://tools.ietf.org/html/rfc7230#section-3.3.3) // // Any 2xx (Successful) response to a CONNECT request implies that // the connection will become a tunnel immediately after the empty // line that concludes the header fields. A client MUST ignore any // Content-Length or Transfer-Encoding header fields received in // such a message. // if (transferEncoding.any { encoding -> encoding.isNotBlank() && encoding != "identity" }) { headers.remove(Headers.CONTENT_LENGTH) contentLength = -1 } val contentStream = dataStream(request, connection)?.decode(transferEncoding) ?: ByteArrayInputStream(ByteArray(0)) val inputStream = if (shouldDecode && contentEncoding != null) contentStream.decode(contentEncoding) else contentStream val cancellationConnection = WeakReference<HttpURLConnection>(connection) val progressStream = ProgressInputStream( inputStream, onProgress = { readBytes -> request.executionOptions.responseProgress(readBytes, contentLength ?: readBytes) ensureRequestActive(request, cancellationConnection.get()) } ) // The input and output streams returned by connection are not buffered. In order to give consistent progress // reporting, by means of flushing, the input stream here is buffered. return Response( url = request.url, headers = headers, contentLength = contentLength ?: -1, statusCode = connection.responseCode, responseMessage = connection.responseMessage.orEmpty(), body = DefaultBody.from( { progressStream.buffered(FuelManager.progressBufferSize) }, { contentLength ?: -1 } ) ) } private fun dataStream(request: Request, connection: HttpURLConnection): InputStream? = try { hook.interpretResponseStream(request, connection.inputStream)?.buffered() } catch (_: IOException) { hook.interpretResponseStream(request, connection.errorStream)?.buffered() } private fun establishConnection(request: Request): HttpURLConnection { val url = request.url val connection = proxy?.let { url.openConnection(it) } ?: url.openConnection() return connection as HttpURLConnection } private fun setBodyIfDoOutput(connection: HttpURLConnection, request: Request) { val body = request.body if (!connection.doOutput || body.isEmpty()) { return } val contentLength = body.length if (contentLength != null && contentLength != -1L) { // The content has a known length, so no need to chunk connection.setFixedLengthStreamingMode(contentLength.toLong()) } else { // The content doesn't have a known length, so turn it into chunked connection.setChunkedStreamingMode(4096) } val noProgressHandler = request.executionOptions.requestProgress.isNotSet() val outputStream = if (noProgressHandler) { // No need to report progress, let's just send the payload without buffering connection.outputStream } else { // The input and output streams returned by connection are not buffered. In order to give consistent progress // reporting, by means of flushing, the output stream here is buffered. val totalBytes = if ((contentLength ?: -1L).toLong() > 0) { contentLength!!.toLong() } else { null } ProgressOutputStream( connection.outputStream, onProgress = { writtenBytes -> request.executionOptions.requestProgress(writtenBytes, totalBytes ?: writtenBytes) ensureRequestActive(request, connection) } ).buffered(FuelManager.progressBufferSize) } body.writeTo(outputStream) connection.outputStream.flush() } private fun setDoOutput(connection: HttpURLConnection, method: Method) = when (method) { Method.GET, Method.HEAD, Method.OPTIONS, Method.TRACE -> connection.doOutput = false Method.DELETE, Method.POST, Method.PUT, Method.PATCH -> connection.doOutput = true } companion object { private val SUPPORTED_DECODING = listOf("gzip", "deflate; q=0.5") private fun coerceMethod(method: Method) = if (method == Method.PATCH) Method.POST else method } }
fuel/src/main/kotlin/com/github/kittinunf/fuel/toolbox/HttpClient.kt
730503103
package abi43_0_0.expo.modules.sharing import android.content.Context import abi43_0_0.expo.modules.core.BasePackage class SharingPackage : BasePackage() { override fun createExportedModules(context: Context) = listOf(SharingModule(context)) }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/sharing/SharingPackage.kt
604837786
package org.jetbrains.fortran.ide.actions import com.intellij.ide.actions.CreateFileFromTemplateAction import com.intellij.ide.actions.CreateFileFromTemplateDialog import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import org.jetbrains.fortran.FortranIcons class FortranCreateFileAction : CreateFileFromTemplateAction(CAPTION, "", FortranIcons.fileTypeIcon), DumbAware { override fun getActionName(directory: PsiDirectory?, newName: String, templateName: String?): String = CAPTION override fun buildDialog( project: Project, directory: PsiDirectory, builder: CreateFileFromTemplateDialog.Builder ) { builder.setTitle(CAPTION).addKind("Empty File", FortranIcons.fileTypeIcon, "Fortran File") .addKind("Main Program", FortranIcons.mainProgramIcon, "Main Program") .addKind("Module", FortranIcons.moduleIcon, "Module") .addKind("Function", FortranIcons.functionIcon, "Function") .addKind("Subroutine", FortranIcons.subroutineIcon, "Subroutine") } private companion object { private const val CAPTION = "New Fortran File" } }
src/main/kotlin/org/jetbrains/fortran/ide/actions/FortranCreateFileAction.kt
4279340979
package com.teamwizardry.librarianlib.glitter.test.systems import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding import com.teamwizardry.librarianlib.glitter.modules.BasicPhysicsUpdateModule import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderModule import net.minecraft.entity.Entity import net.minecraft.util.Identifier object ForwardFacingSystem : TestSystem(Identifier("liblib-glitter-test:forward_facing")) { override fun configure() { val position = bind(3) val previousPosition = bind(3) val velocity = bind(3) val color = bind(4) updateModules.add( BasicPhysicsUpdateModule( position = position, previousPosition = previousPosition, velocity = velocity, enableCollision = true, gravity = ConstantBinding(0.02), bounciness = ConstantBinding(0.8), friction = ConstantBinding(0.02), damping = ConstantBinding(0.01) ) ) renderModules.add( SpriteRenderModule.build( Identifier("minecraft", "textures/item/clay_ball.png"), position ) .previousPosition(previousPosition) .color(color) .size(0.2) .facingVector(velocity) .build() ) } override fun spawn(player: Entity) { val eyePos = player.getCameraPosVec(1f) val look = player.rotationVector val spawnDistance = 2 val spawnVelocity = 0.2 this.addParticle( 200, // position eyePos.x + look.x * spawnDistance, eyePos.y + look.y * spawnDistance, eyePos.z + look.z * spawnDistance, // previous position eyePos.x + look.x * spawnDistance, eyePos.y + look.y * spawnDistance, eyePos.z + look.z * spawnDistance, // velocity look.x * spawnVelocity, look.y * spawnVelocity, look.z * spawnVelocity, // color Math.random(), Math.random(), Math.random(), 1.0 ) } }
modules/glitter/src/test/kotlin/com/teamwizardry/librarianlib/glitter/test/systems/ForwardFacingSystem.kt
4135715364
package com.quijotelui.model import org.hibernate.annotations.Immutable import java.math.BigDecimal import javax.persistence.Column import javax.persistence.Entity import javax.persistence.Id import javax.persistence.Table @Entity @Immutable @Table(name = "v_ele_retenciones_detalle") class RetencionDetalle { @Id @Column(name = "id") var id : Long? = null @Column(name = "codigo") var codigo : String? = null @Column(name = "numero") var numero : String? = null @Column(name = "tipo") var tipo : String? = null @Column(name = "codigo_sri") var codigoSRI : String? = null @Column(name = "base_imponible") val baseImponible : BigDecimal? = null @Column(name = "porcentaje") val porcentaje : BigDecimal? = null @Column(name = "valor_retenido") val valorRetenido : BigDecimal? = null @Column(name = "tipo_comprobante") var tipoComprobante : String? = null @Column(name = "numero_comprobante") var numeroComprobante : String? = null @Column(name = "fecha_comprobante") var fechaComprobante : String? = null }
src/main/kotlin/com/quijotelui/model/RetencionDetalle.kt
2386614131
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.hilt.integration.workerapp import android.os.Build import androidx.hilt.work.HiltWorkerFactory import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.SdkSuppress import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import androidx.work.ListenableWorker import androidx.work.testing.TestListenableWorkerBuilder import com.google.common.truth.Truth.assertThat import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import javax.inject.Inject @SmallTest @HiltAndroidTest @RunWith(AndroidJUnit4::class) // TODO: Find out why random ClassNotFoundException is thrown in APIs lower than 21. @SdkSuppress(minSdkVersion = Build.VERSION_CODES.LOLLIPOP) class SimpleTest { @get:Rule val testRule = HiltAndroidRule(this) @Inject lateinit var hiltWorkerFactory: HiltWorkerFactory @Before fun setup() { testRule.inject() } @Test fun testWorkerInject() { val context = InstrumentationRegistry.getInstrumentation().targetContext val worker = TestListenableWorkerBuilder<SimpleWorker>(context).apply { setWorkerFactory(hiltWorkerFactory) }.build() val result = worker.doWork() assertThat(result).isEqualTo(ListenableWorker.Result.success()) } @Test fun testCoroutineWorkerInject() { val context = InstrumentationRegistry.getInstrumentation().targetContext val worker = TestListenableWorkerBuilder<SimpleCoroutineWorker>(context).apply { setWorkerFactory(hiltWorkerFactory) }.build() runBlocking { val result = worker.doWork() assertThat(result).isEqualTo(ListenableWorker.Result.success()) } } @Test fun testNestedWorkerInject() { val context = InstrumentationRegistry.getInstrumentation().targetContext val worker = TestListenableWorkerBuilder<TopClass.NestedWorker>(context).apply { setWorkerFactory(hiltWorkerFactory) }.build() val result = worker.doWork() assertThat(result).isEqualTo(ListenableWorker.Result.success()) } }
hilt/integration-tests/workerapp/src/androidTest/java/androidx/hilt/integration/workerapp/SimpleTest.kt
4171746008
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.parser.expansion import androidx.annotation.VisibleForTesting import androidx.room.parser.ParsedQuery import androidx.room.parser.SqlParser import androidx.room.processor.QueryRewriter import androidx.room.solver.query.result.PojoRowAdapter import androidx.room.solver.query.result.QueryResultAdapter import androidx.room.verifier.QueryResultInfo import androidx.room.vo.EmbeddedField import androidx.room.vo.Entity import androidx.room.vo.EntityOrView import androidx.room.vo.Field import androidx.room.vo.Pojo import androidx.room.vo.columnNames import java.util.Locale /** * Interprets and rewrites SQL queries in the context of the provided entities and views such that * star projection (select *) turn into explicit column lists and embedded fields are re-named to * avoid conflicts in the response data set. */ class ProjectionExpander( private val tables: List<EntityOrView> ) : QueryRewriter { private class IdentifierMap<V> : HashMap<String, V>() { override fun put(key: String, value: V): V? { return super.put(key.lowercase(Locale.ENGLISH), value) } override fun get(key: String): V? { return super.get(key.lowercase(Locale.ENGLISH)) } } /** * Rewrites the specified [query] in the context of the provided [pojo]. Expanding its start * projection ('SELECT *') and converting its named binding templates to positional * templates (i.e. ':VVV' to '?'). */ @VisibleForTesting(otherwise = VisibleForTesting.PRIVATE) fun interpret( query: ParsedQuery, pojo: Pojo? ) = interpret( query = ExpandableSqlParser.parse(query.original).also { it.resultInfo = query.resultInfo }, pojo = pojo ) override fun rewrite( query: ParsedQuery, resultAdapter: QueryResultAdapter ): ParsedQuery { if (resultAdapter.rowAdapters.isEmpty()) { return query } // Don't know how to expand when multiple POJO types are created from the same row. if (resultAdapter.rowAdapters.size > 1) { return query } val rowAdapter = resultAdapter.rowAdapters.single() return if (rowAdapter is PojoRowAdapter) { interpret( query = ExpandableSqlParser.parse(query.original), pojo = rowAdapter.pojo ).let { val reParsed = SqlParser.parse(it) if (reParsed.errors.isEmpty()) { reParsed } else { query // return original, expansion somewhat failed } } } else { query } } private fun interpret( query: ExpandableParsedQuery, pojo: Pojo? ): String { val queriedTableNames = query.tables.map { it.name } return query.sections.joinToString("") { section -> when (section) { is ExpandableSection.Text -> section.text is ExpandableSection.BindVar -> "?" is ExpandableSection.Newline -> "\n" is ExpandableSection.Projection -> { if (pojo == null) { section.text } else { interpretProjection(query, section, pojo, queriedTableNames) } } } } } private fun interpretProjection( query: ExpandableParsedQuery, section: ExpandableSection.Projection, pojo: Pojo, queriedTableNames: List<String> ): String { val aliasToName = query.tables .map { (name, alias) -> alias to name } .toMap(IdentifierMap()) val nameToAlias = query.tables .groupBy { it.name.lowercase(Locale.ENGLISH) } .filter { (_, pairs) -> pairs.size == 1 } .map { (name, pairs) -> name to pairs.first().alias } .toMap(IdentifierMap()) return when (section) { is ExpandableSection.Projection.All -> { expand( pojo = pojo, ignoredColumnNames = query.explicitColumns, // The columns come directly from the specified table. // We should not prepend the prefix-dot to the columns. shallow = findEntityOrView(pojo)?.tableName in queriedTableNames, nameToAlias = nameToAlias, resultInfo = query.resultInfo ) } is ExpandableSection.Projection.Table -> { val embedded = findEmbeddedField(pojo, section.tableAlias) if (embedded != null) { expandEmbeddedField( embedded = embedded, table = findEntityOrView(embedded.pojo), shallow = false, tableToAlias = nameToAlias ).joinToString(", ") } else { val tableName = aliasToName[section.tableAlias] ?: section.tableAlias val table = tables.find { it.tableName == tableName } pojo.fields.filter { field -> field.parent == null && field.columnName !in query.explicitColumns && table?.columnNames?.contains(field.columnName) == true }.joinToString(", ") { field -> "`${section.tableAlias}`.`${field.columnName}`" } } } } } private fun findEntityOrView(pojo: Pojo): EntityOrView? { return tables.find { it.typeName == pojo.typeName } } private fun findEmbeddedField( pojo: Pojo, tableAlias: String ): EmbeddedField? { // Try to find by the prefix. val matchByPrefix = pojo.embeddedFields.find { it.prefix == tableAlias } if (matchByPrefix != null) { return matchByPrefix } // Try to find by the table name. return pojo.embeddedFields.find { it.prefix.isEmpty() && findEntityOrView(it.pojo)?.tableName == tableAlias } } private fun expand( pojo: Pojo, ignoredColumnNames: List<String>, shallow: Boolean, nameToAlias: Map<String, String>, resultInfo: QueryResultInfo? ): String { val table = findEntityOrView(pojo) return ( pojo.embeddedFields.flatMap { expandEmbeddedField(it, findEntityOrView(it.pojo), shallow, nameToAlias) } + pojo.fields.filter { field -> field.parent == null && field.columnName !in ignoredColumnNames && (resultInfo == null || resultInfo.hasColumn(field.columnName)) }.map { field -> if (table != null && table is Entity) { // Should not happen when defining a view val tableAlias = nameToAlias[table.tableName.lowercase(Locale.ENGLISH)] ?: table.tableName "`$tableAlias`.`${field.columnName}` AS `${field.columnName}`" } else { "`${field.columnName}`" } } ).joinToString(", ") } private fun QueryResultInfo.hasColumn(columnName: String): Boolean { return columns.any { column -> column.name == columnName } } private fun expandEmbeddedField( embedded: EmbeddedField, table: EntityOrView?, shallow: Boolean, tableToAlias: Map<String, String> ): List<String> { val pojo = embedded.pojo return if (table != null) { if (embedded.prefix.isNotEmpty()) { table.fields.map { field -> if (shallow) { "`${embedded.prefix}${field.columnName}`" } else { "`${embedded.prefix}`.`${field.columnName}` " + "AS `${embedded.prefix}${field.columnName}`" } } } else { table.fields.map { field -> if (shallow) { "`${field.columnName}`" } else { val tableAlias = tableToAlias[table.tableName] ?: table.tableName "`$tableAlias`.`${field.columnName}` AS `${field.columnName}`" } } } } else { if (!shallow && embedded.prefix.isNotEmpty() && embedded.prefix in tableToAlias.values ) { pojo.fields.map { field -> "`${embedded.prefix}`.`${field.columnNameWithoutPrefix(embedded.prefix)}` " + "AS `${field.columnName}`" } } else { pojo.fields.map { field -> "`${field.columnName}`" } } } } private fun Field.columnNameWithoutPrefix(prefix: String): String { return if (columnName.startsWith(prefix)) { columnName.substring(prefix.length) } else { columnName } } }
room/room-compiler/src/main/kotlin/androidx/room/parser/expansion/ProjectionExpander.kt
2991292644
package app.entryscreen.login import domain.login.TinderLoginUseCase import io.reactivex.Scheduler import io.reactivex.observers.DisposableCompletableObserver import reporter.CrashReporter internal class TinderLoginCoordinator( private val view: TinderLoginView, private val asyncExecutionScheduler: Scheduler, private val postExecutionScheduler: Scheduler, private val resultCallback: ResultCallback, private val crashReporter: CrashReporter) { private var useCase: TinderLoginUseCase? = null fun actionDoLogin(facebookId: String, facebookToken: String) { useCase?.dispose() view.setRunning() TinderLoginUseCase( facebookId, facebookToken, asyncExecutionScheduler, postExecutionScheduler).apply { useCase = this execute(object : DisposableCompletableObserver() { override fun onError(error: Throwable) { crashReporter.report(error) view.setError() } override fun onComplete() { resultCallback.onTinderLoginSuccess() view.setStale() } }) } } fun actionCancel() { view.setStale() useCase?.dispose() } interface ResultCallback { fun onTinderLoginSuccess() } }
app/src/main/kotlin/app/entryscreen/login/TinderLoginCoordinator.kt
1027025021
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.appcompat.app import android.content.res.Configuration import android.text.TextUtils import androidx.appcompat.app.NightModeCustomAttachBaseContextActivity.CUSTOM_FONT_SCALE import androidx.appcompat.app.NightModeCustomAttachBaseContextActivity.CUSTOM_LOCALE import androidx.appcompat.testutils.NightModeActivityTestRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import androidx.test.filters.SdkSuppress import androidx.test.platform.app.InstrumentationRegistry import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import java.util.Locale /** * This is one approach to customizing Activity configuration that's used in google3. * <p> * */ @SdkSuppress(minSdkVersion = 16) @MediumTest @RunWith(AndroidJUnit4::class) class NightModeRtlTestUtilsRegressionTestCase { private var restoreConfig: (() -> Unit)? = null @get:Rule val activityRule = NightModeActivityTestRule( NightModeCustomAttachBaseContextActivity::class.java, initialTouchMode = false, launchActivity = false ) @Suppress("DEPRECATION") @Before fun setup() { // Duplicated from the Google Calendar app's RtlTestUtils.java val context = InstrumentationRegistry.getInstrumentation().targetContext val resources = context.resources val locale = CUSTOM_LOCALE val configuration = resources.configuration // Preserve initial state for later. val initialConfig = Configuration(configuration) val initialLocale = Locale.getDefault() restoreConfig = { Locale.setDefault(initialLocale) resources.updateConfiguration(initialConfig, resources.displayMetrics) } // Set up the custom state. configuration.fontScale = CUSTOM_FONT_SCALE configuration.setLayoutDirection(locale) configuration.setLocale(locale) Locale.setDefault(locale) resources.updateConfiguration(configuration, resources.displayMetrics) // Launch the activity last. activityRule.launchActivity(null) } @After fun teardown() { // Restore the initial state. restoreConfig?.invoke() } @Test @Suppress("DEPRECATION") fun testLocaleIsMaintained() { // Check that the custom configuration properties are maintained val config = activityRule.activity.resources.configuration assertEquals(CUSTOM_LOCALE, config.locale) assertEquals(TextUtils.getLayoutDirectionFromLocale(CUSTOM_LOCALE), config.layoutDirection) } @Test fun testFontScaleIsMaintained() { // Check that the custom configuration properties are maintained val config = activityRule.activity.resources.configuration assertEquals(CUSTOM_FONT_SCALE, config.fontScale) } }
appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/NightModeRtlTestUtilsRegressionTestCase.kt
203907402
val property: String <selection><caret>=</selection> "Non-traversable test"
kotlin-eclipse-ui-test/testData/wordSelection/selectPrevious/NonTraversableElement/1.kt
2021842589
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.opengl.templates import org.lwjgl.generator.* import org.lwjgl.opengl.* val INTEL_performance_query = "INTELPerformanceQuery".nativeClassGL("INTEL_performance_query", postfix = INTEL) { documentation = """ Native bindings to the $registryLink extension. The purpose of this extension is to expose Intel proprietary hardware performance counters to the OpenGL applications. Performance counters may count: ${ul( "number of hardware events such as number of spawned vertex shaders. In this case the results represent the number of events.", """ duration of certain activity, like time took by all fragment shader invocations. In that case the result usually represents the number of clocks in which the particular HW unit was busy. In order to use such counter efficiently, it should be normalized to the range of <0,1> by dividing its value by the number of render clocks. """, """ used throughput of certain memory types such as texture memory. In that case the result of performance counter usually represents the number of bytes transferred between GPU and memory. """ )} This extension specifies universal API to manage performance counters on different Intel hardware platforms. Performance counters are grouped together into proprietary, hardware-specific, fixed sets of counters that are measured together by the GPU. It is assumed that performance counters are started and ended on any arbitrary boundaries during rendering. A set of performance counters is represented by a unique query type. Each query type is identified by assigned name and ID. Multiple query types (sets of performance counters) are supported by the Intel hardware. However each Intel hardware generation supports different sets of performance counters. Therefore the query types between hardware generations can be different. The definition of query types and their results structures can be learned through the API. It is also documented in a separate document of Intel OGL Performance Counters Specification issued per each new hardware generation. The API allows to create multiple instances of any query type and to sample different fragments of 3D rendering with such instances. Query instances are identified with handles. Requires ${GL30.core}. """ IntConstant( "Returned by the capsMask parameter of GetPerfQueryInfoINTEL.", "PERFQUERY_SINGLE_CONTEXT_INTEL"..0x0000, "PERFQUERY_GLOBAL_CONTEXT_INTEL"..0x0001 ) IntConstant( "Accepted by the flags parameter of GetPerfQueryDataINTEL.", "PERFQUERY_WAIT_INTEL"..0x83FB, "PERFQUERY_FLUSH_INTEL"..0x83FA, "PERFQUERY_DONOT_FLUSH_INTEL"..0x83F9 ) IntConstant( "Returned by GetPerfCounterInfoINTEL function as counter type enumeration in location pointed by counterTypeEnum.", "PERFQUERY_COUNTER_EVENT_INTEL"..0x94F0, "PERFQUERY_COUNTER_DURATION_NORM_INTEL"..0x94F1, "PERFQUERY_COUNTER_DURATION_RAW_INTEL"..0x94F2, "PERFQUERY_COUNTER_THROUGHPUT_INTEL"..0x94F3, "PERFQUERY_COUNTER_RAW_INTEL"..0x94F4, "PERFQUERY_COUNTER_TIMESTAMP_INTEL"..0x94F5 ) IntConstant( "Returned by glGetPerfCounterInfoINTEL function as counter data type enumeration in location pointed by counterDataTypeEnum.", "PERFQUERY_COUNTER_DATA_UINT32_INTEL"..0x94F8, "PERFQUERY_COUNTER_DATA_UINT64_INTEL"..0x94F9, "PERFQUERY_COUNTER_DATA_FLOAT_INTEL"..0x94FA, "PERFQUERY_COUNTER_DATA_DOUBLE_INTEL"..0x94FB, "PERFQUERY_COUNTER_DATA_BOOL32_INTEL"..0x94FC ) IntConstant( "Accepted by the {@code pname} parameter of GetIntegerv.", "PERFQUERY_QUERY_NAME_LENGTH_MAX_INTEL"..0x94FD, "PERFQUERY_COUNTER_NAME_LENGTH_MAX_INTEL"..0x94FE, "PERFQUERY_COUNTER_DESC_LENGTH_MAX_INTEL"..0x94FF ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv.", "PERFQUERY_GPA_EXTENDED_COUNTERS_INTEL"..0x9500 ) void( "BeginPerfQueryINTEL", "", GLuint.IN("queryHandle", "") ) void( "CreatePerfQueryINTEL", "", GLuint.IN("queryId", ""), Check(1)..ReturnParam..GLuint_p.OUT("queryHandle", "") ) void( "DeletePerfQueryINTEL", "", GLuint.IN("queryHandle", "") ) void( "EndPerfQueryINTEL", "", GLuint.IN("queryHandle", "") ) void( "GetFirstPerfQueryIdINTEL", "", Check(1)..ReturnParam..GLuint_p.OUT("queryId", "") ) void( "GetNextPerfQueryIdINTEL", "", GLuint.IN("queryId", ""), Check(1)..ReturnParam..GLuint_p.OUT("nextQueryId", "") ) void( "GetPerfCounterInfoINTEL", "", GLuint.IN("queryId", ""), GLuint.IN("counterId", ""), AutoSize("counterName")..GLuint.IN("counterNameLength", ""), GLcharASCII_p.OUT("counterName", ""), AutoSize("counterDesc")..GLuint.IN("counterDescLength", ""), GLcharASCII_p.OUT("counterDesc", ""), Check(1)..GLuint_p.OUT("counterOffset", ""), Check(1)..GLuint_p.OUT("counterDataSize", ""), Check(1)..GLuint_p.OUT("counterTypeEnum", ""), Check(1)..GLuint_p.OUT("counterDataTypeEnum", ""), Check(1)..GLuint64_p.OUT("rawCounterMaxValue", "") ) void( "GetPerfQueryDataINTEL", "", GLuint.IN("queryHandle", ""), GLuint.IN("flags", ""), AutoSize("data")..GLsizei.IN("dataSize", ""), void_p.OUT("data", ""), Check(1)..GLuint_p.OUT("bytesWritten", "") ) void( "GetPerfQueryIdByNameINTEL", "", GLcharASCII_p.IN("queryName", ""), Check(1)..ReturnParam..GLuint_p.OUT("queryId", "") ) void( "GetPerfQueryInfoINTEL", "", GLuint.IN("queryId", ""), AutoSize("queryName")..GLuint.IN("queryNameLength", ""), GLcharASCII_p.OUT("queryName", ""), Check(1)..GLuint_p.OUT("dataSize", ""), Check(1)..GLuint_p.OUT("noCounters", ""), Check(1)..GLuint_p.OUT("noInstances", ""), Check(1)..GLuint_p.OUT("capsMask", "") ) }
modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/INTEL_performance_query.kt
1749388746
/** * Copyright 2015 Groupon 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.groupon.aint.kmond.output import com.groupon.aint.kmond.Metrics import com.groupon.vertx.utils.Logger import io.vertx.core.Handler import io.vertx.core.eventbus.Message /** * Output handler for logging. * * @author Gil Markham (gil at groupon dot com) */ class LoggingHandler(): Handler<Message<Metrics>> { companion object { private val log = Logger.getLogger(LoggingHandler::class.java) } override fun handle(event: Message<Metrics>) { log.info("handle", "metricsReceived", arrayOf("metrics"), event.body()) } }
src/main/kotlin/com/groupon/aint/kmond/output/LoggingHandler.kt
262837515
package ch.unstable.lib.sbb.auth import android.util.Base64 import okhttp3.Interceptor import okhttp3.Request import okhttp3.Response import okhttp3.internal.Util.UTF_8 import java.text.SimpleDateFormat import java.util.* import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec class AuthInterceptor(private val dateSource: DateSource) : Interceptor { constructor() : this(DefaultDateSource()) private val userAgent = run { val versionName = "10.6.0" val androidVersion = "9" val deviceName = "Google;Android SDK built for x86" "SBBmobile/flavorprodRelease-$versionName-RELEASE Android/$androidVersion ($deviceName)" } private val token = UUID.randomUUID().toString() private val macKey: SecretKeySpec = SecretKeySpec(Keys.macKey.toByteArray(UTF_8), "HmacSHA1") private fun createSignature(date: String, path: String): String { return Mac.getInstance("HmacSHA1").also { it.init(macKey) it.update(path.toByteArray(UTF_8)) it.update(date.toByteArray(UTF_8)) }.doFinal().let { Base64.encodeToString(it, Base64.NO_WRAP) } } fun createNewRequest(original: Request): Request { val date = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(dateSource.currentDate) val url = original.url() val signature = createSignature(date, url.encodedPath()) // for unknown reasons the path needs to be url-encoded again AFTER calculating the // signature.. val doubleEncodedUrl = original.url().newBuilder() .encodedPath("/") .also { url.encodedPathSegments().forEach {segment -> it.addPathSegment(segment) } }.build() return original.newBuilder() .url(doubleEncodedUrl) .addHeader("X-API-AUTHORIZATION", signature) .addHeader("X-API-DATE", date) .addHeader("X-APP-TOKEN", token) .addHeader("User-Agent", userAgent) .build() } override fun intercept(chain: Interceptor.Chain): Response { val request = createNewRequest(chain.request()) return chain.proceed(request) } }
lib/sbb/src/main/java/ch/unstable/lib/sbb/auth/AuthInterceptor.kt
2267337816
// 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.car.trustagent import android.Manifest.permission import android.app.Activity import android.content.Context import androidx.room.Room import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.GrantPermissionRule import com.google.android.libraries.car.trustagent.testutils.Base64CryptoHelper import com.google.common.truth.Truth.assertThat import com.google.common.util.concurrent.MoreExecutors.directExecutor import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.spy import com.nhaarman.mockitokotlin2.verify import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.UnconfinedTestDispatcher import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith /** * Collection of unit tests for [AssociationManager] where Bluetooth permissions are not granted. */ @ExperimentalCoroutinesApi @RunWith(AndroidJUnit4::class) class AssociationManagerMissingBluetoothPermissionsTest { // Grant only non-Bluetooth permissions. @get:Rule val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant( permission.ACCESS_FINE_LOCATION, permission.ACCESS_BACKGROUND_LOCATION, ) private val testDispatcher = UnconfinedTestDispatcher() private val context = ApplicationProvider.getApplicationContext<Context>() private lateinit var database: ConnectedCarDatabase private lateinit var bleManager: FakeBleManager private lateinit var associationManager: AssociationManager private lateinit var associationCallback: AssociationManager.AssociationCallback @Before fun setUp() { // Using directExecutor to ensure that all operations happen on the main thread and allows for // tests to wait until the operations are done before continuing. Without this, operations can // leak and interfere between tests. See b/153095973 for details. database = Room.inMemoryDatabaseBuilder(context, ConnectedCarDatabase::class.java) .allowMainThreadQueries() .setQueryExecutor(directExecutor()) .build() val associatedCarManager = AssociatedCarManager(context, database, Base64CryptoHelper()) bleManager = spy(FakeBleManager()) associationCallback = mock() associationManager = AssociationManager(context, associatedCarManager, bleManager).apply { registerAssociationCallback(associationCallback) coroutineContext = testDispatcher } } @After fun after() { database.close() } @Test fun startSppDiscovery_returnsFalse() { bleManager.isEnabled = true assertThat(associationManager.startSppDiscovery()).isFalse() assertThat(associationManager.isSppDiscoveryStarted).isFalse() } @Test fun startCdmDiscovery_returnsFalse() { associationManager.isSppEnabled = false val discoveryRequest = DiscoveryRequest.Builder(Activity()).build() assertThat(associationManager.startCdmDiscovery(discoveryRequest, mock())).isFalse() } @Test fun associate_notifiesCallbackOfFailure() { associationManager.associate(mock<DiscoveredCar>()) verify(associationCallback).onAssociationFailed() } }
trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/AssociationManagerMissingBluetoothPermissionsTest.kt
78180605
/* * Copyright (c) 2017. tangzx(love.tangzx@qq.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.lua.debugger.emmy.value import com.intellij.icons.AllIcons import com.intellij.xdebugger.evaluation.XDebuggerEvaluator import com.intellij.xdebugger.frame.* import com.tang.intellij.lua.debugger.LuaXBoolPresentation import com.tang.intellij.lua.debugger.LuaXNumberPresentation import com.tang.intellij.lua.debugger.LuaXStringPresentation import com.tang.intellij.lua.debugger.emmy.EmmyDebugStackFrame import com.tang.intellij.lua.debugger.emmy.LuaValueType import com.tang.intellij.lua.debugger.emmy.VariableValue import com.tang.intellij.lua.lang.LuaIcons import java.util.* abstract class LuaXValue(val value: VariableValue) : XValue() { companion object { fun create(v: VariableValue, frame: EmmyDebugStackFrame): LuaXValue { return when(v.valueTypeValue) { LuaValueType.TSTRING -> StringXValue(v) LuaValueType.TNUMBER -> NumberXValue(v) LuaValueType.TBOOLEAN -> BoolXValue(v) LuaValueType.TUSERDATA, LuaValueType.TTABLE -> TableXValue(v, frame) LuaValueType.GROUP -> GroupXValue(v, frame) else -> AnyXValue(v) } } } val name: String get() { return value.nameValue } var parent: LuaXValue? = null } private object VariableComparator : Comparator<VariableValue> { override fun compare(o1: VariableValue, o2: VariableValue): Int { val w1 = if (o1.fake) 0 else 1 val w2 = if (o2.fake) 0 else 1 if (w1 != w2) return w1.compareTo(w2) return o1.nameValue.compareTo(o2.nameValue) } } class StringXValue(v: VariableValue) : LuaXValue(v) { override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) { xValueNode.setPresentation(null, LuaXStringPresentation(value.value), false) } } class NumberXValue(v: VariableValue) : LuaXValue(v) { override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) { xValueNode.setPresentation(null, LuaXNumberPresentation(value.value), false) } } class BoolXValue(val v: VariableValue) : LuaXValue(v) { override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) { xValueNode.setPresentation(null, LuaXBoolPresentation(v.value), false) } } class AnyXValue(val v: VariableValue) : LuaXValue(v) { override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) { xValueNode.setPresentation(null, v.valueTypeName, v.value, false) } } class GroupXValue(v: VariableValue, val frame: EmmyDebugStackFrame) : LuaXValue(v) { private val children = mutableListOf<LuaXValue>() init { value.children?. sortedWith(VariableComparator)?. forEach { children.add(create(it, frame)) } } override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) { xValueNode.setPresentation(AllIcons.Nodes.UpLevel, value.valueTypeName, value.value, true) } override fun computeChildren(node: XCompositeNode) { val cl = XValueChildrenList() children.forEach { it.parent = this cl.add(it.name, it) } node.addChildren(cl, true) } } class TableXValue(v: VariableValue, val frame: EmmyDebugStackFrame) : LuaXValue(v) { private val children = mutableListOf<LuaXValue>() init { value.children?. sortedWith(VariableComparator)?. forEach { children.add(create(it, frame)) } } override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) { var icon = AllIcons.Json.Object if (value.valueTypeName == "C#") { icon = LuaIcons.CSHARP } else if (value.valueTypeName == "C++") { icon = LuaIcons.CPP } xValueNode.setPresentation(icon, value.valueTypeName, value.value, true) } override fun computeChildren(node: XCompositeNode) { val ev = this.frame.evaluator if (ev != null) { ev.eval(evalExpr, value.cacheId, object : XDebuggerEvaluator.XEvaluationCallback { override fun errorOccurred(err: String) { node.setErrorMessage(err) } override fun evaluated(value: XValue) { if (value is TableXValue) { val cl = XValueChildrenList() children.clear() children.addAll(value.children) children.forEach { it.parent = this@TableXValue cl.add(it.name, it) } node.addChildren(cl, true) } else { // todo: table is nil? node.setErrorMessage("nil") } } }, 2) } else super.computeChildren(node) } private val evalExpr: String get() { var name = name val properties = ArrayList<String>() var parent = this.parent while (parent != null) { if (!parent.value.fake) { properties.add(name) name = parent.name } parent = parent.parent } val sb = StringBuilder(name) for (i in properties.indices.reversed()) { val parentName = properties[i] if (parentName.startsWith("[")) sb.append(parentName) else sb.append(String.format("[\"%s\"]", parentName)) } return sb.toString() } }
src/main/java/com/tang/intellij/lua/debugger/emmy/value/LuaXValue.kt
1839537058
package org.wordpress.aztec.plugins.shortcodes import org.wordpress.aztec.plugins.shortcodes.extensions.ATTRIBUTE_VIDEOPRESS_HIDDEN_ID import org.wordpress.aztec.plugins.shortcodes.extensions.ATTRIBUTE_VIDEOPRESS_HIDDEN_SRC import org.wordpress.aztec.plugins.html2visual.IHtmlPreprocessor import org.wordpress.aztec.plugins.shortcodes.utils.GutenbergUtils import org.wordpress.aztec.plugins.visual2html.IHtmlPostprocessor class VideoShortcodePlugin : IHtmlPreprocessor, IHtmlPostprocessor { private val TAG = "video" private val TAG_VIDEOPRESS_SHORTCODE = "wpvideo" override fun beforeHtmlProcessed(source: String): String { if (GutenbergUtils.contentContainsGutenbergBlocks(source)) return source var newSource = source.replace(Regex("(?<!\\[)\\[$TAG([^\\]]*)\\](?!\\])"), "<$TAG$1 />") newSource = newSource.replace(Regex("(?<!\\[)\\[$TAG_VIDEOPRESS_SHORTCODE([^\\]]*)\\](?!\\])"), { it -> fromVideoPressShortCodeToHTML(it) }) return newSource } override fun onHtmlProcessed(source: String): String { if (GutenbergUtils.contentContainsGutenbergBlocks(source)) { // From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video // > Tag omission None, both the starting and ending tag are mandatory. return StringBuilder(source) .replace(Regex("(<$TAG[^>]*?)(\\s*/>)"), "\$1></$TAG>") } return StringBuilder(source) .replace(Regex("<$TAG([^>]*(?<! )) */>"), { it -> fromHTMLToShortcode(it) }) .replace(Regex("<$TAG([^>]*(?<! )) *></$TAG>"), { it -> fromHTMLToShortcode(it) }) } /** * This function is used to convert VideoPress shortcode to HTML video. * Called by `beforeHtmlProcessed`. * * For example, a shortcode like the following * `[wpvideo OcobLTqC w=640 h=400 autoplay=true html5only=true3]` will be converted to * `<video videopress_hidden_id=OcobLTqC w=640 h=400 autoplay=true html5only=true3> */ private fun fromVideoPressShortCodeToHTML(source: MatchResult): String { val match = source.groupValues.get(1) val splittedMatch = match.split(" ") val attributesBuilder = StringBuilder() attributesBuilder.append("<$TAG ") splittedMatch.forEach { if (!it.isBlank()) { if (it.contains('=')) { attributesBuilder.append(it) } else { // This is the videopress ID attributesBuilder.append("$ATTRIBUTE_VIDEOPRESS_HIDDEN_ID=" + it) } attributesBuilder.append(' ') } } attributesBuilder.append(" />") return attributesBuilder.toString() } /** * This function is used to convert HTML video tag to the correct video shortcode. * At the moment standard WordPress `video` shortcodes and VideoPress `wpvideo` shortcodes are supported. */ private fun fromHTMLToShortcode(source: MatchResult): String { val match = source.groupValues.get(1) val splittedMatch = match.split(" ") val attributesBuilder = StringBuilder() var isVideoPress = false splittedMatch.forEach { if (!it.isBlank()) { if (it.contains(ATTRIBUTE_VIDEOPRESS_HIDDEN_ID)) { // This is the videopress ID attribute val splitted = it.split("=") if (splitted.size == 2) { // just make sure there is a correct ID attributesBuilder.append(splitted[1].replace("\"", "")) isVideoPress = true } } else if (it.contains(ATTRIBUTE_VIDEOPRESS_HIDDEN_SRC)) { // nope - do nothing. It's just used to keep a reference to the real src of the video, // and use it to play the video in the apps } else { attributesBuilder.append(it) } attributesBuilder.append(' ') } } val shotcodeTag = if (isVideoPress) TAG_VIDEOPRESS_SHORTCODE else TAG return "[$shotcodeTag " + attributesBuilder.toString().trim() + "]" } }
wordpress-shortcodes/src/main/java/org/wordpress/aztec/plugins/shortcodes/VideoShortcodePlugin.kt
780132688
package com.junnanhao.next.data import android.support.annotation.NonNull import com.junnanhao.next.data.model.Song import io.reactivex.Observable /** * Created by Jonas on 2017/5/29. * music data source */ interface SongsDataSource { fun isInitialized(): Boolean fun scanMusic(): Observable<List<Song>> fun getSongs():List<Song> fun getSong(@NonNull songId: Long): Observable<Song> fun saveSong(@NonNull song: Song): Observable<Song> }
app/src/main/java/com/junnanhao/next/data/SongsDataSource.kt
1375253340
/** * The MIT License (MIT) * * Copyright (c) 2019 vk.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. */ // ********************************************************************* // THIS FILE IS AUTO GENERATED! // DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING. // ********************************************************************* package com.vk.sdk.api.groups.dto import com.google.gson.annotations.SerializedName import kotlin.Int enum class GroupsGroupFullSection( val value: Int ) { @SerializedName("0") NONE(0), @SerializedName("1") PHOTOS(1), @SerializedName("2") TOPICS(2), @SerializedName("3") AUDIOS(3), @SerializedName("4") VIDEOS(4), @SerializedName("5") MARKET(5), @SerializedName("6") STORIES(6), @SerializedName("7") APPS(7), @SerializedName("8") FOLLOWERS(8), @SerializedName("9") LINKS(9), @SerializedName("10") EVENTS(10), @SerializedName("11") PLACES(11), @SerializedName("12") CONTACTS(12), @SerializedName("13") APP_BTNS(13), @SerializedName("14") DOCS(14), @SerializedName("15") EVENT_COUNTERS(15), @SerializedName("16") GROUP_MESSAGES(16), @SerializedName("24") ALBUMS(24), @SerializedName("26") CATEGORIES(26), @SerializedName("27") ADMIN_HELP(27), @SerializedName("31") APP_WIDGET(31), @SerializedName("32") PUBLIC_HELP(32), @SerializedName("33") HS_DONATION_APP(33), @SerializedName("34") HS_MARKET_APP(34), @SerializedName("35") ADDRESSES(35), @SerializedName("36") ARTIST_PAGE(36), @SerializedName("37") PODCAST(37), @SerializedName("39") ARTICLES(39), @SerializedName("40") ADMIN_TIPS(40), @SerializedName("41") MENU(41), @SerializedName("42") FIXED_POST(42), @SerializedName("43") CHATS(43), @SerializedName("44") EVERGREEN_NOTICE(44), @SerializedName("45") MUSICIANS(45), @SerializedName("46") NARRATIVES(46), @SerializedName("47") DONUT_DONATE(47), @SerializedName("48") CLIPS(48), @SerializedName("49") MARKET_CART(49), @SerializedName("50") CURATORS(50), @SerializedName("51") MARKET_SERVICES(51), @SerializedName("53") CLASSIFIEDS(53), @SerializedName("54") TEXTLIVES(54), @SerializedName("55") DONUT_FOR_DONS(55), @SerializedName("57") BADGES(57), @SerializedName("58") CHATS_CREATION(58); }
api/src/main/java/com/vk/sdk/api/groups/dto/GroupsGroupFullSection.kt
53194295
/* * Copyright 2016 Pedro Rodrigues * * 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.hpedrorodrigues.gzmd.constant object PreferenceKey { val ASK_TO_EXIT = "close_app" val ENABLE_AUTO_SCROLL = "enable_auto_scroll" val NIGHT_MODE = "night_mode" val KEEP_SCREEN_ON = "keep_screen_on" val SCROLL_SPEED = "scroll_speed" val TEXT_SIZE = "text_size" }
app/src/main/kotlin/com/hpedrorodrigues/gzmd/constant/PreferenceKey.kt
2657861523
package de.tum.`in`.tumcampusapp.component.tumui.lectures.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.CheckBox import android.widget.CompoundButton import de.tum.`in`.tumcampusapp.R import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarController import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CalendarItem import de.tum.`in`.tumcampusapp.utils.Utils import java.lang.Long.parseLong class LectureListSelectionAdapter( context: Context, private val calendarItems: List<CalendarItem>, private val appWidgetId: Int ) : BaseAdapter(), CompoundButton.OnCheckedChangeListener { private val calendarController: CalendarController = CalendarController(context) private val inflater: LayoutInflater = LayoutInflater.from(context) override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) { // save new preferences Utils.logv("Widget asked to change ${buttonView.text} to $isChecked") if (isChecked) { calendarController.deleteLectureFromBlacklist(this.appWidgetId, buttonView.text as String) } else { calendarController.addLectureToBlacklist(this.appWidgetId, buttonView.text as String) } } override fun getCount() = calendarItems.size override fun getItem(position: Int) = calendarItems[position] override fun getItemId(position: Int) = parseLong(calendarItems[position].nr) override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { val view: View = convertView ?: inflater.inflate(R.layout.list_timetable_configure_item, parent, false) val checkBox = view.findViewById<CheckBox>(R.id.timetable_configure_item) checkBox.isChecked = !calendarItems[position].blacklisted checkBox.text = calendarItems[position].title checkBox.setOnCheckedChangeListener(this) return view } }
app/src/main/java/de/tum/in/tumcampusapp/component/tumui/lectures/adapter/LectureListSelectionAdapter.kt
3959611963
fun sum(a : Int, b : Int): Int { return a + b } fun factorial20() : Int { var res = 1 for (n in (1..20)) { res *= n } return res // it's another comment } fun my(first : Double, second : Char, f : Int) { var third = 2 * f; var forth = 3 * first; val fifth = 100 * 9 * 3423 * 123 * 324; var sixth = second; second = 'a'; return; }
src/test/resources/org/jetbrains/pmdkotlin/ignoreIdentifiersAndLiteralsTest/IgnoreIdentifiers2.kt
578681490
package info.nightscout.androidaps.plugins.constraints.versionChecker import android.content.Context import android.net.ConnectivityManager import info.nightscout.androidaps.BuildConfig import info.nightscout.androidaps.MainApp import info.nightscout.androidaps.R import info.nightscout.androidaps.logging.L import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.utils.SP import org.slf4j.LoggerFactory import java.io.IOException import java.net.URL import java.util.concurrent.TimeUnit // check network connection fun isConnected(): Boolean { val connMgr = MainApp.instance().applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager return connMgr.activeNetworkInfo?.isConnected ?: false } private val log = LoggerFactory.getLogger(L.CORE) fun triggerCheckVersion() { if (!SP.contains(R.string.key_last_time_this_version_detected)) { // On a new installation, set it as 30 days old in order to warn that there is a new version. SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30)) } // If we are good, only check once every day. if (System.currentTimeMillis() > SP.getLong(R.string.key_last_time_this_version_detected, 0) + CHECK_EVERY) { checkVersion() } } private fun checkVersion() = if (isConnected()) { Thread { try { val version: String? = findVersion(URL("https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/build.gradle").readText()) compareWithCurrentVersion(version, BuildConfig.VERSION_NAME) } catch (e: IOException) { log.debug("Github master version check error: $e") } }.start() } else log.debug("Github master version no checked. No connectivity") fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) { val newVersionElements = newVersion.toNumberList() val currentVersionElements = currentVersion.toNumberList() if (newVersionElements == null || newVersionElements.isEmpty()) { onVersionNotDetectable() return } if (currentVersionElements == null || currentVersionElements.isEmpty()) { // current version scrambled?! onNewVersionDetected(currentVersion, newVersion) return } newVersionElements.take(3).forEachIndexed { i, newElem -> val currElem: Int = currentVersionElements.getOrNull(i) ?: return onNewVersionDetected(currentVersion, newVersion) (newElem - currElem).let { when { it > 0 -> return onNewVersionDetected(currentVersion, newVersion) it < 0 -> return onOlderVersionDetected() it == 0 -> Unit } } } onSameVersionDetected() } private fun onOlderVersionDetected() { log.debug("Version newer than master. Are you developer?") SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis()) } fun onSameVersionDetected() { SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis()) } fun onVersionNotDetectable() { log.debug("fetch failed") } fun onNewVersionDetected(currentVersion: String, newVersion: String?) { val now = System.currentTimeMillis() if (now > SP.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) { log.debug("Version ${currentVersion} outdated. Found $newVersion") val notification = Notification(Notification.NEWVERSIONDETECTED, String.format(MainApp.gs(R.string.versionavailable), newVersion.toString()), Notification.LOW) RxBus.send(EventNewNotification(notification)) SP.putLong(R.string.key_last_versionchecker_warning, now) } } @Deprecated(replaceWith = ReplaceWith("numericVersionPart()"), message = "Will not work if RCs have another index number in it.") fun String.versionStrip() = this.mapNotNull { when (it) { in '0'..'9' -> it '.' -> it else -> null } }.joinToString(separator = "") fun String.numericVersionPart(): String = "(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1) ?: "" fun String?.toNumberList() = this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() } fun findVersion(file: String?): String? { val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex() return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull() } val CHECK_EVERY = TimeUnit.DAYS.toMillis(1) val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt
3568804962
package de.westnordost.streetcomplete.view import android.content.Context import android.graphics.Bitmap import android.graphics.Matrix import android.graphics.Shader import android.graphics.drawable.BitmapDrawable import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import android.widget.ImageView import android.widget.RelativeLayout import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.util.BitmapUtil import kotlinx.android.synthetic.main.side_select_puzzle.view.* class StreetSideSelectPuzzle @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : FrameLayout(context, attrs, defStyleAttr) { var listener: ((isRight:Boolean) -> Unit)? = null set(value) { field = value leftSide.setOnClickListener { listener?.invoke(false) } rightSide.setOnClickListener { listener?.invoke(true) } } private var leftImageResId: Int = 0 private var rightImageResId: Int = 0 private var isLeftImageSet: Boolean = false private var isRightImageSet: Boolean = false private var onlyShowingOneSide: Boolean = false init { LayoutInflater.from(context).inflate(R.layout.side_select_puzzle, this, true) addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ -> val width = Math.min(bottom - top, right - left) val height = Math.max(bottom - top, right - left) val params = rotateContainer.layoutParams if(width != params.width || height != params.height) { params.width = width params.height = height rotateContainer.layoutParams = params } val streetWidth = if (onlyShowingOneSide) width else width / 2 if (!isLeftImageSet && leftImageResId != 0) { setStreetDrawable(leftImageResId, streetWidth, leftSideImage, true) isLeftImageSet = true } if (!isRightImageSet && rightImageResId != 0) { setStreetDrawable(rightImageResId, streetWidth, rightSideImage, false) isRightImageSet = true } } } fun setStreetRotation(rotation: Float) { rotateContainer.rotation = rotation val scale = Math.abs(Math.cos(rotation * Math.PI / 180)).toFloat() rotateContainer.scaleX = 1 + scale * 2 / 3f rotateContainer.scaleY = 1 + scale * 2 / 3f } fun setLeftSideImageResource(resId: Int) { leftImageResId = resId } fun setRightSideImageResource(resId: Int) { rightImageResId = resId } fun replaceLeftSideImageResource(resId: Int) { leftImageResId = resId replaceAnimated(resId, leftSideImage, true) } fun replaceRightSideImageResource(resId: Int) { rightImageResId = resId replaceAnimated(resId, rightSideImage, false) } fun showOnlyRightSide() { isRightImageSet = false onlyShowingOneSide = true val params = RelativeLayout.LayoutParams(0, 0) params.addRule(RelativeLayout.ALIGN_PARENT_LEFT) strut.layoutParams = params } fun showOnlyLeftSide() { isLeftImageSet = false onlyShowingOneSide = true val params = RelativeLayout.LayoutParams(0, 0) params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) strut.layoutParams = params } fun showBothSides() { isRightImageSet = false isLeftImageSet = isRightImageSet onlyShowingOneSide = false val params = RelativeLayout.LayoutParams(0, 0) params.addRule(RelativeLayout.CENTER_HORIZONTAL) strut.layoutParams = params } private fun replaceAnimated(resId: Int, imgView: ImageView, flip180Degrees: Boolean) { val width = if (onlyShowingOneSide) rotateContainer.width else rotateContainer.width / 2 setStreetDrawable(resId, width, imgView, flip180Degrees) (imgView.parent as View).bringToFront() imgView.scaleX = 3f imgView.scaleY = 3f imgView.animate().scaleX(1f).scaleY(1f) } private fun setStreetDrawable(resId: Int, width: Int, imageView: ImageView, flip180Degrees: Boolean) { val drawable = scaleToWidth(BitmapUtil.asBitmapDrawable(resources, resId), width, flip180Degrees) drawable.tileModeY = Shader.TileMode.REPEAT imageView.setImageDrawable(drawable) } private fun scaleToWidth(drawable: BitmapDrawable, width: Int, flip180Degrees: Boolean): BitmapDrawable { val m = Matrix() val scale = width.toFloat() / drawable.intrinsicWidth m.postScale(scale, scale) if (flip180Degrees) m.postRotate(180f) val bitmap = Bitmap.createBitmap( drawable.bitmap, 0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight, m, true ) return BitmapDrawable(resources, bitmap) } }
app/src/main/java/de/westnordost/streetcomplete/view/StreetSideSelectPuzzle.kt
1496648295
package org.stepik.android.presentation.magic_links import io.reactivex.Scheduler import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.magic_links.interactor.MagicLinkInteractor import ru.nobird.android.presentation.base.PresenterBase import javax.inject.Inject class MagicLinkPresenter @Inject constructor( private val magicLinkInteractor: MagicLinkInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<MagicLinkView>() { private var state: MagicLinkView.State = MagicLinkView.State.Idle set(value) { field = value view?.setState(value) } fun onData(url: String) { if (state != MagicLinkView.State.Idle) return state = MagicLinkView.State.Loading compositeDisposable += magicLinkInteractor .createMagicLink(url) .observeOn(mainScheduler) .subscribeOn(backgroundScheduler) .subscribeBy( onSuccess = { state = MagicLinkView.State.Success(it.url) }, onError = { state = MagicLinkView.State.Success(url) } ) } }
app/src/main/java/org/stepik/android/presentation/magic_links/MagicLinkPresenter.kt
2286660604
class Outer { inner class Inner { fun box() = "OK" } } fun box() = Outer().Inner().box() fun main(args: Array<String>) { println(box()) }
backend.native/tests/codegen/innerClass/simple.kt
2525789148
package lt.markmerkk.app.mvp.interactors import com.badlogic.gdx.Gdx import lt.markmerkk.app.mvp.NetworkEventProvider import lt.markmerkk.app.network.events.EventPlayersPosition import lt.markmerkk.app.network.events.EventPlayersRegister import lt.markmerkk.app.network.events.NetworkEvent import org.slf4j.LoggerFactory /** * @author mariusmerkevicius * @since 2016-10-30 */ class NetworkEventProviderClientImpl( private val listener: ClientEventListener ) : NetworkEventProvider { override fun event(eventObject: NetworkEvent) { Gdx.app.postRunnable { when (eventObject) { is EventPlayersRegister -> listener.onPlayersRegister(eventObject.registerPlayers) is EventPlayersPosition -> listener.onPlayersPosition(eventObject.playersPosition) else -> logger.debug("Undefined event received: $eventObject") } } } override fun connected(connectionId: Int) { Gdx.app.postRunnable { listener.onConnected(connectionId) } } override fun disconnected(connectionId: Int) { Gdx.app.postRunnable { listener.onDisconnected(connectionId) } } companion object { val logger = LoggerFactory.getLogger(NetworkEventProviderClientImpl::class.java)!! } }
core/src/main/java/lt/markmerkk/app/mvp/interactors/NetworkEventProviderClientImpl.kt
2557173315
package su.jfdev.test.immutability import com.google.common.collect.ImmutableSet.* import su.jfdev.test.immutability.Immutability.* class SuiteBuilder<T> { private val sub: Builder<Immutability<T>> = builder() infix fun append(immutability: Immutability<T>) = apply { sub.add(immutability) } operator fun invoke(name: String) = Suite(name, sub.build()) companion object { fun <T> build(name: String, builder: SuiteBuilder<T>.() -> Unit) = SuiteBuilder<T>() .apply(builder)("$name should be immutable") } }
test/src/main/kotlin/su/jfdev/test/immutability/SuiteBuilder.kt
656511672
package de.d3adspace.mercantor.core import de.d3adspace.mercantor.core.service.ServiceRepositoryImpl /** * @author Felix Klauke <info@felix-klauke.de> */ object MercantorFactory { fun createMercantor(): Mercantor { val serviceRepository = ServiceRepositoryImpl() return MercantorImpl(serviceRepository) } }
core/src/main/kotlin/de/d3adspace/mercantor/core/MercantorFactory.kt
3277694809
package com.commit451.gitlab.model.api import android.os.Parcelable import androidx.annotation.StringDef import com.squareup.moshi.Json import kotlinx.android.parcel.Parcelize import java.util.Date /** * Todos. Not processing Target, since it is different depending on what the type is, which * makes it not play nice with any automated json parsing */ @Parcelize data class Todo( @Json(name = "id") var id: String? = null, @Json(name = "project") var project: Project? = null, @Json(name = "author") var author: User? = null, @Json(name = "action_name") var actionName: String? = null, @Json(name = "target_type") @TargetType @get:TargetType var targetType: String? = null, @Json(name = "target_url") var targetUrl: String? = null, @Json(name = "body") var body: String? = null, @Json(name = "state") @State @get:State var state: String? = null, @Json(name = "created_at") var createdAt: Date? = null ) : Parcelable { companion object { const val TARGET_ISSUE = "Issue" const val TARGET_MERGE_REQUEST = "MergeRequest" const val STATE_PENDING = "pending" const val STATE_DONE = "done" } @StringDef(TARGET_ISSUE, TARGET_MERGE_REQUEST) @Retention(AnnotationRetention.SOURCE) annotation class TargetType @StringDef(STATE_PENDING, STATE_DONE) @Retention(AnnotationRetention.SOURCE) annotation class State }
app/src/main/java/com/commit451/gitlab/model/api/Todo.kt
3373436536
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.github.divinespear.plugin import org.gradle.api.Plugin import org.gradle.api.Project import org.gradle.api.plugins.JavaLibraryPlugin import org.gradle.kotlin.dsl.* class JpaSchemaGenerationPlugin : Plugin<Project> { companion object { private const val SPRING_VERSION = "[5.0,6.0)" private val SPRING_DEPENDENCIES = listOf( "org.springframework:spring-orm:${SPRING_VERSION}", "org.springframework:spring-context:${SPRING_VERSION}", "org.springframework:spring-aspects:${SPRING_VERSION}" ) } override fun apply(project: Project) { project.run { plugins.apply(JavaLibraryPlugin::class) configurations { register(CONFIGURATION_NAME) } dependencies { SPRING_DEPENDENCIES.forEach { CONFIGURATION_NAME(it) } } extensions.create<JpaSchemaGenerationExtension>(EXTENSION_NAME).apply { defaultOutputDirectory = project.buildDir.resolve("generated-schema") targets = project.container(JpaSchemaGenerationProperties::class) } tasks { register(PLUGIN_NAME, JpaSchemaGenerationTask::class) { group = "help" dependsOn(project.tasks.getByPath("classes")) } } } } }
src/main/kotlin/io/github/divinespear/plugin/plugin.kt
3801558953
package com.exaltead.sceneclassifier.extraction import android.media.AudioFormat import android.media.AudioFormat.CHANNEL_IN_MONO const val SAMPLING_RATE = 44100 const val SAMPLE_DURATION = 1 const val SAMPLE_MAX_LENGHT = SAMPLING_RATE * SAMPLE_DURATION const val CHANNELS = CHANNEL_IN_MONO const val AUDIO_ENCODING = AudioFormat.ENCODING_PCM_FLOAT
SceneClassifier/app/src/main/java/com/exaltead/sceneclassifier/extraction/constants.kt
635246519
package com.abdulmujibaliu.koutube.fragments.videos import com.abdulmujibaliu.koutube.data.models.PlayListItemsResult import com.abdulmujibaliu.koutube.data.models.YoutubeVideo import com.aliumujib.mkanapps.coremodule.basemvpcontracts.BaseContracts /** * Created by aliumujib on 25/02/2018. */ interface VideosContracts { interface VideosView : BaseContracts.BaseView<VideosPresenter> { fun setData(playLists: List<YoutubeVideo>) fun setNextPage(playLists: List<YoutubeVideo>) fun launchVideoPlayer(video: YoutubeVideo) } interface VideosPresenter : BaseContracts.BasePresenter { fun getVideos() fun playVideo(video: YoutubeVideo) } }
videos_module/src/main/java/com/abdulmujibaliu/koutube/fragments/videos/VideosContracts.kt
4207752860
package de.handler.mobile.wifivideo import android.net.wifi.p2p.WifiP2pDevice import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import de.handler.mobile.wifivideo.DeviceListFragment.OnListFragmentInteractionListener class WifiP2pDeviceRecyclerViewAdapter(private val listener: OnListFragmentInteractionListener?) : RecyclerView.Adapter<WifiP2pDeviceRecyclerViewAdapter.ViewHolder>() { var values: List<WifiP2pDevice>? = null get() = field set(values) { field = values notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.item_device, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindItem(values?.get(position)) holder.view.setOnClickListener { holder.item?.let { it1 -> listener?.onListFragmentInteraction(it1) } } } override fun getItemCount(): Int { return if (values == null) return 0 else { values!!.size } } inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) { private val deviceNameTextView: TextView = view.findViewById<View>(R.id.id) as TextView private val deviceAddressTextView: TextView = view.findViewById<View>(R.id.content) as TextView var item: WifiP2pDevice? = null fun bindItem(wifiP2pDevice: WifiP2pDevice?) { item = wifiP2pDevice deviceNameTextView.text = wifiP2pDevice?.deviceName deviceAddressTextView.text = wifiP2pDevice?.deviceAddress } } }
app/src/main/java/de/handler/mobile/wifivideo/WifiP2pDeviceRecyclerViewAdapter.kt
3735917449
package info.nightscout.androidaps.activities import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.util.DisplayMetrics import android.view.ViewGroup import android.widget.LinearLayout import android.widget.RelativeLayout import android.widget.TextView import com.google.android.material.datepicker.MaterialDatePicker import com.jjoe64.graphview.GraphView import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.fragments.HistoryBrowserData import info.nightscout.androidaps.databinding.ActivityHistorybrowseBinding import info.nightscout.androidaps.events.EventAutosensCalculationFinished import info.nightscout.androidaps.events.EventCustomCalculationFinished import info.nightscout.androidaps.events.EventRefreshOverview import info.nightscout.androidaps.events.EventScale import info.nightscout.androidaps.extensions.toVisibility import info.nightscout.androidaps.extensions.toVisibilityKeepSpace import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.BuildHelper import info.nightscout.androidaps.plugins.general.overview.OverviewMenus import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewGraph import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DefaultValueHelper import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.rx.AapsSchedulers import info.nightscout.androidaps.workflow.CalculationWorkflow import info.nightscout.shared.logging.LTag import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import java.util.* import javax.inject.Inject import kotlin.math.min class HistoryBrowseActivity : NoSplashAppCompatActivity() { @Inject lateinit var historyBrowserData: HistoryBrowserData @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var defaultValueHelper: DefaultValueHelper @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var buildHelper: BuildHelper @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var overviewMenus: OverviewMenus @Inject lateinit var dateUtil: DateUtil @Inject lateinit var context: Context @Inject lateinit var calculationWorkflow: CalculationWorkflow private val disposable = CompositeDisposable() private val secondaryGraphs = ArrayList<GraphView>() private val secondaryGraphsLabel = ArrayList<TextView>() private var axisWidth: Int = 0 private var rangeToDisplay = 24 // for graph // private var start: Long = 0 private lateinit var binding: ActivityHistorybrowseBinding private var destroyed = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityHistorybrowseBinding.inflate(layoutInflater) setContentView(binding.root) binding.left.setOnClickListener { adjustTimeRange(historyBrowserData.overviewData.fromTime - T.hours(rangeToDisplay.toLong()).msecs()) loadAll("onClickLeft") } binding.right.setOnClickListener { adjustTimeRange(historyBrowserData.overviewData.fromTime + T.hours(rangeToDisplay.toLong()).msecs()) loadAll("onClickRight") } binding.end.setOnClickListener { setTime(dateUtil.now()) loadAll("onClickEnd") } binding.zoom.setOnClickListener { var hours = rangeToDisplay + 6 hours = if (hours > 24) 6 else hours rxBus.send(EventScale(hours)) } binding.zoom.setOnLongClickListener { Calendar.getInstance().also { calendar -> calendar.timeInMillis = historyBrowserData.overviewData.fromTime calendar[Calendar.MILLISECOND] = 0 calendar[Calendar.SECOND] = 0 calendar[Calendar.MINUTE] = 0 calendar[Calendar.HOUR_OF_DAY] = 0 setTime(calendar.timeInMillis) } loadAll("onLongClickZoom") true } binding.date.setOnClickListener { MaterialDatePicker.Builder.datePicker() .setSelection(dateUtil.timeStampToUtcDateMillis(historyBrowserData.overviewData.fromTime)) .setTheme(R.style.DatePicker) .build() .apply { addOnPositiveButtonClickListener { selection -> setTime(dateUtil.mergeUtcDateToTimestamp(historyBrowserData.overviewData.fromTime, selection)) binding.date.text = dateUtil.dateAndTimeString(historyBrowserData.overviewData.fromTime) loadAll("onClickDate") } } .show(supportFragmentManager, "history_date_picker") } val dm = DisplayMetrics() @Suppress("DEPRECATION") if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) display?.getRealMetrics(dm) else windowManager.defaultDisplay.getMetrics(dm) axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80 binding.bgGraph.gridLabelRenderer?.gridColor = rh.gac(this, R.attr.graphGrid) binding.bgGraph.gridLabelRenderer?.reloadStyles() binding.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth overviewMenus.setupChartMenu(context, binding.chartMenuButton) prepareGraphsIfNeeded(overviewMenus.setting.size) savedInstanceState?.let { bundle -> rangeToDisplay = bundle.getInt("rangeToDisplay", 0) historyBrowserData.overviewData.fromTime = bundle.getLong("start", 0) historyBrowserData.overviewData.toTime = bundle.getLong("end", 0) } } override fun onPause() { super.onPause() disposable.clear() calculationWorkflow.stopCalculation(CalculationWorkflow.HISTORY_CALCULATION, "onPause") } @Synchronized override fun onDestroy() { destroyed = true super.onDestroy() } override fun onResume() { super.onResume() disposable += rxBus .toObservable(EventAutosensCalculationFinished::class.java) .observeOn(aapsSchedulers.io) .subscribe({ // catch only events from iobCobCalculator if (it.cause is EventCustomCalculationFinished) refreshLoop("EventAutosensCalculationFinished") }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventIobCalculationProgress::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateCalcProgress(it.pass.finalPercent(it.progressPct)) }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventUpdateOverviewGraph::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGUI("EventRefreshOverview") }, fabricPrivacy::logException) disposable += rxBus .toObservable(EventScale::class.java) .observeOn(aapsSchedulers.main) .subscribe({ rangeToDisplay = it.hours setTime(historyBrowserData.overviewData.fromTime) loadAll("rangeChange") }, fabricPrivacy::logException) updateCalcProgress(100) if (historyBrowserData.overviewData.fromTime == 0L) { // set start of current day setTime(dateUtil.now()) loadAll("onResume") } else { updateGUI("onResume") } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putInt("rangeToDisplay", rangeToDisplay) outState.putLong("start", historyBrowserData.overviewData.fromTime) outState.putLong("end", historyBrowserData.overviewData.toTime) } private fun prepareGraphsIfNeeded(numOfGraphs: Int) { if (numOfGraphs != secondaryGraphs.size - 1) { //aapsLogger.debug("New secondary graph count ${numOfGraphs-1}") // rebuild needed secondaryGraphs.clear() secondaryGraphsLabel.clear() binding.iobGraph.removeAllViews() for (i in 1 until numOfGraphs) { val relativeLayout = RelativeLayout(this) relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) val graph = GraphView(this) graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rh.dpToPx(100)).also { it.setMargins(0, rh.dpToPx(15), 0, rh.dpToPx(10)) } graph.gridLabelRenderer?.gridColor = rh.gac(R.attr.graphGrid) graph.gridLabelRenderer?.reloadStyles() graph.gridLabelRenderer?.isHorizontalLabelsVisible = false graph.gridLabelRenderer?.labelVerticalWidth = axisWidth graph.gridLabelRenderer?.numVerticalLabels = 3 graph.viewport.backgroundColor = rh.gac(this, R.attr.viewPortBackgroundColor) relativeLayout.addView(graph) val label = TextView(this) val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(rh.dpToPx(30), rh.dpToPx(25), 0, 0) } layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP) layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT) label.layoutParams = layoutParams relativeLayout.addView(label) secondaryGraphsLabel.add(label) binding.iobGraph.addView(relativeLayout) secondaryGraphs.add(graph) } } } @Suppress("SameParameterValue") private fun loadAll(from: String) { updateDate() runCalculation(from) } private fun setTime(start: Long) { GregorianCalendar().also { calendar -> calendar.timeInMillis = start calendar[Calendar.MILLISECOND] = 0 calendar[Calendar.SECOND] = 0 calendar[Calendar.MINUTE] = 0 calendar[Calendar.HOUR_OF_DAY] -= (calendar[Calendar.HOUR_OF_DAY] % rangeToDisplay) adjustTimeRange(calendar.timeInMillis) } } private fun adjustTimeRange(start: Long) { historyBrowserData.overviewData.fromTime = start historyBrowserData.overviewData.toTime = historyBrowserData.overviewData.fromTime + T.hours(rangeToDisplay.toLong()).msecs() historyBrowserData.overviewData.endTime = historyBrowserData.overviewData.toTime } private fun runCalculation(from: String) { calculationWorkflow.runCalculation( CalculationWorkflow.HISTORY_CALCULATION, historyBrowserData.iobCobCalculator, historyBrowserData.overviewData, from, historyBrowserData.overviewData.toTime, bgDataReload = true, limitDataToOldestAvailable = false, cause = EventCustomCalculationFinished(), runLoop = false ) } @Volatile var runningRefresh = false @Suppress("SameParameterValue") private fun refreshLoop(from: String) { if (runningRefresh) return runningRefresh = true rxBus.send(EventRefreshOverview(from)) aapsLogger.debug(LTag.UI, "refreshLoop finished") runningRefresh = false } private fun updateDate() { binding.date.text = dateUtil.dateAndTimeString(historyBrowserData.overviewData.fromTime) binding.zoom.text = rangeToDisplay.toString() } @Suppress("UNUSED_PARAMETER") @SuppressLint("SetTextI18n") fun updateGUI(from: String) { aapsLogger.debug(LTag.UI, "updateGui $from") updateDate() val pump = activePlugin.activePump val graphData = GraphData(injector, binding.bgGraph, historyBrowserData.overviewData) val menuChartSettings = overviewMenus.setting graphData.addInRangeArea(historyBrowserData.overviewData.fromTime, historyBrowserData.overviewData.endTime, defaultValueHelper.determineLowLine(), defaultValueHelper.determineHighLine()) graphData.addBgReadings(menuChartSettings[0][OverviewMenus.CharType.PRE.ordinal], context) if (buildHelper.isDev()) graphData.addBucketedData() graphData.addTreatments(context) graphData.addEps(context, 0.95) if (menuChartSettings[0][OverviewMenus.CharType.TREAT.ordinal]) graphData.addTherapyEvents() if (menuChartSettings[0][OverviewMenus.CharType.ACT.ordinal]) graphData.addActivity(0.8) if (pump.pumpDescription.isTempBasalCapable && menuChartSettings[0][OverviewMenus.CharType.BAS.ordinal]) graphData.addBasals() graphData.addTargetLine() graphData.addNowLine(dateUtil.now()) // set manual x bounds to have nice steps graphData.setNumVerticalLabels() graphData.formatAxis(historyBrowserData.overviewData.fromTime, historyBrowserData.overviewData.endTime) graphData.performUpdate() // 2nd graphs prepareGraphsIfNeeded(menuChartSettings.size) val secondaryGraphsData: ArrayList<GraphData> = ArrayList() val now = System.currentTimeMillis() for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) { val secondGraphData = GraphData(injector, secondaryGraphs[g], historyBrowserData.overviewData) var useABSForScale = false var useIobForScale = false var useCobForScale = false var useDevForScale = false var useRatioForScale = false var useDSForScale = false var useBGIForScale = false when { menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] -> useBGIForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true } val alignDevBgiScale = menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] && menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] if (menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(useABSForScale, 1.0) if (menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(useIobForScale, 1.0) if (menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(useCobForScale, if (useCobForScale) 1.0 else 0.5) if (menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(useDevForScale, 1.0) if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(useBGIForScale, if (alignDevBgiScale) 1.0 else 0.8) if (menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(useRatioForScale, if (useRatioForScale) 1.0 else 0.8) if (menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(useDSForScale, 1.0) // set manual x bounds to have nice steps secondGraphData.formatAxis(historyBrowserData.overviewData.fromTime, historyBrowserData.overviewData.endTime) secondGraphData.addNowLine(now) secondaryGraphsData.add(secondGraphData) } for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) { secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1) secondaryGraphs[g].visibility = ( menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] || menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] ).toVisibility() secondaryGraphsData[g].performUpdate() } } private fun updateCalcProgress(percent: Int) { binding.progressBar.progress = percent binding.progressBar.visibility = (percent != 100).toVisibilityKeepSpace() } }
app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt
3932539420
package venus.riscv /** Describes how to get fields from RV32 instruction formats */ enum class InstructionField(val lo: Int, val hi: Int) { ENTIRE(0, 32), OPCODE(0, 7), RD(7, 12), FUNCT3(12, 15), RS1(15, 20), RS2(20, 25), FUNCT7(25, 32), IMM_11_0(20, 32), IMM_4_0(7, 12), IMM_11_5(25, 32), IMM_11_B(7, 8), IMM_4_1(8, 12), IMM_10_5(25, 31), IMM_12(31, 32), IMM_31_12(12, 32), IMM_19_12(12, 20), IMM_11_J(20, 21), IMM_10_1(21, 31), IMM_20(31, 32), SHAMT(20, 25), }
src/main/kotlin/venus/riscv/InstructionField.kt
1890732538
package com.abdulmujibaliu.koutube.adapters import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import com.abdulmujibaliu.koutube.fragments.playlists.PlaylistsFragment import com.abdulmujibaliu.koutube.fragments.videos.VideosFragment /** * Created by abdulmujibaliu on 10/15/17. */ class VideoTabsAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) { override fun getCount(): Int { return 2 } val fragments : List<Fragment> = listOf(VideosFragment.newInstance(), PlaylistsFragment.newInstance()) override fun getItem(position: Int): Fragment { return if (position == 0) { fragments[0] } else { fragments[1] } } override fun getPageTitle(position: Int): String { return if(position == 0){ "VIDEOS" }else{ "PLAYLISTS" } } }
videos_module/src/main/java/com/abdulmujibaliu/koutube/adapters/VideoTabsAdapter.kt
1582371200
package com.deanveloper.slak.event.channel import com.deanveloper.slak.channel.Channel import java.time.LocalDateTime class ChannelUnarchiveEvent(channel: Channel, ts: LocalDateTime) : ChannelEvent { override val type = "channel_unarchive" override val channel = channel override val ts = ts }
src/main/kotlin/com/deanveloper/slak/event/channel/ChannelUnarchiveEvent.kt
1327234834
package info.nightscout.androidaps.plugins.general.automation.triggers import com.google.common.base.Optional import dagger.android.HasAndroidInjector import org.json.JSONObject // Used for instantiation of other triggers only class TriggerDummy(injector: HasAndroidInjector, val shouldRun: Boolean = false) : Trigger(injector) { override fun shouldRun(): Boolean { return shouldRun } override fun dataJSON(): JSONObject { throw NotImplementedError("An operation is not implemented") } override fun fromJSON(data: String): Trigger { throw NotImplementedError("An operation is not implemented") } override fun friendlyName(): Int { throw NotImplementedError("An operation is not implemented") } override fun friendlyDescription(): String { return "TriggerDummy" } override fun icon(): Optional<Int> { throw NotImplementedError("An operation is not implemented") } override fun duplicate(): Trigger { throw NotImplementedError("An operation is not implemented") } }
automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/triggers/TriggerDummy.kt
3668926244
package com.auth0.android.util import okhttp3.mockwebserver.MockResponse import java.nio.file.Files import java.nio.file.Paths internal class AuthenticationAPIMockServer : APIMockServer() { fun willReturnSuccessfulChangePassword(): AuthenticationAPIMockServer { server.enqueue(responseWithJSON("NOT REALLY A JSON", 200)) return this } fun willReturnSuccessfulPasswordlessStart(): AuthenticationAPIMockServer { val json = """{ "phone+number": "+1098098098" }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnSuccessfulSignUp(): AuthenticationAPIMockServer { val json = """{ "_id": "gjsmgdkjs72jljsf2dsdhh", "email": "support@auth0.com", "email_verified": false, "username": "support" }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnSuccessfulEmptyBody(): AuthenticationAPIMockServer { server.enqueue(responseEmpty(200)) return this } fun willReturnSuccessfulLogin(idToken: String = ID_TOKEN): AuthenticationAPIMockServer { val json = """{ "refresh_token": "$REFRESH_TOKEN", "id_token": "$idToken", "access_token": "$ACCESS_TOKEN", "token_type": "$BEARER", "expires_in": 86000 }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnSuccessfulLoginWithRecoveryCode(): AuthenticationAPIMockServer { val json = """{ "refresh_token": "$REFRESH_TOKEN", "id_token": "$ID_TOKEN", "access_token": "$ACCESS_TOKEN", "token_type": "$BEARER", "expires_in": 86000, "recovery_code": "654321" }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnInvalidRequest(): AuthenticationAPIMockServer { val json = """{ "error": "invalid_request", "error_description": "a random error" }""" server.enqueue(responseWithJSON(json, 400)) return this } fun willReturnEmptyJsonWebKeys(): AuthenticationAPIMockServer { val json = """{ "keys": [] }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnValidJsonWebKeys(): AuthenticationAPIMockServer { try { val encoded = Files.readAllBytes(Paths.get("src/test/resources/rsa_jwks.json")) val json = String(encoded) server.enqueue(responseWithJSON(json, 200)) } catch (ignored: Exception) { println("File parsing error") } return this } fun willReturnUserInfo(): AuthenticationAPIMockServer { val json = """{ "email": "p@p.xom", "email_verified": false, "picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png", "user_id": "auth0|53b995f8bce68d9fc900099c", "name": "p@p.xom", "nickname": "p", "identities": [ { "user_id": "53b995f8bce68d9fc900099c", "provider": "auth0", "connection": "Username-Password-Authentication", "isSocial": false } ], "created_at": "2014-07-06T18:33:49.005Z", "username": "p", "updated_at": "2015-09-30T19:43:48.499Z" }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnPlainTextUnauthorized(): AuthenticationAPIMockServer { server.enqueue(responseWithPlainText("Unauthorized", 401)) return this } fun willReturnTokens(): AuthenticationAPIMockServer { val json = """{ "access_token": "$ACCESS_TOKEN", "refresh_token": "$REFRESH_TOKEN", "id_token": "$ID_TOKEN", "token_type": "Bearer", "expires_in": 86000 }""" server.enqueue(responseWithJSON(json, 200)) return this } fun willReturnSuccessfulMFAChallenge(): AuthenticationAPIMockServer { val json = """{ "challenge_type":"oob", "binding_method":"prompt", "oob_code": "abcdefg" }""" server.enqueue(responseWithJSON(json, 200)) return this } private fun responseEmpty(statusCode: Int): MockResponse { return MockResponse() .setResponseCode(statusCode) } private fun responseWithPlainText(statusMessage: String, statusCode: Int): MockResponse { return MockResponse() .setResponseCode(statusCode) .addHeader("Content-Type", "text/plain") .setBody(statusMessage) } companion object { const val REFRESH_TOKEN = "REFRESH_TOKEN" const val ID_TOKEN = "ID_TOKEN" const val ACCESS_TOKEN = "ACCESS_TOKEN" private const val BEARER = "BEARER" } }
auth0/src/test/java/com/auth0/android/util/AuthenticationAPIMockServer.kt
394081903
/* * Copyright (C) 2014-2021 Arpit Khurana <arpitkh96@gmail.com>, Vishal Nehra <vishalmeham2@gmail.com>, * Emmanuel Messulam<emmanuelbendavid@gmail.com>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.filesystem.compressed.extractcontents.helpers import android.content.Context import com.amaze.filemanager.file_operations.utils.UpdatePosition import org.apache.commons.compress.archivers.tar.TarArchiveInputStream import org.apache.commons.compress.compressors.CompressorInputStream import java.io.InputStream import java.lang.reflect.Constructor abstract class AbstractCompressedTarArchiveExtractor( context: Context, filePath: String, outputPath: String, listener: OnUpdate, updatePosition: UpdatePosition ) : AbstractCommonsArchiveExtractor(context, filePath, outputPath, listener, updatePosition) { private val compressorInputStreamConstructor: Constructor<out CompressorInputStream> init { compressorInputStreamConstructor = getCompressorInputStreamClass() .getDeclaredConstructor(InputStream::class.java) compressorInputStreamConstructor.isAccessible = true } /** * Subclasses implement this method to specify the [CompressorInputStream] class to be used. It * will be used to create the backing inputstream beneath [TarArchiveInputStream] in * [createFrom]. * * @return Class representing the implementation will be handling */ abstract fun getCompressorInputStreamClass(): Class<out CompressorInputStream> override fun createFrom(inputStream: InputStream): TarArchiveInputStream { return TarArchiveInputStream(compressorInputStreamConstructor.newInstance(inputStream)) } }
app/src/main/java/com/amaze/filemanager/filesystem/compressed/extractcontents/helpers/AbstractCompressedTarArchiveExtractor.kt
2659907279
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions.branchedTransformations import org.jetbrains.kotlin.cfg.WhenChecker import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.branches import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor import org.jetbrains.kotlin.types.typeUtil.isNothing import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf object BranchedFoldingUtils { private fun getFoldableBranchedAssignment(branch: KtExpression?): KtBinaryExpression? { fun checkAssignment(expression: KtBinaryExpression): Boolean { if (expression.operationToken !in KtTokens.ALL_ASSIGNMENTS) return false val left = expression.left as? KtNameReferenceExpression ?: return false if (expression.right == null) return false val parent = expression.parent if (parent is KtBlockExpression) { return !KtPsiUtil.checkVariableDeclarationInBlock(parent, left.text) } return true } return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.takeIf(::checkAssignment) } fun getFoldableBranchedReturn(branch: KtExpression?): KtReturnExpression? = (branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.takeIf { it.returnedExpression != null && it.returnedExpression !is KtLambdaExpression && it.getTargetLabel() == null } private fun KtBinaryExpression.checkAssignmentsMatch( other: KtBinaryExpression, leftType: KotlinType, rightTypeConstructor: TypeConstructor ): Boolean { val left = this.left ?: return false val otherLeft = other.left ?: return false if (left.text != otherLeft.text || operationToken != other.operationToken || left.mainReference?.resolve() != otherLeft.mainReference?.resolve() ) return false val rightType = other.rightType() ?: return false return rightType.constructor == rightTypeConstructor || (operationToken == KtTokens.EQ && rightType.isSubtypeOf(leftType)) } private fun KtBinaryExpression.rightType(): KotlinType? { val right = this.right ?: return null val context = this.analyze() val diagnostics = context.diagnostics fun hasTypeMismatchError(e: KtExpression) = diagnostics.forElement(e).any { it.factory == Errors.TYPE_MISMATCH } if (hasTypeMismatchError(this) || hasTypeMismatchError(right)) return null return right.getType(context) } internal fun getFoldableAssignmentNumber(expression: KtExpression?): Int { expression ?: return -1 val assignments = linkedSetOf<KtBinaryExpression>() fun collectAssignmentsAndCheck(e: KtExpression?): Boolean = when (e) { is KtWhenExpression -> { val entries = e.entries !e.hasMissingCases() && entries.isNotEmpty() && entries.all { entry -> val assignment = getFoldableBranchedAssignment(entry.expression)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(entry.expression?.lastBlockStatementOrThis()) } } is KtIfExpression -> { val branches = e.branches val elseBranch = branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` branches.size > 1 && elseBranch != null && branches.all { branch -> val assignment = getFoldableBranchedAssignment(branch)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(branch?.lastBlockStatementOrThis()) } } is KtTryExpression -> { e.tryBlockAndCatchBodies().all { val assignment = getFoldableBranchedAssignment(it)?.run { assignments.add(this) } assignment != null || collectAssignmentsAndCheck(it?.lastBlockStatementOrThis()) } } is KtCallExpression -> { e.analyze().getType(e)?.isNothing() ?: false } is KtBreakExpression, is KtContinueExpression, is KtThrowExpression, is KtReturnExpression -> true else -> false } if (!collectAssignmentsAndCheck(expression)) return -1 val firstAssignment = assignments.firstOrNull { !it.right.isNullExpression() } ?: assignments.firstOrNull() ?: return 0 val leftType = firstAssignment.left?.let { it.getType(it.analyze(BodyResolveMode.PARTIAL)) } ?: return 0 val rightTypeConstructor = firstAssignment.rightType()?.constructor ?: return -1 if (assignments.any { !firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) }) { return -1 } if (expression.anyDescendantOfType<KtBinaryExpression>( predicate = { if (it.operationToken in KtTokens.ALL_ASSIGNMENTS) if (it.getNonStrictParentOfType<KtFinallySection>() != null) firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) else it !in assignments else false } ) ) { return -1 } return assignments.size } private fun getFoldableReturns(branches: List<KtExpression?>): List<KtReturnExpression>? = branches.fold<KtExpression?, MutableList<KtReturnExpression>?>(mutableListOf()) { prevList, branch -> if (prevList == null) return@fold null val foldableBranchedReturn = getFoldableBranchedReturn(branch) if (foldableBranchedReturn != null) { prevList.add(foldableBranchedReturn) } else { val currReturns = getFoldableReturns(branch?.lastBlockStatementOrThis()) ?: return@fold null prevList += currReturns } prevList } internal fun getFoldableReturns(expression: KtExpression?): List<KtReturnExpression>? = when (expression) { is KtWhenExpression -> { val entries = expression.entries when { expression.hasMissingCases() -> null entries.isEmpty() -> null else -> getFoldableReturns(entries.map { it.expression }) } } is KtIfExpression -> { val branches = expression.branches when { branches.isEmpty() -> null branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` == null -> null else -> getFoldableReturns(branches) } } is KtTryExpression -> { if (expression.finallyBlock?.finalExpression?.let { getFoldableReturns(listOf(it)) }?.isNotEmpty() == true) null else getFoldableReturns(expression.tryBlockAndCatchBodies()) } is KtCallExpression -> { if (expression.analyze().getType(expression)?.isNothing() == true) emptyList() else null } is KtBreakExpression, is KtContinueExpression, is KtThrowExpression -> emptyList() else -> null } private fun getFoldableReturnNumber(expression: KtExpression?) = getFoldableReturns(expression)?.size ?: -1 fun canFoldToReturn(expression: KtExpression?): Boolean = getFoldableReturnNumber(expression) > 0 fun tryFoldToAssignment(expression: KtExpression) { var lhs: KtExpression? = null var op: String? = null val psiFactory = KtPsiFactory(expression) fun KtBinaryExpression.replaceWithRHS() { if (lhs == null || op == null) { lhs = left!!.copy() as KtExpression op = operationReference.text } val rhs = right!! if (rhs is KtLambdaExpression && this.parent !is KtBlockExpression) { replace(psiFactory.createSingleStatementBlock(rhs)) } else { replace(rhs) } } fun lift(e: KtExpression?) { when (e) { is KtWhenExpression -> e.entries.forEach { entry -> getFoldableBranchedAssignment(entry.expression)?.replaceWithRHS() ?: lift(entry.expression?.lastBlockStatementOrThis()) } is KtIfExpression -> e.branches.forEach { branch -> getFoldableBranchedAssignment(branch)?.replaceWithRHS() ?: lift(branch?.lastBlockStatementOrThis()) } is KtTryExpression -> e.tryBlockAndCatchBodies().forEach { getFoldableBranchedAssignment(it)?.replaceWithRHS() ?: lift(it?.lastBlockStatementOrThis()) } } } lift(expression) if (lhs != null && op != null) { expression.replace(psiFactory.createExpressionByPattern("$0 $1 $2", lhs!!, op!!, expression)) } } fun foldToReturn(expression: KtExpression): KtExpression { fun KtReturnExpression.replaceWithReturned() { replace(returnedExpression!!) } fun lift(e: KtExpression?) { when (e) { is KtWhenExpression -> e.entries.forEach { entry -> val entryExpr = entry.expression getFoldableBranchedReturn(entryExpr)?.replaceWithReturned() ?: lift(entryExpr?.lastBlockStatementOrThis()) } is KtIfExpression -> e.branches.forEach { branch -> getFoldableBranchedReturn(branch)?.replaceWithReturned() ?: lift(branch?.lastBlockStatementOrThis()) } is KtTryExpression -> e.tryBlockAndCatchBodies().forEach { getFoldableBranchedReturn(it)?.replaceWithReturned() ?: lift(it?.lastBlockStatementOrThis()) } } } lift(expression) return expression.replaced(KtPsiFactory(expression).createExpressionByPattern("return $0", expression)) } private fun KtTryExpression.tryBlockAndCatchBodies(): List<KtExpression?> = listOf(tryBlock) + catchClauses.map { it.catchBody } private fun KtWhenExpression.hasMissingCases(): Boolean = !KtPsiUtil.checkWhenExpressionHasSingleElse(this) && WhenChecker.getMissingCases(this, safeAnalyzeNonSourceRootCode()).isNotEmpty() }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt
3283899877
/* * Copyright (c) 2020 MarkLogic Corporation * * 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.marklogic.client.test.dbfunction import com.fasterxml.jackson.databind.ObjectWriter import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.marklogic.client.DatabaseClientFactory import com.marklogic.client.io.DocumentMetadataHandle import com.marklogic.client.io.InputStreamHandle import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody.Companion.toRequestBody const val contentDbName = "DBFUnitTest" const val modulesDbName = "DBFUnitTestModules" const val serverName = "DBFUnitTest" val host = System.getenv("TEST_HOST") ?: "localhost" val serverPort = System.getenv("TEST_PORT")?.toInt() ?: 8016 fun main(args: Array<String>) { val mapper = jacksonObjectMapper() val serializer = mapper.writerWithDefaultPrettyPrinter() /* TODO: skip setup operations where result is present teardown where result is absent amp the test inspector to add header create roles and users parameterize the port, user name, etc */ when(val operation = if (args.isNotEmpty()) args[0] else "setup") { "setup" -> dbfTestSetup(serializer) "teardown" -> dbfTestTeardown(serializer) else -> throw java.lang.IllegalArgumentException("unknown operation: $operation") } } fun dbfTestSetup(serializer: ObjectWriter) { setupServer(serializer) setupModules() } fun dbfTestTeardown(serializer: ObjectWriter) { teardownServer(serializer) } fun setupServer(serializer: ObjectWriter) { val dbClient = DatabaseClientFactory.newClient( host, 8002, DatabaseClientFactory.DigestAuthContext("admin", "admin") ) val client = dbClient.clientImplementation as OkHttpClient for (dbName in listOf(contentDbName, modulesDbName)) { createEntity( client, serializer, "databases", "database", dbName, mapOf("database-name" to dbName) ) val forestName = "$dbName-1" createEntity( client, serializer, "forests", "forest", forestName, mapOf("forest-name" to forestName, "database" to dbName) ) } val userName = "rest-reader" if (!existsEntity(client, "users", "user", userName)) { createEntity( client, serializer, "users", "user", userName, mapOf( "user-name" to userName, "password" to "x", "role" to listOf(userName) ) ) } createEntity( client, serializer, "servers?group-id=Default&server-type=http", "appserver", serverName, mapOf( "server-name" to serverName, "root" to "/", "port" to serverPort, "content-database" to contentDbName, "modules-database" to modulesDbName ) ) dbClient.release() } fun existsEntity(client: OkHttpClient, address: String, name: String, instanceName: String) : Boolean { val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/${address}/${instanceName}""") .get() .build() ).execute() val status = response.code if (status < 400) return true if (status == 404) return false throw RuntimeException("""Could not create $instanceName ${name}: $status""") } fun createEntity(client: OkHttpClient, serializer: ObjectWriter, address: String, name: String, instanceName: String, instancedef: Map<String,Any>) { val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/${address}""") .post( serializer.writeValueAsString(instancedef).toRequestBody("application/json".toMediaTypeOrNull()) ) .build() ).execute() if (response.code >= 400) { throw RuntimeException("""Could not create $instanceName ${name}: ${response.code}""") } } fun setupModules() { val dbClient = DatabaseClientFactory.newClient( host, 8000, "DBFUnitTestModules", DatabaseClientFactory.DigestAuthContext("admin", "admin") ) val docMgr = dbClient.newJSONDocumentManager() val docMeta = DocumentMetadataHandle() val docPerm = docMeta.permissions docPerm.add("rest-reader", DocumentMetadataHandle.Capability.EXECUTE) for (scriptName in listOf("testInspector")) { val scriptPath = """./${scriptName}.sjs""" val scriptUri = """/dbf/test/${scriptName}.sjs""" val inspectorStream = DBFunctionTestUtil.getResourceAsStream(scriptPath) docMgr.write(scriptUri, docMeta, InputStreamHandle(inspectorStream)) } dbClient.release() } fun teardownServer(serializer: ObjectWriter) { val dbClient = DatabaseClientFactory.newClient( host, 8002, DatabaseClientFactory.DigestAuthContext("admin", "admin") ) val client = dbClient.clientImplementation as OkHttpClient val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/servers/$serverName/properties?group-id=Default""") .put(serializer.writeValueAsString( mapOf("content-database" to 0, "modules-database" to 0) ).toRequestBody("application/json".toMediaTypeOrNull()) ) .build() ).execute() if (response.code >= 400) { throw RuntimeException("""Could not detach $serverName appserver: ${response.code}""") } for (dbName in listOf(contentDbName, modulesDbName)) { deleteEntity(client, """databases/${dbName}?forest-delete=data""", "database", dbName) } deleteEntity(client, """servers/$serverName?group-id=Default""", "appserver", serverName) dbClient.release() } fun deleteEntity(client: OkHttpClient, address: String, name: String, instanceName: String) { val response = client.newCall( Request.Builder() .url("""http://${host}:8002/manage/v2/${address}""") .delete() .build() ).execute() if (response.code >= 400) { throw RuntimeException("""Could not delete $instanceName ${name}: ${response.code}""") } }
ml-development-tools/src/test/kotlin/com/marklogic/client/test/dbfunction/fntestconf.kt
3851472339
package failchat.chat class ChatClientCallbacks( val onChatMessage: (ChatMessage) -> Unit, val onStatusUpdate: (StatusUpdate) -> Unit, val onChatMessageDeleted: (ChatMessage) -> Unit )
src/main/kotlin/failchat/chat/ChatClientCallbacks.kt
1887859556
package de.bettinggame.application import de.bettinggame.domain.GameRepository import de.bettinggame.domain.Game import de.bettinggame.domain.Location import de.bettinggame.domain.TournamentLevel import org.springframework.context.i18n.LocaleContextHolder import org.springframework.stereotype.Service import java.time.OffsetDateTime import java.util.* data class LocationTo(val name: String, val city: String, val country: String) { constructor(location: Location, locale: Locale) : this( location.name.getValueForLocale(locale), location.city.getValueForLocale(locale), location.country.getValueForLocale(locale) ) } data class GameTo( val identifier: String, val homeTeam: TeamTo, val guestTeam: TeamTo, val location: LocationTo, val starttime: OffsetDateTime, val goalsHomeTeam: Int?, val goalsGuestTeam: Int? ) { constructor(game: Game, locale: Locale) : this( game.identifier, TeamTo(game.homeTeam), TeamTo(game.guestTeam), LocationTo(game.location, locale), game.starttime, game.goalsHomeTeam, game.goalsGuestTeam ) } @Service class GameService(private val gameRepository: GameRepository) { fun findAllGames(): Map<TournamentLevel, List<GameTo>> { val locale = LocaleContextHolder.getLocale() return gameRepository.findAllByOrderByStarttime() .groupBy({ it.level }, { GameTo(it, locale) }) .toSortedMap() } }
src/main/kotlin/de/bettinggame/application/Games.kt
1290200000
/* * Copyright 2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.configurationcache import org.gradle.api.internal.artifacts.ivyservice.projectmodule.LocalComponentProvider import org.gradle.api.internal.project.ProjectState import org.gradle.internal.component.local.model.LocalComponentMetadata class ConfigurationCacheAwareLocalComponentProvider( private val delegate: LocalComponentProvider, private val cache: BuildTreeConfigurationCache ) : LocalComponentProvider { override fun getComponent(project: ProjectState): LocalComponentMetadata { return cache.loadOrCreateProjectMetadata(project.identityPath) { delegate.getComponent(project) } } }
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/ConfigurationCacheAwareLocalComponentProvider.kt
263352360
package com.acornui.graphic import kotlinx.serialization.* import kotlinx.serialization.builtins.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* import kotlin.math.abs /** * Hue saturation value */ @Serializable(with = HsvSerializer::class) data class Hsv( val h: Double = 0.0, val s: Double = 0.0, val v: Double = 0.0, val a: Double = 1.0 ) { fun toRgb(): Color { val r: Double val g: Double val b: Double val c = v * s val x = c * (1.0 - abs((h / 60.0) % 2.0 - 1.0)) val m = v - c when { h < 60.0 -> { r = c + m g = x + m b = 0.0 + m } h < 120.0 -> { r = x + m g = c + m b = 0.0 + m } h < 180.0 -> { r = 0.0 + m g = c + m b = x + m } h < 240.0 -> { r = 0.0 + m g = x + m b = c + m } h < 300.0 -> { r = x + m g = 0.0 + m b = c + m } else -> { r = c + m g = 0.0 + m b = x + m } } return Color(r, g, b, a) } } @Serializer(forClass = Hsv::class) object HsvSerializer : KSerializer<Hsv> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Hsv", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, value: Hsv) { encoder.encodeSerializableValue(ListSerializer(Double.serializer()), listOf(value.h, value.s, value.v, value.a)) } override fun deserialize(decoder: Decoder): Hsv { val values = decoder.decodeSerializableValue(ListSerializer(Double.serializer())) return Hsv(values[0], values[1], values[2], values[3]) } }
acornui-core/src/main/kotlin/com/acornui/graphic/Hsv.kt
77822267
package org.wordpress.android.push enum class NotificationType { COMMENT, LIKE, COMMENT_LIKE, AUTOMATTCHER, FOLLOW, REBLOG, BADGE_RESET, NOTE_DELETE, TEST_NOTE, ZENDESK, UNKNOWN_NOTE, AUTHENTICATION, GROUP_NOTIFICATION, ACTIONS_RESULT, ACTIONS_PROGRESS, PENDING_DRAFTS, QUICK_START_REMINDER, POST_UPLOAD_SUCCESS, POST_UPLOAD_ERROR, MEDIA_UPLOAD_SUCCESS, MEDIA_UPLOAD_ERROR, POST_PUBLISHED, STORY_SAVE_SUCCESS, STORY_SAVE_ERROR, STORY_FRAME_SAVE_SUCCESS, STORY_FRAME_SAVE_ERROR, BLOGGING_REMINDERS, CREATE_SITE, WEEKLY_ROUNDUP, BLOGGING_PROMPTS_ONBOARDING, }
WordPress/src/main/java/org/wordpress/android/push/NotificationType.kt
1869891281
package org.wordpress.android.ui.mysite.cards.quickstart import android.animation.ObjectAnimator import android.content.res.ColorStateList import android.graphics.Paint import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.appcompat.widget.PopupMenu import androidx.core.content.ContextCompat import androidx.core.view.isVisible import com.google.android.material.textview.MaterialTextView import org.wordpress.android.R import org.wordpress.android.databinding.MySiteCardToolbarBinding import org.wordpress.android.databinding.NewQuickStartTaskTypeItemBinding import org.wordpress.android.databinding.QuickStartCardBinding import org.wordpress.android.databinding.QuickStartTaskTypeItemBinding import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.CUSTOMIZE import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.GET_TO_KNOW_APP import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.GROW import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickStartCard import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickStartCard.QuickStartTaskTypeItem import org.wordpress.android.ui.mysite.MySiteCardAndItemViewHolder import org.wordpress.android.ui.utils.ListItemInteraction import org.wordpress.android.ui.utils.UiHelpers import org.wordpress.android.util.extensions.setVisible import org.wordpress.android.util.extensions.viewBinding const val PERCENT_HUNDRED = 100 class QuickStartCardViewHolder( parent: ViewGroup, private val uiHelpers: UiHelpers ) : MySiteCardAndItemViewHolder<QuickStartCardBinding>(parent.viewBinding(QuickStartCardBinding::inflate)) { fun bind(card: QuickStartCard) = with(binding) { mySiteCardToolbar.update(card) quickStartCustomize.update(CUSTOMIZE, card.taskTypeItems) quickStartGrow.update(GROW, card.taskTypeItems) quickStartGetToKnowApp.update(GET_TO_KNOW_APP, card.taskTypeItems, card.onRemoveMenuItemClick) } private fun MySiteCardToolbarBinding.update(card: QuickStartCard) { if (!card.toolbarVisible) { mySiteCardToolbar.visibility = View.GONE return } mySiteCardToolbarTitle.text = uiHelpers.getTextOfUiString(itemView.context, card.title) mySiteCardToolbarMore.isVisible = card.moreMenuVisible mySiteCardToolbarMore.setOnClickListener { showQuickStartCardMenu( card.onRemoveMenuItemClick, mySiteCardToolbarMore ) } } private fun showQuickStartCardMenu(onRemoveMenuItemClick: ListItemInteraction, anchor: View) { val quickStartPopupMenu = PopupMenu(itemView.context, anchor) quickStartPopupMenu.setOnMenuItemClickListener { onRemoveMenuItemClick.click() return@setOnMenuItemClickListener true } quickStartPopupMenu.inflate(R.menu.quick_start_card_menu) quickStartPopupMenu.show() } private fun QuickStartTaskTypeItemBinding.update( taskType: QuickStartTaskType, taskTypeItems: List<QuickStartTaskTypeItem> ) { val hasItemOfTaskType = taskTypeItems.any { it.quickStartTaskType == taskType } itemRoot.setVisible(hasItemOfTaskType) if (!hasItemOfTaskType) return val item = taskTypeItems.first { it.quickStartTaskType == taskType } with(itemTitle) { text = uiHelpers.getTextOfUiString(itemView.context, item.title) isEnabled = item.titleEnabled paintFlags(item) } itemSubtitle.text = uiHelpers.getTextOfUiString(itemView.context, item.subtitle) itemProgress.update(item) itemRoot.setOnClickListener { item.onClick.click() } } private fun NewQuickStartTaskTypeItemBinding.update( taskType: QuickStartTaskType, taskTypeItems: List<QuickStartTaskTypeItem>, onRemoveMenuItemClick: ListItemInteraction ) { val hasItemOfTaskType = taskTypeItems.any { it.quickStartTaskType == taskType } quickStartItemRoot.setVisible(hasItemOfTaskType) if (!hasItemOfTaskType) return val item = taskTypeItems.first { it.quickStartTaskType == taskType } with(quickStartItemTitle) { text = uiHelpers.getTextOfUiString(itemView.context, item.title) isEnabled = item.titleEnabled } quickStartItemSubtitle.text = uiHelpers.getTextOfUiString(itemView.context, item.subtitle) quickStartItemProgress.update(item) showCompletedIconIfNeeded(item.progress) quickStartItemRoot.setOnClickListener { item.onClick.click() } quickStartItemMoreIcon.setOnClickListener { showQuickStartCardMenu( onRemoveMenuItemClick, quickStartItemMoreIcon ) } } private fun NewQuickStartTaskTypeItemBinding.showCompletedIconIfNeeded(progress: Int) { quickStartTaskCompletedIcon.setVisible(progress == PERCENT_HUNDRED) } private fun MaterialTextView.paintFlags(item: QuickStartTaskTypeItem) { paintFlags = if (item.strikeThroughTitle) { paintFlags or Paint.STRIKE_THRU_TEXT_FLAG } else { paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv() } } private fun ProgressBar.update(item: QuickStartTaskTypeItem) { ObjectAnimator.ofInt(this, PROGRESS, item.progress).setDuration(PROGRESS_ANIMATION_DURATION).start() val progressIndicatorColor = ContextCompat.getColor(itemView.context, item.progressColor) progressTintList = ColorStateList.valueOf(progressIndicatorColor) } companion object { private const val PROGRESS = "progress" private const val PROGRESS_ANIMATION_DURATION = 600L } }
WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/quickstart/QuickStartCardViewHolder.kt
4093538298
package org.wordpress.android.ui.posts.editor.media import dagger.Reusable import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.ui.posts.editor.EditorTracker import javax.inject.Inject enum class AddExistingMediaSource { WP_MEDIA_LIBRARY, STOCK_PHOTO_LIBRARY } /** * Loads existing media items (they must have a valid url) from the local db and adds them to the editor. */ @Reusable class AddExistingMediaToPostUseCase @Inject constructor( private val editorTracker: EditorTracker, private val getMediaModelUseCase: GetMediaModelUseCase, private val appendMediaToEditorUseCase: AppendMediaToEditorUseCase ) { suspend fun addMediaExistingInRemoteToEditorAsync( site: SiteModel, source: AddExistingMediaSource, mediaIdList: List<Long>, editorMediaListener: EditorMediaListener ) { getMediaModelUseCase .loadMediaByRemoteId(site, mediaIdList) .onEach { media -> editorTracker.trackAddMediaEvent(site, source, media.isVideo) } .let { appendMediaToEditorUseCase.addMediaToEditor(editorMediaListener, it) editorMediaListener.syncPostObjectWithUiAndSaveIt() } } }
WordPress/src/main/java/org/wordpress/android/ui/posts/editor/media/AddExistingMediaToPostUseCase.kt
1447332853
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.impl import com.intellij.openapi.project.Project import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.content.Content import com.intellij.ui.content.ContentManager import com.intellij.ui.content.TabDescriptor import com.intellij.ui.content.TabGroupId import com.intellij.util.Consumer import com.intellij.util.ContentUtilEx import com.intellij.util.concurrency.annotations.RequiresBackgroundThread import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.log.VcsLogBundle import com.intellij.vcs.log.VcsLogUi import com.intellij.vcs.log.impl.VcsLogManager.VcsLogUiFactory import com.intellij.vcs.log.ui.MainVcsLogUi import com.intellij.vcs.log.ui.VcsLogPanel import com.intellij.vcs.log.ui.VcsLogUiEx import org.jetbrains.annotations.ApiStatus import java.util.function.Function import java.util.function.Supplier import javax.swing.JComponent /** * Utility methods to operate VCS Log tabs as [Content]s of the [ContentManager] of the VCS toolwindow. */ object VcsLogContentUtil { private fun getLogUi(c: JComponent): VcsLogUiEx? { val uis = VcsLogPanel.getLogUis(c) require(uis.size <= 1) { "Component $c has more than one log ui: $uis" } return uis.singleOrNull() } internal fun selectLogUi(project: Project, logUi: VcsLogUi, requestFocus: Boolean = true): Boolean { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return false val manager = toolWindow.contentManager val component = ContentUtilEx.findContentComponent(manager) { c -> getLogUi(c)?.id == logUi.id } ?: return false if (!toolWindow.isVisible) { toolWindow.activate(null) } return ContentUtilEx.selectContent(manager, component, requestFocus) } fun getId(content: Content): String? { return getLogUi(content.component)?.id } @JvmStatic fun <U : VcsLogUiEx> openLogTab(project: Project, logManager: VcsLogManager, tabGroupId: TabGroupId, tabDisplayName: Function<U, @NlsContexts.TabTitle String>, factory: VcsLogUiFactory<out U>, focus: Boolean): U { val logUi = logManager.createLogUi(factory, VcsLogTabLocation.TOOL_WINDOW) val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: throw IllegalStateException("Could not find tool window for id ${ChangesViewContentManager.TOOLWINDOW_ID}") ContentUtilEx.addTabbedContent(toolWindow.contentManager, tabGroupId, TabDescriptor(VcsLogPanel(logManager, logUi), Supplier { tabDisplayName.apply(logUi) }, logUi), focus) if (focus) { toolWindow.activate(null) } return logUi } fun closeLogTab(manager: ContentManager, tabId: String): Boolean { return ContentUtilEx.closeContentTab(manager) { c: JComponent -> getLogUi(c)?.id == tabId } } @JvmStatic fun runInMainLog(project: Project, consumer: Consumer<in MainVcsLogUi>) { val window = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) if (window == null || !selectMainLog(window.contentManager)) { showLogIsNotAvailableMessage(project) return } val runConsumer = Runnable { VcsLogContentProvider.getInstance(project)!!.executeOnMainUiCreated(consumer) } if (!window.isVisible) { window.activate(runConsumer) } else { runConsumer.run() } } @RequiresEdt fun showLogIsNotAvailableMessage(project: Project) { VcsBalloonProblemNotifier.showOverChangesView(project, VcsLogBundle.message("vcs.log.is.not.available"), MessageType.WARNING) } internal fun findMainLog(cm: ContentManager): Content? { // here tab name is used instead of log ui id to select the correct tab // it's done this way since main log ui may not be created when this method is called return cm.contents.find { VcsLogContentProvider.TAB_NAME == it.tabName } } private fun selectMainLog(cm: ContentManager): Boolean { val mainContent = findMainLog(cm) ?: return false cm.setSelectedContent(mainContent) return true } fun selectMainLog(project: Project): Boolean { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return false return selectMainLog(toolWindow.contentManager) } @JvmStatic fun updateLogUiName(project: Project, ui: VcsLogUi) { val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return val manager = toolWindow.contentManager val component = ContentUtilEx.findContentComponent(manager) { c: JComponent -> ui === getLogUi(c) } ?: return ContentUtilEx.updateTabbedContentDisplayName(manager, component) } @ApiStatus.ScheduledForRemoval @Deprecated("use VcsProjectLog#runWhenLogIsReady(Project, Consumer) instead.") @JvmStatic @RequiresBackgroundThread fun getOrCreateLog(project: Project): VcsLogManager? { VcsProjectLog.ensureLogCreated(project) return VcsProjectLog.getInstance(project).logManager } }
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentUtil.kt
2434447130
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes import com.intellij.codeInsight.intention.IntentionAction import com.intellij.psi.PsiElement import kotlin.reflect.KClass import kotlin.reflect.full.isSubclassOf abstract class QuickFixesPsiBasedFactory<PSI : PsiElement>( private val classTag: KClass<PSI>, private val suitabilityChecker: PsiElementSuitabilityChecker<PSI>, ) : QuickFixFactory { fun createQuickFix(psiElement: PsiElement): List<IntentionAction> { checkIfPsiElementIsSupported(psiElement) @Suppress("UNCHECKED_CAST") return doCreateQuickFix(psiElement as PSI) } private fun checkIfPsiElementIsSupported(psiElement: PsiElement) { if (!psiElement::class.isSubclassOf(classTag)) { throw InvalidPsiElementTypeException( expectedPsiType = psiElement::class, actualPsiType = classTag, factoryName = this::class.toString() ) } @Suppress("UNCHECKED_CAST") if (!suitabilityChecker.isSupported(psiElement as PSI)) { throw UnsupportedPsiElementException(psiElement, this::class.toString()) } } protected abstract fun doCreateQuickFix(psiElement: PSI): List<IntentionAction> } inline fun <reified PSI : PsiElement> quickFixesPsiBasedFactory( suitabilityChecker: PsiElementSuitabilityChecker<PSI> = PsiElementSuitabilityCheckers.ALWAYS_SUITABLE, crossinline createQuickFix: (PSI) -> List<IntentionAction>, ): QuickFixesPsiBasedFactory<PSI> { return object : QuickFixesPsiBasedFactory<PSI>(PSI::class, suitabilityChecker) { override fun doCreateQuickFix(psiElement: PSI): List<IntentionAction> = createQuickFix(psiElement) } } inline fun <reified PSI : PsiElement, reified PSI2 : PsiElement> QuickFixesPsiBasedFactory<PSI>.coMap( suitabilityChecker: PsiElementSuitabilityChecker<PSI2> = PsiElementSuitabilityCheckers.ALWAYS_SUITABLE, crossinline map: (PSI2) -> PSI? ): QuickFixesPsiBasedFactory<PSI2> { return quickFixesPsiBasedFactory(suitabilityChecker) { psiElement -> val newPsi = map(psiElement) ?: return@quickFixesPsiBasedFactory emptyList() createQuickFix(newPsi) } } class InvalidPsiElementTypeException( expectedPsiType: KClass<out PsiElement>, actualPsiType: KClass<out PsiElement>, factoryName: String, ) : Exception("PsiElement with type $expectedPsiType is expected but $actualPsiType found for $factoryName") class UnsupportedPsiElementException( psiElement: PsiElement, factoryName: String ) : Exception("PsiElement $psiElement is unsopported for $factoryName")
plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/classic/quickfixes/QuickFixesPsiBasedFactory.kt
676750642
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. @file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog") package org.jetbrains.intellij.build.impl import com.intellij.openapi.util.io.FileUtilRt import com.intellij.openapi.util.text.Strings import io.opentelemetry.api.common.AttributeKey import io.opentelemetry.api.common.Attributes import io.opentelemetry.api.trace.Span import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import org.jetbrains.intellij.build.* import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot import org.jetbrains.intellij.build.dependencies.DependenciesProperties import org.jetbrains.jps.model.JpsModel import org.jetbrains.jps.model.JpsProject import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes import org.jetbrains.jps.model.java.JavaResourceRootProperties import org.jetbrains.jps.model.java.JavaSourceRootProperties import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleSourceRoot import org.jetbrains.jps.util.JpsPathUtil import java.nio.file.Files import java.nio.file.Path import java.util.concurrent.ConcurrentLinkedQueue class BuildContextImpl private constructor(private val compilationContext: CompilationContextImpl, override val productProperties: ProductProperties, override val windowsDistributionCustomizer: WindowsDistributionCustomizer?, override val linuxDistributionCustomizer: LinuxDistributionCustomizer?, override val macDistributionCustomizer: MacDistributionCustomizer?, override val proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY, private val distFiles: ConcurrentLinkedQueue<Map.Entry<Path, String>>) : BuildContext { override val fullBuildNumber: String get() = "${applicationInfo.productCode}-$buildNumber" override val systemSelector: String get() = productProperties.getSystemSelector(applicationInfo, buildNumber) override val buildNumber: String = options.buildNumber ?: readSnapshotBuildNumber(paths.communityHomeDir) override val xBootClassPathJarNames: List<String> get() = productProperties.xBootClassPathJarNames override var bootClassPathJarNames = persistentListOf("util.jar", "util_rt.jar") override val applicationInfo: ApplicationInfoProperties = ApplicationInfoPropertiesImpl(project, productProperties, options).patch(this) private var builtinModulesData: BuiltinModulesFileData? = null init { @Suppress("DEPRECATION") if (productProperties.productCode == null) { productProperties.productCode = applicationInfo.productCode } check(!systemSelector.contains(' ')) { "System selector must not contain spaces: $systemSelector" } options.buildStepsToSkip.addAll(productProperties.incompatibleBuildSteps) if (!options.buildStepsToSkip.isEmpty()) { Span.current().addEvent("build steps to be skipped", Attributes.of( AttributeKey.stringArrayKey("stepsToSkip"), options.buildStepsToSkip.toImmutableList() )) } } companion object { @JvmStatic @JvmOverloads fun createContext(communityHome: BuildDependenciesCommunityRoot, projectHome: Path, productProperties: ProductProperties, proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY, options: BuildOptions = BuildOptions()): BuildContextImpl { val projectHomeAsString = FileUtilRt.toSystemIndependentName(projectHome.toString()) val windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeAsString) val linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeAsString) val macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeAsString) val compilationContext = CompilationContextImpl.create( communityHome = communityHome, projectHome = projectHome, buildOutputRootEvaluator = createBuildOutputRootEvaluator(projectHome, productProperties, options), options = options ) return BuildContextImpl(compilationContext = compilationContext, productProperties = productProperties, windowsDistributionCustomizer = windowsDistributionCustomizer, linuxDistributionCustomizer = linuxDistributionCustomizer, macDistributionCustomizer = macDistributionCustomizer, proprietaryBuildTools = proprietaryBuildTools, distFiles = ConcurrentLinkedQueue()) } } override var builtinModule: BuiltinModulesFileData? get() { if (options.buildStepsToSkip.contains(BuildOptions.PROVIDED_MODULES_LIST_STEP)) { return null } return builtinModulesData ?: throw IllegalStateException("builtinModulesData is not set. " + "Make sure `BuildTasksImpl.buildProvidedModuleList` was called before") } set(value) { check(builtinModulesData == null) { "builtinModulesData was already set" } builtinModulesData = value } override fun addDistFile(file: Map.Entry<Path, String>) { messages.debug("$file requested to be added to app resources") distFiles.add(file) } override fun getDistFiles(): Collection<Map.Entry<Path, String>> { return java.util.List.copyOf(distFiles) } override fun findApplicationInfoModule(): JpsModule { return findRequiredModule(productProperties.applicationInfoModule) } override val options: BuildOptions get() = compilationContext.options @Suppress("SSBasedInspection") override val messages: BuildMessages get() = compilationContext.messages override val dependenciesProperties: DependenciesProperties get() = compilationContext.dependenciesProperties override val paths: BuildPaths get() = compilationContext.paths override val bundledRuntime: BundledRuntime get() = compilationContext.bundledRuntime override val project: JpsProject get() = compilationContext.project override val projectModel: JpsModel get() = compilationContext.projectModel override val compilationData: JpsCompilationData get() = compilationContext.compilationData override val stableJavaExecutable: Path get() = compilationContext.stableJavaExecutable override val stableJdkHome: Path get() = compilationContext.stableJdkHome override val projectOutputDirectory: Path get() = compilationContext.projectOutputDirectory override fun findRequiredModule(name: String): JpsModule { return compilationContext.findRequiredModule(name) } override fun findModule(name: String): JpsModule? { return compilationContext.findModule(name) } override fun getOldModuleName(newName: String): String? { return compilationContext.getOldModuleName(newName) } override fun getModuleOutputDir(module: JpsModule): Path { return compilationContext.getModuleOutputDir(module) } override fun getModuleTestsOutputPath(module: JpsModule): String { return compilationContext.getModuleTestsOutputPath(module) } override fun getModuleRuntimeClasspath(module: JpsModule, forTests: Boolean): List<String> { return compilationContext.getModuleRuntimeClasspath(module, forTests) } override fun notifyArtifactBuilt(artifactPath: Path) { compilationContext.notifyArtifactWasBuilt(artifactPath) } override fun notifyArtifactWasBuilt(artifactPath: Path) { compilationContext.notifyArtifactWasBuilt(artifactPath) } override fun findFileInModuleSources(moduleName: String, relativePath: String): Path? { for (info in getSourceRootsWithPrefixes(findRequiredModule(moduleName))) { if (relativePath.startsWith(info.second)) { val result = info.first.resolve(Strings.trimStart(Strings.trimStart(relativePath, info.second), "/")) if (Files.exists(result)) { return result } } } return null } override fun signFiles(files: List<Path>, options: Map<String, String>) { if (proprietaryBuildTools.signTool == null) { Span.current().addEvent("files won't be signed", Attributes.of( AttributeKey.stringArrayKey("files"), files.map(Path::toString), AttributeKey.stringKey("reason"), "sign tool isn't defined") ) } else { proprietaryBuildTools.signTool.signFiles(files, this, options) } } override fun executeStep(stepMessage: String, stepId: String, step: Runnable): Boolean { if (options.buildStepsToSkip.contains(stepId)) { Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("name"), stepMessage)) } else { messages.block(stepMessage, step::run) } return true } override fun shouldBuildDistributions(): Boolean { return options.targetOs.lowercase() != BuildOptions.OS_NONE } override fun shouldBuildDistributionForOS(os: OsFamily, arch: JvmArchitecture): Boolean { return shouldBuildDistributions() && listOf(BuildOptions.OS_ALL, os.osId).contains(options.targetOs.lowercase()) && (options.targetArch == null || options.targetArch == arch) } override fun createCopyForProduct(productProperties: ProductProperties, projectHomeForCustomizers: Path): BuildContext { val projectHomeForCustomizersAsString = FileUtilRt.toSystemIndependentName(projectHomeForCustomizers.toString()) /** * FIXME compiled classes are assumed to be already fetched in the FIXME from [CompilationContextImpl.prepareForBuild], please change them together */ val options = BuildOptions() options.useCompiledClassesFromProjectOutput = true val compilationContextCopy = compilationContext.createCopy( messages = messages, options = options, buildOutputRootEvaluator = createBuildOutputRootEvaluator(paths.projectHome, productProperties, options) ) val copy = BuildContextImpl( compilationContext = compilationContextCopy, productProperties = productProperties, windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeForCustomizersAsString), linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeForCustomizersAsString), macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeForCustomizersAsString), proprietaryBuildTools = proprietaryBuildTools, distFiles = ConcurrentLinkedQueue() ) @Suppress("DEPRECATION") val productCode = productProperties.productCode copy.paths.artifactDir = paths.artifactDir.resolve(productCode!!) copy.paths.artifacts = "${paths.artifacts}/$productCode" copy.compilationContext.prepareForBuild() return copy } override fun includeBreakGenLibraries() = isJavaSupportedInProduct private val isJavaSupportedInProduct: Boolean get() = productProperties.productLayout.bundledPluginModules.contains("intellij.java.plugin") override fun patchInspectScript(path: Path) { //todo[nik] use placeholder in inspect.sh/inspect.bat file instead Files.writeString(path, Files.readString(path).replace(" inspect ", " ${productProperties.inspectCommandName} ")) } override fun getAdditionalJvmArguments(os: OsFamily): List<String> { val jvmArgs: MutableList<String> = ArrayList() val classLoader = productProperties.classLoader if (classLoader != null) { jvmArgs.add("-Djava.system.class.loader=$classLoader") } jvmArgs.add("-Didea.vendor.name=${applicationInfo.shortCompanyName}") jvmArgs.add("-Didea.paths.selector=$systemSelector") if (productProperties.platformPrefix != null) { jvmArgs.add("-Didea.platform.prefix=${productProperties.platformPrefix}") } jvmArgs.addAll(productProperties.additionalIdeJvmArguments) if (productProperties.useSplash) { @Suppress("SpellCheckingInspection") jvmArgs.add("-Dsplash=true") } jvmArgs.addAll(getCommandLineArgumentsForOpenPackages(this, os)) return jvmArgs } } private fun createBuildOutputRootEvaluator(projectHome: Path, productProperties: ProductProperties, buildOptions: BuildOptions): (JpsProject) -> Path { return { project -> val appInfo = ApplicationInfoPropertiesImpl(project = project, productProperties = productProperties, buildOptions = buildOptions) projectHome.resolve("out/${productProperties.getOutputDirectoryName(appInfo)}") } } private fun getSourceRootsWithPrefixes(module: JpsModule): Sequence<Pair<Path, String>> { return module.sourceRoots.asSequence() .filter { root: JpsModuleSourceRoot -> JavaModuleSourceRootTypes.PRODUCTION.contains(root.rootType) } .map { moduleSourceRoot: JpsModuleSourceRoot -> var prefix: String val properties = moduleSourceRoot.properties prefix = if (properties is JavaSourceRootProperties) { properties.packagePrefix.replace(".", "/") } else { (properties as JavaResourceRootProperties).relativeOutputPath } if (!prefix.endsWith("/")) { prefix += "/" } Pair(Path.of(JpsPathUtil.urlToPath(moduleSourceRoot.url)), prefix.trimStart('/')) } } private fun readSnapshotBuildNumber(communityHome: BuildDependenciesCommunityRoot): String { return Files.readString(communityHome.communityRoot.resolve("build.txt")).trim { it <= ' ' } }
platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/BuildContextImpl.kt
171329222
enum Foo<caret>(val s: String) { A("a"), B("b") }
plugins/kotlin/idea/tests/testData/intentions/addMissingClassKeyword/enum.kt
1620188329
package com.sys1yagi.longeststreakandroid.tool import android.util.Log import com.sys1yagi.longeststreakandroid.db.OrmaDatabase import com.sys1yagi.longeststreakandroid.model.Event import java.util.* class LongestStreakCounter { val a = Calendar.getInstance() val b = Calendar.getInstance() fun count(database: OrmaDatabase, now: Long, zoneId: String): Int { var streaksBegin = TimeKeeper.day(now, zoneId) var count = 0 database.selectFromEventLog() .orderByCreatedAtDesc() .toList() .forEach { System.out.println("${it.type}") when (it.type) { Event.Type.PUSH, Event.Type.ISSUES, Event.Type.PULL_REQUEST -> { val day = TimeKeeper.day(it.createdAt, zoneId) if ((streaksBegin == day && count == 0) || isMatchYesterday(streaksBegin, day) ) { count++ streaksBegin = day } else if (streaksBegin != day ) { return count } } } } return count } fun isMatchYesterday(today: Long, day: Long): Boolean { if (today - 1 == day) { return true } var t = today.toInt() a.set(Calendar.YEAR, t / 10000) t = t % 10000 a.set(Calendar.MONTH, t / 100 - 1) t = t % 100 a.set(Calendar.DAY_OF_MONTH, t) var d = day.toInt() b.set(Calendar.YEAR, d / 10000) d = d % 10000 b.set(Calendar.MONTH, d / 100 - 1) d = d % 100 b.set(Calendar.DAY_OF_MONTH, d) a.add(Calendar.DAY_OF_MONTH, -1) return a.equals(b) } }
app/src/main/java/com/sys1yagi/longeststreakandroid/tool/LongestStreakCounter.kt
1542917167
package kilobyte.common.instruction.parametrizedroutines import com.google.common.base.Preconditions.checkArgument import kilobyte.common.extensions.* import kilobyte.common.hardware.RegisterFile import kilobyte.common.instruction.DecompiledInstruction import kilobyte.common.instruction.Format import kilobyte.common.instruction.Instruction import kilobyte.common.instruction.decomposedrepresentation.DecomposedRepresentation import kilobyte.common.instruction.exceptions.IllegalCharactersInMnemonicException import kilobyte.common.instruction.exceptions.MalformedMnemonicException import kilobyte.common.instruction.mnemonic.iname import kilobyte.common.instruction.mnemonic.standardizeMnemonic import kilobyte.common.instruction.mnemonic.throwExceptionIfContainsIllegalCharacters import kilobyte.common.instruction.mnemonic.throwIfIncorrectNumberOfCommas import kilobyte.common.machinecode.* import kilobyte.decompiler.MachineCodeDecoder import java.util.* val fieldNameToIndexMap = mapOf( "rs" to 1, "rt" to 2, "rd" to 3, "shamt" to 4, "funct" to 5, "offset" to 3, "address" to 3, "target" to 1, "hint" to 2 // pseudo field ) fun indexOf(fieldName: String): Int { return fieldNameToIndexMap[fieldName]!! } val fieldNameToMethodCallMap: HashMap<String, (n: MachineCode) -> Int> = hashMapOf( Pair("rs", MachineCode::rs), Pair("rt", MachineCode::rt), Pair("rd", MachineCode::rd), Pair("shamt", MachineCode::shamt), Pair("funct", MachineCode::funct), Pair("offset", MachineCode::offset), Pair("target", MachineCode::target), Pair("address", MachineCode::offset), Pair("hint", MachineCode::hint) ) /** * Hint-variable descriptions * source: http://www.cs.cmu.edu/afs/cs/academic/class/15740-f97/public/doc/mips-isa.pdf * page A-117 * Reference: MIPS-instruction with prefix 'PREF' */ enum class Hint(val value: Int) { LOAD(0), STORE(1), LOAD_STREAMED(3), STORE_STREAMED(5), LOAD_RETAINED(6), STORE_RETAINED(7); companion object { fun from(findValue: Int): Hint = values().first { it.value == findValue } } fun description(value: Int): String { when (value) { LOAD.value -> return "Data is expected to be loaded (not modified). " + "Fetch data as if for a load" STORE.value -> return "Data is expected to be stored or modified. " + "Fetch data as if for a store." LOAD_STREAMED.value -> return "Data is expected to be loaded (not " + "modified) but not reused extensively; " + "it will “stream” through cache. Fetch " + "data as if for a load and place it in " + "the cache so that it will not displace " + "data prefetched as 'retained'." STORE_STREAMED.value -> return "Data is expected to be stored or modified " + "but not reused extensively; it will " + "'stream' through cache. Fetch data as if " + "for a store and place it in the cache so " + "that it will not displace data " + "prefetched as 'retained'." LOAD_RETAINED.value -> return "Data is expected to be loaded (not " + "modified) and reused extensively; it " + "should be “retained” in the cache. Fetch " + "data as if for a load and place it in the " + "cache so that it will not be displaced by " + "data prefetched as “streamed”" STORE_RETAINED.value -> return "Data is expected to be stored or " + "modified and reused extensively; it " + "should be “retained” in the cache. " + "Fetch data as if for a store and place " + "it in the cache so that will not be " + "displaced by data prefetched as “streamed”." else -> return "Not yet defined." } } } /** * This method creates objects implementing the ParametrizedInstructionRoutine * by utilizing the given format to make assertions as to what manner 32-bit * integers are to be interpreted and the given string as a template to * pattern-match supplied mnemonics against. * * This method creates bi-directional parametrized routines for * Instruction instantiation using the format of the instruction and a * "abstract" String representation of the "mnemonic pattern", i.e. * * "iname rd, rs, rt" is the "abstract" "mnemonic pattern" * * This text will first provide one example of how to interpret two * R-format instruction and an I-format instruction to showcase the * similarities between how to represent them despite them having * different "mnemonic patterns" to serve as a background for the * abstraction for creating these patterns from String representations * alone. * * Example 1 (R-format): * ===================== * * The "add" instruction is expressed on the form, * * iname rd, rs, rt (1.1) * * which means that for * * add $t1, $t2, $t3 (1.2) * * we get that rd=$t1, rs=$t2, and rt=$t3. * * Using the String representation of (1.1) we can determine the number of * arguments. The correct number of commas can then be inferred to be the * number of arguments minus one, i.e. (argc - 1) where argc is the * argument count. * * From the Format we know the constituents of the Instruction when * represented in its numerical form, for the R-format especially we * have that it decomposes into the following fields, * * | 6 bits | 5 bits | 5 bits | 5 bits | 5 bits | 6 bits | * |:-------:|:------:|:------:|:------:|:------:|:-------:| * | op | rs | rt | rd | shamt | funct | * * Hence, when parsing (1.2) we assign the arguments into an integer * array with 6 elements (all defaulting to zero) like so, * * arr = [op, $t2, $t3, $t1, 0, funct] * ^ * | * default value * * Note that the actual values for the opcode and funct field are * retrieved elsewhere. Since the shamt parameter is not part of the * "mnemonic pattern" then we know it to be zero. * * Important: * ========== * * Derived from the mnemonic pattern we know what constraints need to be * placed on the respective fields, in this example we have that shamt * has to be 0, to wit we can evaluate the legality of a given numeric * representation of the instruction. It is because of this property we * present the two operations (instantiation from a string and a number) * as a cohesive unit. * * As stated earlier, the "opcode" and "funct" field are accessible as * delegates supplied by another object and with that the entire 32-bit number * can be decompiled. * * Example 2 (R-format): * ===================== * * The "mult" instruction is expressed on the form, * * mult rs, rt, for an example "mult $t1, $t2" * * As in "Example 1" the text alone allows us to infer the expected * argument count, which is two of course, and the appropriate number of * commas. Combined with the fact that the instruction is in the R-format * and the opcode and funct field is retrievable elsewhere we get that * * arr = [op, $t1, $t2, 0, 0, funct] * ^ ^ * | | * default values * * Example 3 (I-format): * ===================== * * All I-format instructions are decomposed into fields of the same * length. * * An I-type instruction is determined uniquely by its opcode field. * * The opcode is the leftmost 6-bits of the instruction when * represented as a 32-bit number. * * From the Format we know the constituents of the Instruction when * represented in its numerical form. Specifically for the I-format we * have that it decomposes into the following fields, * * | 6 bits | 5 bits | 5 bits | 16 bits | * |:-------:|:------:|:------:|:-------:| * | op | rs | rt | offset | * * I-format instructions are traditionally written on the form, * * iname rt, offset * * For an example, * * lw $t0, 24($s2) * * which is represented numerically as * * | op | rs | rt | offset | * |:-------:|:------:|:------:|:-------:| * | 0x23 | 18 | 8 | 24_{10} | * * meaning that rs=$s2, rt=$t0, and the offset=24. */ interface ParametrizedInstructionRoutine { fun invoke(prototype: Instruction, machineCode: MachineCode): DecompiledInstruction fun invoke(prototype: Instruction, mnemonicRepresentation: String): Instruction } fun from(format: Format, pattern: String): ParametrizedInstructionRoutine { /* * We standardize the pattern to ensure consistency not out of necessity. * That way we do not have to worry about fudging up our definitions * by writing say "iname rt,offset" instead of "iname rt, offset". */ val standardizedPattern = standardizeMnemonic(pattern) /* * We create an array of the tokens in the standardized array, in the * above example we get that fields = ["iname", "rt", "offset"] */ val fields = standardizedPattern.tokenize() return object : ParametrizedInstructionRoutine { override fun invoke(prototype: Instruction, mnemonicRepresentation: String): Instruction { val standardizedMnemonic = standardizeMnemonic(mnemonicRepresentation) throwExceptionIfContainsIllegalCharacters(standardizedMnemonic) val expectedNumberOfCommas = standardizedPattern.countCommas() throwIfIncorrectNumberOfCommas(expectedNumberOfCommas, mnemonicRepresentation) val expectedNumberOfArguments = standardizedPattern.replace(",", "").split(" ").size - 1 throwIfIncorrectNumberOfArgs(expectedNumberOfArguments, standardizedMnemonic) if (!isAllowedToContainParentheses(format) && standardizedMnemonic.containsParentheses()) { throw IllegalCharactersInMnemonicException(standardizedMnemonic, "<parentheses>") } checkArgument(prototype.iname == standardizedMnemonic.iname()) /* * For instructions expressed using the mnemonic-pattern "iname rd, rs, rt" * we get that the contents of the tokens array will contain * the _values_ of rd, rs, and rt, (and _not_ the string literals * "rd", "rs, "rt") like so: * * tokens=[rd, rs, rt] * * however, the arguments rd, rs, rt do not appear in the same * order as they have to when represented numerically so we * use the "fields" array which tells us what values we are observing * inside the "tokens" array together with "fieldNameToIndexMap" * to place the values at the correct places. */ val tokens: Array<String> = standardizedMnemonic.tokenize() val opcode = prototype.opcode val n = IntArray(format.noOfFields) n[0] = opcode if (format == Format.R || prototype == Instruction.JALR) { n[5] = prototype.funct!! } if (prototype.opcode == 1) { assert(prototype.rt != null) /* The prototype will have its rt field set whenever * its opcode is equal to 1. This is the case for * branch-instructions such as BLTZL, BGEZ but also * trap instructions! * * For instance, BLTZL: op=1, rt=2 * BGEZ: op=1, rt=1 * TGEI: op=1, rt=8 */ val index = indexOf("rt") n[index] = prototype.rt!! } // TODO: Why? return value is not captured does this happen in-place? formatMnemonic(tokens, n, prototype, fields) if (prototype == Instruction.JAL) { // The jump instruction (jal) specifies an absolute memory address // (in bytes) to jump to, but is coded without its last two bits. n[1] = (MachineCodeDecoder.decode(tokens[1]) shr 2).toInt() } val d = DecomposedRepresentation.fromIntArray(n, *format.lengths).asLong() return prototype(standardizedMnemonic, d) } /** * When in machineCode, we trust. **/ override fun invoke(prototype: Instruction, machineCode: MachineCode): DecompiledInstruction { val mnemonicRepresentation = formatMachineCodeToMnemonic(prototype, machineCode, fields) val inst = prototype(mnemonicRepresentation, machineCode) val errors = errorCheckPrototype(machineCode, format, fields) if (errors.isNotEmpty()) { return DecompiledInstruction.PartiallyValid(inst, errors) } return DecompiledInstruction.Valid(inst) } } } private fun shouldFieldBeZero(fieldName: String, fields: Array<String>): Boolean { return !fields.contains(fieldName) } private fun fieldIsNotZero(fieldName: String, machineCode: MachineCode): Boolean { return fieldNameToMethodCallMap[fieldName]!!.invoke(machineCode) != 0 } private fun errorCheckPrototype(machineCode: MachineCode, format: Format, fields: Array<String>): ArrayList<String> { val errors = ArrayList<String>() when (format) { Format.R -> { // TODO: Can definitely be refactored if (shouldFieldBeZero("shamt", fields) && fieldIsNotZero("shamt", machineCode)) { errors.add("Expected shamt to be zero. Got ${machineCode.shamt()}") } if (shouldFieldBeZero("rd", fields) && fieldIsNotZero("rd", machineCode)) { errors.add("Expected rd to be zero. Got ${machineCode.rd()}") } if (shouldFieldBeZero("rt", fields) && fieldIsNotZero("rt", machineCode)) { errors.add("Expected rt to be zero. Got ${machineCode.rt()}") } if (shouldFieldBeZero("rs", fields) && fieldIsNotZero("rs", machineCode)) { errors.add("Expected rs to be zero. Got ${machineCode.rs()}") } } Format.I -> { } Format.J -> { } else -> { throw IllegalStateException("Attempted to instantiate " + "a instruction from an unknown format. Format: $format") } } return errors } private fun formatMachineCodeToMnemonic(prototype: Instruction, machineCode: MachineCode, fields: Array<String>): String { val iname = prototype.iname var mnemonicRepresentation = "$iname " for (i in fields.indices) { // The fields are given in order, so we can just concatenate // the strings. when (fields[i]) { "rd" -> mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rd()) "rt" -> mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rt()) "rs" -> mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rs()) "offset" -> mnemonicRepresentation += machineCode.offset().toString() "target" -> mnemonicRepresentation += machineCode.target().toString() "shamt" -> mnemonicRepresentation += machineCode.shamt().toString() "address" -> { mnemonicRepresentation += machineCode.offset().toString() if (!fields.contains("rs") && iname != "lui") { mnemonicRepresentation += "(" mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rs()) mnemonicRepresentation += ")" } } "hint" -> { mnemonicRepresentation += machineCode.hint().toString() prototype.hint = Hint.from(machineCode.hint()) } } if (i != fields.indices.first && i != fields.indices.last) { mnemonicRepresentation += ", " } } return mnemonicRepresentation.trim() } private fun formatMnemonic(tokens: Array<String>, n: IntArray, prototype: Instruction, fields: Array<String>): Array<String> { for (i in 1..tokens.size - 1) { // from 1 so that we can skip the iname val destinationIndex: Int = indexOf(fields[i]) when (fields[i]) { "target" -> n[destinationIndex] = tokens[i].getOffset() "offset" -> n[destinationIndex] = tokens[i].getOffset() "address" -> { n[destinationIndex] = tokens[i].getOffset() n[indexOf("rs")] = RegisterFile.indexOf(tokens[i].getRegister()) } "hint" -> { val hint = tokens[i].getOffset() n[destinationIndex] = hint prototype.hint = Hint.from(hint) } "shamt" -> { // Handles for instance the "19" in sll $s1, $t1, 19 n[destinationIndex] = tokens[i].toInt() } else -> n[destinationIndex] = RegisterFile.indexOf(tokens[i]) } } return tokens } fun isAllowedToContainParentheses(format: Format): Boolean { return (format == Format.I) } /** * Check if given String contains correct number of arguments. Arguments is * how many parameters an instruction has been given. * Example: * add $t1, $t2, $t3 (3) * jr $t1 (1) * break (0) */ fun throwIfIncorrectNumberOfArgs(expectedArgc: Int, standardizedMnemonic: String) { // -1 for the instruction name val withoutCommas = standardizedMnemonic.removeCommas() val actualArgc = withoutCommas.split(" ").size - 1 if (expectedArgc == actualArgc) { return } val err = "Wrong number of arguments. Expected $expectedArgc arguments. Got: $actualArgc" throw MalformedMnemonicException(standardizedMnemonic, err) } @JvmField val EXIT_PATTERN = from(Format.EXIT, "iname") @JvmField val INAME = from(Format.R, "iname") @JvmField val INAME_RS = from(Format.R, "iname rs") @JvmField val INAME_RD = from(Format.R, "iname rd") @JvmField val INAME_RS_RT = from(Format.R, "iname rs, rt") @JvmField val INAME_RD_RS = from(Format.R, "iname rd, rs") @JvmField val INAME_RD_RS_RT = from(Format.R, "iname rd, rs, rt") @JvmField val INAME_RD_RT_SHAMT = from(Format.R, "iname rd, rt, shamt") /** * The difference between offset and address is that address will accept an * syntax of N($REG) while offset will not. Offset can be referred as * immediate-instruction-type like N whereas N is an number. */ @JvmField val INAME_RT_OFFSET = from(Format.I, "iname rt, offset") @JvmField val INAME_RS_OFFSET = from(Format.I, "iname rs, offset") @JvmField val INAME_RS_RT_OFFSET = from(Format.I, "iname rs, rt, offset") @JvmField val INAME_RT_RS_OFFSET = from(Format.I, "iname rt, rs, offset") @JvmField val INAME_RT_ADDRESS = from(Format.I, "iname rt, address") @JvmField val INAME_HINT_ADDRESS = from(Format.I, "iname hint, address") @JvmField val INAME_TARGET = from(Format.J, "iname target")
src/main/kotlin/kilobyte/common/instruction/parametrizedroutines/ParametrizedInstructionRoutines.kt
1392745938
/* * Komunumo – Open Source Community Manager * Copyright (C) 2017 Java User Group Switzerland * * 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/>. */ package ch.komunumo.server import ch.komunumo.server.business.authorization.boundary.AuthorizationResource import ch.komunumo.server.business.authorization.control.AuthorizationService import ch.komunumo.server.business.event.boundary.EventResource import ch.komunumo.server.business.event.boundary.EventsResource import ch.komunumo.server.business.user.boundary.UserResource import ch.komunumo.server.business.user.boundary.UsersResource import org.jetbrains.ktor.application.ApplicationCallPipeline import org.jetbrains.ktor.application.install import org.jetbrains.ktor.features.CORS import org.jetbrains.ktor.features.CallLogging import org.jetbrains.ktor.features.Compression import org.jetbrains.ktor.features.DefaultHeaders import org.jetbrains.ktor.gson.GsonSupport import org.jetbrains.ktor.host.embeddedServer import org.jetbrains.ktor.http.HttpMethod import org.jetbrains.ktor.netty.Netty import org.jetbrains.ktor.routing.Routing import org.jetbrains.ktor.routing.get import org.jetbrains.ktor.routing.post import org.jetbrains.ktor.routing.put import org.jetbrains.ktor.routing.route fun main(args: Array<String>) { embeddedServer(Netty, 8080) { install(DefaultHeaders) install(Compression) install(CallLogging) install(CORS) { method(HttpMethod.Post) method(HttpMethod.Get) method(HttpMethod.Put) method(HttpMethod.Delete) method(HttpMethod.Head) method(HttpMethod.Options) header("Authorization") header("Location") anyHost() } install(GsonSupport) { setPrettyPrinting() } intercept(ApplicationCallPipeline.Call) { AuthorizationService.intercept(call) } install(Routing) { route("api") { route("authorization") { get { AuthorizationResource.handleGet(call) } post { AuthorizationResource.handlePost(call) } } route("events") { get { EventsResource.handleGet(call) } post { EventsResource.handlePost(call) } route("{id}") { get { EventResource.handleGet(call) } put { EventResource.handlePut(call) } } } route("users") { get { UsersResource.handleGet(call) } post { UsersResource.handlePost(call) } route("{id}") { get { UserResource.handleGet(call) } put { UserResource.handlePut(call) } } } } } }.start(wait = true) }
src/main/kotlin/ch/komunumo/server/Main.kt
2519778564
package org.coner.crispyfish.filetype.ecf import java.io.File class NotEventControlFileException(file: File) : IllegalArgumentException( "File is not an ecf file: $file" )
library/src/main/kotlin/org/coner/crispyfish/filetype/ecf/NotEventControlFileException.kt
924445029
package com.eden.orchid.impl.relations import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.Relation import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.annotations.Option import com.eden.orchid.api.theme.pages.OrchidPage import javax.inject.Inject class PageRelation @Inject constructor( context: OrchidContext ) : Relation<OrchidPage>(context) { @Option @Description("The Id of an item to look up.") lateinit var itemId: String @Option @Description("The type of collection the item is expected to come from.") lateinit var collectionType: String @Option @Description("The specific Id of the given collection type where the item is expected to come from.") lateinit var collectionId: String override fun load(): OrchidPage? { if(listOf(collectionType, collectionId, itemId).any { it.isNotBlank() }) { return context.findPage(this.collectionType, this.collectionId, this.itemId) } else { return null } } }
OrchidCore/src/main/kotlin/com/eden/orchid/impl/relations/PageRelation.kt
2470695229
package org.frice.obj.button import org.frice.event.MOUSE_PRESSED import org.frice.event.OnMouseEvent import org.frice.platform.FriceImage import org.frice.platform.owner.ImageOwner import org.frice.resource.image.ImageResource import org.frice.util.shape.FShapeQuad import java.util.function.Consumer /** * Created by ice1000 on 2016/9/3 0003. * * @author ice1000 * @since v0.5 */ class ImageButton @JvmOverloads constructor( var imageNormal: ImageResource, var imagePressed: ImageResource = imageNormal, override var x: Double, override var y: Double) : ImageOwner, FButton { override fun buttonStateChange(e: OnMouseEvent) { bool = e.type == MOUSE_PRESSED } private var bool = false override var width: Double = super.width override var height: Double = super.height override var rotate = 0.0 override var isVisible = true override var died = false override var onMouseListener: Consumer<OnMouseEvent>? = null var collisionBox: FShapeQuad? = null override val box: FShapeQuad get() = collisionBox ?: this override val image: FriceImage get () = if (bool) imagePressed.image else imageNormal.image }
src/org/frice/obj/button/ImageButton.kt
316856401
package com.meiji.daily.data.local.dao /** * Created by Meiji on 2017/11/28. */ import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import com.meiji.daily.bean.ZhuanlanBean import io.reactivex.Maybe @Dao interface ZhuanlanDao { @Insert(onConflict = OnConflictStrategy.IGNORE) fun insert(zhuanlanBean: ZhuanlanBean): Long @Insert(onConflict = OnConflictStrategy.IGNORE) fun insert(list: MutableList<ZhuanlanBean>) @Query("SELECT * FROM zhuanlans WHERE type = :type") fun query(type: Int): Maybe<MutableList<ZhuanlanBean>> @Query("DELETE FROM zhuanlans WHERE slug = :slug") fun delete(slug: String) }
app/src/main/java/com/meiji/daily/data/local/dao/ZhuanlanDao.kt
4148863879
package net.tlalka.imager.core import net.tlalka.imager.data.GeoImage import net.tlalka.imager.utils.GeoUtils class GeoCalculator { fun calculate(i1: GeoImage, i2: GeoImage) { val distance = GeoUtils.distanceInM(i1.latitude, i1.longitude, i2.latitude, i2.longitude) val direction = GeoUtils.bearingInDeg(i1.latitude, i1.longitude, i2.latitude, i2.longitude) i2.setImageVector(distance, direction, CardinalType[direction].name) } private enum class CardinalType constructor(private val degrees: Int) { N(0), NE(45), E(90), SE(135), S(180), SW(225), W(270), NW(315), X(-1); companion object { private val STEP = 22.5 operator fun get(degrees: Double): CardinalType { val value = if (degrees > NW.degrees + STEP) 0.0 else degrees return values().firstOrNull { Math.abs(value - it.degrees) < STEP } ?: CardinalType.X } } } }
src/main/kotlin/net/tlalka/imager/core/GeoCalculator.kt
3856458835
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide.intentions import com.intellij.codeInsight.intention.IntentionAction import com.intellij.codeInsight.intention.IntentionActionDelegate import com.intellij.codeInsight.intention.impl.preview.IntentionPreviewPopupUpdateProcessor import com.intellij.codeInsight.intention.preview.IntentionPreviewInfo import com.intellij.openapi.util.TextRange import com.intellij.util.ui.UIUtil import org.intellij.lang.annotations.Language import org.toml.TomlTestBase import kotlin.reflect.KClass abstract class TomlIntentionTestBase(private val intentionClass: KClass<out IntentionAction>): TomlTestBase() { protected open val previewExpected: Boolean get() = findIntention()?.startInWriteAction() == true private fun findIntention(): IntentionAction? = myFixture.availableIntentions.firstOrNull { val originalIntention = IntentionActionDelegate.unwrap(it) intentionClass == originalIntention::class } protected fun doAvailableTest( @Language("TOML") before: String, @Language("TOML") after: String, filename: String = "example.toml" ) { InlineFile(before.trimIndent(), filename) launchAction() myFixture.checkResult(after.trimIndent()) } protected fun doUnavailableTest( @Language("TOML") before: String, filename: String = "example.toml" ) { InlineFile(before.trimIndent(), filename) val intention = findIntention() check(intention == null) { "\"${intentionClass.simpleName}\" should not be available" } } private fun launchAction() { UIUtil.dispatchAllInvocationEvents() val intention = findIntention() ?: error("Failed to find ${intentionClass.simpleName} intention") val tomlIntention = intention is TomlElementBaseIntentionAction<*> if (tomlIntention) { if (previewExpected) { myFixture.checkPreviewAndLaunchAction(intention) } else { val previewInfo = IntentionPreviewPopupUpdateProcessor.getPreviewInfo(project, intention, myFixture.file, myFixture.editor) assertEquals(IntentionPreviewInfo.EMPTY, previewInfo) myFixture.launchAction(intention) } } else { myFixture.launchAction(intention) } } protected fun checkAvailableInSelectionOnly(@Language("TOML") code: String, filename: String = "example.toml") { InlineFile(code.replace("<selection>", "<selection><caret>"), filename) val selections = myFixture.editor.selectionModel.let { model -> model.blockSelectionStarts.zip(model.blockSelectionEnds) .map { TextRange(it.first, it.second + 1) } } val intention = findIntention() ?: error("Failed to find ${intentionClass.simpleName} intention") for (pos in myFixture.file.text.indices) { myFixture.editor.caretModel.moveToOffset(pos) val expectAvailable = selections.any { it.contains(pos) } val isAvailable = intention.isAvailable(project, myFixture.editor, myFixture.file) check(isAvailable == expectAvailable) { "Expect ${if (expectAvailable) "available" else "unavailable"}, " + "actually ${if (isAvailable) "available" else "unavailable"} " + "at `${StringBuilder(myFixture.file.text).insert(pos, "<caret>")}`" } } } }
plugins/toml/core/src/test/kotlin/org/toml/ide/intentions/TomlIntentionTestBase.kt
2073415409
// FIR_COMPARISON val v: Boolean = run { return<caret> true } // ELEMENT: "return@run"
plugins/kotlin/completion/testData/handlers/basic/AddLabelToReturn.kt
2255461677
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.base.projectStructure import com.intellij.openapi.project.Project import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.analyzer.LanguageSettingsProvider import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.config.LanguageVersionSettings import org.jetbrains.kotlin.idea.base.facet.platform.platform import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LanguageSettingsOwner import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.LibraryInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo import org.jetbrains.kotlin.platform.TargetPlatformVersion import org.jetbrains.kotlin.platform.jvm.JdkPlatform import org.jetbrains.kotlin.platform.subplatformsOfType @ApiStatus.Internal object IDELanguageSettingsProvider : LanguageSettingsProvider { override fun getLanguageVersionSettings(moduleInfo: ModuleInfo, project: Project): LanguageVersionSettings { return when (moduleInfo) { is ModuleSourceInfo -> moduleInfo.module.languageVersionSettings is LanguageSettingsOwner -> moduleInfo.languageVersionSettings is LibraryInfo -> LanguageVersionSettingsProvider.getInstance(project).librarySettings is PlatformModuleInfo -> moduleInfo.platformModule.module.languageVersionSettings else -> project.languageVersionSettings } } override fun getTargetPlatform(moduleInfo: ModuleInfo, project: Project): TargetPlatformVersion { return when (moduleInfo) { is ModuleSourceInfo -> { val jdkPlatform = moduleInfo.module.platform.subplatformsOfType<JdkPlatform>().firstOrNull() jdkPlatform?.targetVersion ?: TargetPlatformVersion.NoVersion } is LanguageSettingsOwner -> moduleInfo.targetPlatformVersion else -> TargetPlatformVersion.NoVersion } } }
plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/IDELanguageSettingsProvider.kt
1255355904