content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
package me.sdidev.simpleroutetracker.base import android.annotation.SuppressLint import android.app.Service import android.content.Intent import android.location.Location import android.os.Binder import android.os.Bundle import android.os.IBinder import com.google.android.gms.common.api.GoogleApiClient import com.google.android.gms.common.api.PendingResult import com.google.android.gms.common.api.Status import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import me.sdidev.simpleroutetracker.App import me.sdidev.simpleroutetracker.BuildConfig import me.sdidev.simpleroutetracker.LocationUpdateManager import me.sdidev.simpleroutetracker.util.positionFromLocation import org.slf4j.LoggerFactory import javax.inject.Inject class GeoPositionTrackerService : Service() { private val logger = LoggerFactory.getLogger(GeoPositionTrackerService::class.java) private val binder: LocalBinder = LocalBinder() private var googleApiClient: GoogleApiClient? = null private var pendingResult: PendingResult<Status>? = null @Inject lateinit var locationUpdateManager: LocationUpdateManager override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { return START_STICKY_COMPATIBILITY } override fun onCreate() { super.onCreate() App.applicationComponent.resolve(this) googleApiClient = GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(object : GoogleApiClient.ConnectionCallbacks { override fun onConnected(p0: Bundle?) { logger.info("connected to google api") startGoogleApiLocationListening() } override fun onConnectionSuspended(p0: Int) { logger.info("connection suspended") } }) .addOnConnectionFailedListener { error -> logger.warn("google api connection failure: $error") } .build() googleApiClient?.connect() } override fun onDestroy() { googleApiClient?.disconnect() pendingResult?.cancel() super.onDestroy() } override fun onBind(intent: Intent?): IBinder { return binder } @SuppressLint("MissingPermission") private fun startGoogleApiLocationListening() { val lastLocation: Location? = LocationServices.FusedLocationApi.getLastLocation(googleApiClient) if (lastLocation != null) { locationUpdateManager.update(positionFromLocation(lastLocation)) } val locationRequest = LocationRequest() locationRequest.interval = BuildConfig.UPDATE_INTERVAL locationRequest.smallestDisplacement = BuildConfig.MINIMAL_UPDATE_DISTANCE pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates( googleApiClient, locationRequest ) { location -> logger.info("user position: (${location.latitude}, ${location.longitude})") locationUpdateManager.update(positionFromLocation(location)) } } private class LocalBinder : Binder() }
app/src/main/java/me/sdidev/simpleroutetracker/base/GeoPositionTrackerService.kt
1858800717
package com.orgzly.android.ui.views.richtext import android.content.Context import android.content.res.TypedArray import android.graphics.Typeface import android.text.InputType import android.text.SpannableStringBuilder import android.text.Spanned import android.text.TextUtils import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.View import android.widget.FrameLayout import android.widget.TextView import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.prefs.AppPreferences import com.orgzly.android.ui.ImageLoader import com.orgzly.android.ui.main.MainActivity import com.orgzly.android.ui.util.styledAttributes import com.orgzly.android.ui.views.style.CheckboxSpan import com.orgzly.android.ui.views.style.DrawerMarkerSpan import com.orgzly.android.ui.views.style.DrawerSpan import com.orgzly.android.util.LogUtils import com.orgzly.android.util.OrgFormatter class RichText(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs), ActionableRichTextView { fun interface OnUserTextChangeListener { fun onUserTextChange(str: String) } data class Listeners( var onUserTextChange: OnUserTextChangeListener? = null) private val listeners = Listeners() fun setOnUserTextChangeListener(listener: OnUserTextChangeListener) { listeners.onUserTextChange = listener } private val sourceBackgroundColor: Int by lazy { context.styledAttributes(intArrayOf(R.attr.colorSecondaryContainer)) { typedArray -> typedArray.getColor(0, 0) } } data class Attributes( val viewId: Int = 0, val editId: Int = 0, val parseCheckboxes: Boolean = true, val linkify: Boolean = true, val editable: Boolean = true, val inputType: Int = InputType.TYPE_NULL, val imeOptions: Int = 0, val hint: String? = null, val textSize: Int = 0, val paddingHorizontal: Int = 0, val paddingVertical: Int = 0 ) private lateinit var attributes: Attributes private val richTextEdit: RichTextEdit private val richTextView: RichTextView init { parseAttrs(attrs) inflate(getContext(), R.layout.rich_text, this) richTextEdit = findViewById(R.id.rich_text_edit) richTextView = findViewById(R.id.rich_text_view) // TODO: if editable richTextEdit.apply { if (attributes.editId != 0) { id = attributes.editId } setCommonAttributes(this) inputType = attributes.inputType imeOptions = attributes.imeOptions // Wrap lines when editing. Doesn't work when set in XML? setHorizontallyScrolling(false) maxLines = Integer.MAX_VALUE if (AppPreferences.highlightEditedRichText(context)) { setBackgroundColor(sourceBackgroundColor) } else { setBackgroundColor(0) } // If RichTextEdit loses the focus, switch to view mode setOnFocusChangeListener { _, hasFocus -> if (!hasFocus) { toViewMode(true) } } } richTextView.apply { if (attributes.viewId != 0) { id = attributes.viewId } setCommonAttributes(this) if (attributes.editable) { setTextIsSelectable(true) } setOnTapUpListener { _, _, charOffset -> if (attributes.editable) { toEditMode(charOffset) } } setOnActionListener(this@RichText) } } private fun parseAttrs(attrs: AttributeSet?) { if (attrs != null) { context.styledAttributes(attrs, R.styleable.RichText) { typedArray -> readAttributes(typedArray) } } } private fun readAttributes(typedArray: TypedArray) { typedArray.run { attributes = Attributes( getResourceId(R.styleable.RichText_view_id, 0), getResourceId(R.styleable.RichText_edit_id, 0), getBoolean(R.styleable.RichText_parse_checkboxes, true), getBoolean(R.styleable.RichText_linkify, true), getBoolean(R.styleable.RichText_editable, true), getInteger(R.styleable.RichText_android_inputType, InputType.TYPE_NULL), getInteger(R.styleable.RichText_android_imeOptions, 0), getString(R.styleable.RichText_android_hint), getDimensionPixelSize(R.styleable.RichText_android_textSize, 0), getDimensionPixelSize(R.styleable.RichText_paddingHorizontal, 0), getDimensionPixelSize(R.styleable.RichText_paddingVertical, 0), ) } } private fun setCommonAttributes(view: TextView) { view.hint = attributes.hint if (attributes.textSize > 0) { view.setTextSize(TypedValue.COMPLEX_UNIT_PX, attributes.textSize.toFloat()) } if (attributes.paddingHorizontal > 0 || attributes.paddingVertical > 0) { view.setPadding( attributes.paddingHorizontal, attributes.paddingVertical, attributes.paddingHorizontal, attributes.paddingVertical) } } fun setSourceText(text: CharSequence?) { richTextEdit.setText(text) if (richTextView.visibility == View.VISIBLE) { parseAndSetViewText() } } fun getSourceText(): CharSequence? { return richTextEdit.text } fun setVisibleText(text: CharSequence) { richTextView.text = text } fun toEditMode(charOffset: Int) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "editable:${attributes.editable}", charOffset) richTextEdit.activate(charOffset) richTextView.deactivate() } private fun toViewMode(reparseSource: Boolean = false) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "reparseSource:$reparseSource") if (reparseSource) { parseAndSetViewText() } richTextView.activate() richTextEdit.deactivate() } private fun parseAndSetViewText() { val source = richTextEdit.text if (source != null) { val parsed = OrgFormatter.parse( source, context, attributes.linkify, attributes.parseCheckboxes) richTextView.setText(parsed, TextView.BufferType.SPANNABLE) ImageLoader.loadImages(richTextView) } else { richTextView.text = null } } fun setTypeface(typeface: Typeface) { richTextView.typeface = typeface richTextEdit.typeface = typeface } fun setMaxLines(lines: Int) { if (lines < Integer.MAX_VALUE) { richTextView.maxLines = lines richTextView.ellipsize = TextUtils.TruncateAt.END } else { richTextView.maxLines = Integer.MAX_VALUE richTextView.ellipsize = null } } fun setOnEditorActionListener(any: TextView.OnEditorActionListener) { richTextEdit.setOnEditorActionListener(any) } override fun toggleDrawer(markerSpan: DrawerMarkerSpan) { val textSpanned = richTextView.text as Spanned // Find a drawer at the place of the clicked span val pos = textSpanned.getSpanStart(markerSpan) val drawerSpan = textSpanned.getSpans(pos, pos, DrawerSpan::class.java).firstOrNull() if (drawerSpan == null) { Log.w(TAG, "No DrawerSpan found at the place of $markerSpan ($pos)") return } val drawerStart = textSpanned.getSpanStart(drawerSpan) val drawerEnd = textSpanned.getSpanEnd(drawerSpan) val builder = SpannableStringBuilder(textSpanned) val replacement = OrgFormatter.drawerSpanned( drawerSpan.name, drawerSpan.content, isFolded = !drawerSpan.isFolded) builder.removeSpan(drawerSpan) builder.removeSpan(markerSpan) builder.replace(drawerStart, drawerEnd, replacement) richTextView.text = builder } override fun toggleCheckbox(checkboxSpan: CheckboxSpan) { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, checkboxSpan) val content = if (checkboxSpan.isChecked()) "[ ]" else "[X]" val replacement = OrgFormatter.checkboxSpanned( content, checkboxSpan.rawStart, checkboxSpan.rawEnd) val newSource = richTextEdit.text ?.replaceRange(checkboxSpan.rawStart, checkboxSpan.rawEnd, replacement) ?.toString() .orEmpty() listeners.onUserTextChange?.onUserTextChange(newSource) } // TODO: Consider getting MainActivity's *ViewModel* here instead override fun followLinkToNoteWithProperty(name: String, value: String) { MainActivity.followLinkToNoteWithProperty(name, value) } override fun followLinkToFile(path: String) { MainActivity.followLinkToFile(path) } companion object { val TAG: String = RichText::class.java.name } }
app/src/main/java/com/orgzly/android/ui/views/richtext/RichText.kt
2337763849
package motocitizen.ui.menus import android.content.Context import motocitizen.content.message.Message import motocitizen.main.R import motocitizen.utils.copyToClipBoard import motocitizen.utils.getPhonesFromText import motocitizen.utils.makeDial import motocitizen.utils.name import org.jetbrains.anko.sendSMS import org.jetbrains.anko.share class MessageContextMenu(context: Context, val message: Message) : ContextMenu(context) { init { addButton(R.string.share) { context.share(message.text) } addButton(R.string.copy) { context.copyToClipBoard(message.owner.name() + ":" + message.text) } message.text.getPhonesFromText().forEach { addButton(context.getString(R.string.popup_dial, it)) { context.makeDial(it) } } message.text.getPhonesFromText().forEach { addButton(context.getString(R.string.popup_sms, it)) { context.sendSMS(it) } } } }
Motocitizen/src/motocitizen/ui/menus/MessageContextMenu.kt
1587339345
package com.foo.graphql.base import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication /** * Created by arcuri82 on 18-Jul-17. */ @SpringBootApplication open class GQLBaseApplication{ companion object{ const val SCHEMA_NAME = "base.graphqls" } } /* API accessible at http://localhost:8080/graphql UI accessible at http://localhost:8080/graphiql (note the "i" between graph and ql...) UI graph representation at http://localhost:8080/voyager */ fun main(args: Array<String>) { SpringApplication.run(GQLBaseApplication::class.java, "--graphql.tools.schema-location-pattern=**/${GQLBaseApplication.SCHEMA_NAME}") }
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/base/GQLBaseApplication.kt
1452346962
package com.foo.graphql.nullableInput.resolver import com.foo.graphql.nullableInput.DataRepository import com.foo.graphql.nullableInput.type.Flower import graphql.kickstart.tools.GraphQLQueryResolver import org.springframework.stereotype.Component @Component open class QueryResolver( private val dataRepo: DataRepository ) : GraphQLQueryResolver { fun flowersNullInNullOut(id: Array<Int?>?): Flower?{ return dataRepo.findFlowersNullInNullOut(id) } //flowersNullIn(id: [Int]!): Flower fun flowersNullIn(id: Array<Int?>): Flower? { return dataRepo.findFlowersNullIn(id) } //flowersNullOut(id: [Int!]): Flower fun flowersNullOut(id: Array<Int>?): Flower? { return dataRepo.findFlowersNullOut(id) } // flowersNotNullInOut(id: [Int!]!): Flower fun flowersNotNullInOut(id: Array<Int>): Flower?{ return dataRepo.findFlowersNotNullInOut(id) } //flowersScalarNullable(id: Boolean):Flower fun flowersScalarNullable(id: Boolean?): Flower?{ return dataRepo.findFlowersScalarNullable(id) } //flowersScalarNotNullable(id: Boolean!):Flower fun flowersScalarNotNullable(id: Boolean): Flower?{ return dataRepo.findFlowersScalarNotNullable(id) } }
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/nullableInput/resolver/QueryResolver.kt
161684429
package com.piticlistudio.playednext.test.factory import com.piticlistudio.playednext.data.entity.giantbomb.GiantbombFranchise import com.piticlistudio.playednext.data.entity.room.RoomCollection import com.piticlistudio.playednext.data.entity.igdb.IGDBCollection import com.piticlistudio.playednext.domain.model.Collection import com.piticlistudio.playednext.test.factory.DataFactory.Factory.randomInt import com.piticlistudio.playednext.test.factory.DataFactory.Factory.randomString class CollectionFactory { companion object Factory { fun makeRoomCollection(): RoomCollection { return RoomCollection(DataFactory.randomInt(), DataFactory.randomString(), DataFactory.randomString()) } fun makeCollection(id: Int = randomInt(), name: String = randomString(), url: String = randomString()): Collection { return Collection(id, name, url) } fun makeIGDBCollection(): IGDBCollection { return IGDBCollection(randomInt(), randomString(), randomString(), randomString(), DataFactory.randomLong(), DataFactory.randomLong()) } fun makeGiantbombCollection(): GiantbombFranchise = GiantbombFranchise(randomInt(), randomString()) } }
app/src/test/java/com/piticlistudio/playednext/test/factory/CollectionFactory.kt
3301632339
package au.com.outware.neanderthal.util.extensions import androidx.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * @author timmutton */ // Inflates a layout and attaches it to itself fun ViewGroup.inflateLayout(@LayoutRes resource: Int, attachToRoot: Boolean = false): View { return LayoutInflater.from(context).inflate(resource, this, attachToRoot) }
neanderthal/src/main/kotlin/au/com/outware/neanderthal/util/extensions/ViewGroupExtensions.kt
823342381
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.issues import kotlinx.serialization.Serializable import org.junit.Test import org.litote.kmongo.AllCategoriesKMongoBaseTest import org.litote.kmongo.findOne import kotlin.test.assertEquals @Serializable data class FloatContainer(val float: Float, val double: Double) /** * */ class Issue232FloatSerialization : AllCategoriesKMongoBaseTest<FloatContainer>() { @Test fun `test insert and load`() { val e = FloatContainer(2.0F, 2.0) col.insertOne(e) assertEquals(e, col.findOne()) } }
kmongo-core-tests/src/main/kotlin/org/litote/kmongo/issues/Issue232FloatSerialization.kt
1214670241
/* * Transportr * * Copyright (c) 2013 - 2021 Torsten Grote * * 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.grobox.transportr.locations import android.content.Context import android.location.Geocoder import androidx.annotation.WorkerThread import com.mapbox.mapboxsdk.geometry.LatLng import de.grobox.transportr.utils.hasLocation import de.schildbach.pte.dto.Location import de.schildbach.pte.dto.LocationType.ADDRESS import de.schildbach.pte.dto.Point import okhttp3.* import org.json.JSONException import org.json.JSONObject import java.io.IOException import java.util.* import kotlin.concurrent.thread class ReverseGeocoder(private val context: Context, private val callback: ReverseGeocoderCallback) { fun findLocation(location: Location) { if (!location.hasLocation()) return findLocation(location.latAsDouble, location.lonAsDouble) } fun findLocation(location: android.location.Location) { if (location.latitude == 0.0 && location.latitude == 0.0) return findLocation(location.latitude, location.longitude) } private fun findLocation(lat: Double, lon: Double) { if (Geocoder.isPresent()) { findLocationWithGeocoder(lat, lon) } else { findLocationWithOsm(lat, lon) } } private fun findLocationWithGeocoder(lat: Double, lon: Double) { thread(start = true) { try { val geoCoder = Geocoder(context, Locale.getDefault()) val addresses = geoCoder.getFromLocation(lat, lon, 1) if (addresses == null || addresses.size == 0) throw IOException("No results") val address = addresses[0] var name: String? = address.thoroughfare ?: throw IOException("Empty Address") if (address.featureName != null) name += " " + address.featureName val place = address.locality val point = Point.fromDouble(lat, lon) val l = Location(ADDRESS, null, point, place, name) callback.onLocationRetrieved(WrapLocation(l)) } catch (e: IOException) { if (e.message != "Service not Available") { e.printStackTrace() } findLocationWithOsm(lat, lon) } } } private fun findLocationWithOsm(lat: Double, lon: Double) { val client = OkHttpClient() // https://nominatim.openstreetmap.org/reverse?lat=52.5217&lon=13.4324&format=json val url = StringBuilder("https://nominatim.openstreetmap.org/reverse?") url.append("lat=").append(lat).append("&") url.append("lon=").append(lon).append("&") url.append("format=json") val request = Request.Builder() .header("User-Agent", "Transportr (https://transportr.app)") .url(url.toString()) .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { e.printStackTrace() callback.onLocationRetrieved(getWrapLocation(lat, lon)) } @Throws(IOException::class) override fun onResponse(call: Call, response: Response) { val body = response.body() if (!response.isSuccessful || body == null) { callback.onLocationRetrieved(getWrapLocation(lat, lon)) return } val result = body.string() body.close() try { val data = JSONObject(result) val address = data.getJSONObject("address") var name = address.optString("road") if (name.isNotEmpty()) { val number = address.optString("house_number") if (number.isNotEmpty()) name += " $number" } else { name = data.getString("display_name").split(",")[0] } var place = address.optString("city") if (place.isEmpty()) place = address.optString("state") val point = Point.fromDouble(lat, lon) val l = Location(ADDRESS, null, point, place, name) callback.onLocationRetrieved(WrapLocation(l)) } catch (e: JSONException) { callback.onLocationRetrieved(getWrapLocation(lat, lon)) throw IOException(e) } } }) } private fun getWrapLocation(lat: Double, lon: Double): WrapLocation { return WrapLocation(LatLng(lat, lon)) } interface ReverseGeocoderCallback { @WorkerThread fun onLocationRetrieved(location: WrapLocation) } }
app/src/main/java/de/grobox/transportr/locations/ReverseGeocoder.kt
1875637433
package szewek.mcflux.compat.jei.fluxgen import mezz.jei.api.IGuiHelper import mezz.jei.api.IJeiHelpers import net.minecraft.item.ItemStack import net.minecraftforge.fluids.FluidStack import szewek.mcflux.recipes.FluxGenRecipes import szewek.mcflux.recipes.RecipeFluxGen import java.util.* object FluxGenRecipeMaker { fun getFluxGenRecipes(hlp: IJeiHelpers): List<FluxGenRecipeJEI> { val igh = hlp.guiHelper val catalysts = FluxGenRecipes.catalysts val hotFluids = FluxGenRecipes.hotFluids val cleanFluids = FluxGenRecipes.cleanFluids val recipes = ArrayList<FluxGenRecipeJEI>(catalysts.size + hotFluids.size + cleanFluids.size) for (e in catalysts.entries) { val ri = e.key val rfg = e.value val stk = ri.makeItemStack() if (rfg.usage > 0) stk.count = rfg.usage.toInt() recipes.add(FluxGenRecipeJEI(igh, stk, null, rfg.factor.toInt(), 1)) } addFluids(igh, recipes, hotFluids, 0) addFluids(igh, recipes, cleanFluids, 1) return recipes } private fun addFluids(igh: IGuiHelper, l: MutableList<FluxGenRecipeJEI>, m: Map<FluidStack, RecipeFluxGen>, s: Int) { for ((key, rfg) in m) { val fs = key.copy() fs.amount = (if (rfg.usage > 0) rfg.usage else 1).toInt() l.add(FluxGenRecipeJEI(igh, ItemStack.EMPTY, fs, rfg.factor.toInt(), s)) } } }
src/main/java/szewek/mcflux/compat/jei/fluxgen/FluxGenRecipeMaker.kt
3748012309
package nice3point.by.schedule.ScheduleDialogChanger import android.view.View interface iVScheduleChanger { fun switchDeleteIconVisibility(viewVisible: Int) fun setConfirmButtonListener(listener: View.OnClickListener) fun closeDialog() fun getTextViewData(): Array<String?> fun setTextViewData(teacher: String, subject: String, cabinet: String, startTime: String, endTime: String, type: String) fun delBtEdit() }
app/src/main/java/nice3point/by/schedule/ScheduleDialogChanger/iVScheduleChanger.kt
4137012479
package com.github.dawidhyzy.kotlinsample import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* import rx.android.schedulers.AndroidSchedulers import rx.schedulers.Schedulers class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { setTheme(R.style.AppTheme) super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) val nasaApi = NasaApi.create() val observable = nasaApi.getNasaJson(50.0968457f, 19.8891281f) observable .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( { response : NasaResponse -> nasaImageView.load(response.url) }, { error : Throwable -> Log.e("XXX", error.message)}) } }
app/src/main/kotlin/com/github/dawidhyzy/kotlinsample/MainActivity.kt
4062122323
package rt import java.lang.Math internal fun MathSqrt(v: Double) = Math.sqrt(v) internal fun MathAbs(v: Double) = Math.abs(v)
kotlin/math-java.kt
2406429694
/* * Copyright 2018 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.kotlin.dsl.codegen import com.nhaarman.mockito_kotlin.atMost import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.verifyNoMoreInteractions import org.gradle.api.internal.file.pattern.PatternMatcher import org.gradle.api.internal.file.temp.DefaultTemporaryFileProvider import org.gradle.internal.hash.Hashing import org.gradle.kotlin.dsl.accessors.TestWithClassPath import org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments import org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass import org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType import org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments import org.gradle.test.fixtures.file.LeaksFileHandles import org.hamcrest.CoreMatchers.containsString import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.Test import org.slf4j.Logger import java.io.File import java.util.Properties import java.util.function.Consumer import java.util.jar.Attributes import java.util.jar.JarEntry import java.util.jar.JarOutputStream import java.util.jar.Manifest import kotlin.reflect.KClass @LeaksFileHandles("embedded Kotlin compiler environment keepalive") class GradleApiExtensionsTest : TestWithClassPath() { @Test fun `gradle-api-extensions generated jar is reproducible`() { apiKotlinExtensionsGenerationFor( ClassToKClass::class, ClassToKClassParameterizedType::class, GroovyNamedArguments::class, ClassAndGroovyNamedArguments::class ) { assertGeneratedJarHash("6236f057767b0bf27131a299c9128997") } } @Test fun `maps java-lang-Class to kotlin-reflect-KClass`() { apiKotlinExtensionsGenerationFor(ClassToKClass::class) { assertGeneratedExtensions( """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`rawClass`(`type`: kotlin.reflect.KClass<*>): Unit = `rawClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`unknownClass`(`type`: kotlin.reflect.KClass<*>): Unit = `unknownClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`invariantClass`(`type`: kotlin.reflect.KClass<kotlin.Number>): Unit = `invariantClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantClass`(`type`: kotlin.reflect.KClass<out kotlin.Number>): Unit = `covariantClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`contravariantClass`(`type`: kotlin.reflect.KClass<in Int>): Unit = `contravariantClass`(`type`.java) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`varargOfClasses`(vararg `types`: kotlin.reflect.KClass<*>): Unit = `varargOfClasses`(*`types`.map { it.java }.toTypedArray()) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`arrayOfClasses`(`types`: kotlin.Array<kotlin.reflect.KClass<*>>): Unit = `arrayOfClasses`(`types`.map { it.java }.toTypedArray()) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`collectionOfClasses`(`types`: kotlin.collections.Collection<kotlin.reflect.KClass<out kotlin.Number>>): Unit = `collectionOfClasses`(`types`.map { it.java }) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedClass`(`type`: kotlin.reflect.KClass<T>): T = `methodParameterizedClass`(`type`.java) """, """ inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedClass`(`type`: kotlin.reflect.KClass<T>): T = `covariantMethodParameterizedClass`(`type`.java) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out T>): T = `methodParameterizedCovariantClass`(`type`.java) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`methodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in T>): T = `methodParameterizedContravariantClass`(`type`.java) """, """ inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out T>): T = `covariantMethodParameterizedCovariantClass`(`type`.java) """, """ inline fun <T : kotlin.Number> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClass.`covariantMethodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in T>): T = `covariantMethodParameterizedContravariantClass`(`type`.java) """ ) assertUsageCompilation( """ import kotlin.reflect.* fun classToKClass(subject: ClassToKClass) { subject.rawClass(type = String::class) subject.unknownClass(type = String::class) subject.invariantClass(type = Number::class) subject.covariantClass(type = Int::class) subject.contravariantClass(type = Number::class) subject.varargOfClasses(Number::class, Int::class) subject.arrayOfClasses(types = arrayOf(Number::class, Int::class)) subject.collectionOfClasses(listOf(Number::class, Int::class)) subject.methodParameterizedClass(type = Int::class) subject.covariantMethodParameterizedClass(type = Int::class) subject.methodParameterizedCovariantClass(type = Int::class) subject.methodParameterizedContravariantClass(type = Int::class) subject.covariantMethodParameterizedCovariantClass(type = Int::class) subject.covariantMethodParameterizedContravariantClass(type = Int::class) } """ ) } } @Test fun `maps Groovy named arguments to Kotlin vararg of Pair`() { apiKotlinExtensionsGenerationFor(GroovyNamedArguments::class, Consumer::class) { assertGeneratedExtensions( """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`rawMap`(vararg `args`: Pair<String, Any?>): Unit = `rawMap`(mapOf(*`args`)) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`stringUnknownMap`(vararg `args`: Pair<String, Any?>): Unit = `stringUnknownMap`(mapOf(*`args`)) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`stringObjectMap`(vararg `args`: Pair<String, Any?>): Unit = `stringObjectMap`(mapOf(*`args`)) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`mapWithOtherParameters`(`foo`: String, `bar`: Int, vararg `args`: Pair<String, Any?>): Unit = `mapWithOtherParameters`(mapOf(*`args`), `foo`, `bar`) """, """ inline fun org.gradle.kotlin.dsl.fixtures.codegen.GroovyNamedArguments.`mapWithLastSamAndOtherParameters`(`foo`: String, vararg `args`: Pair<String, Any?>, `bar`: java.util.function.Consumer<String>): Unit = `mapWithLastSamAndOtherParameters`(mapOf(*`args`), `foo`, `bar`) """ ) assertUsageCompilation( """ import java.util.function.Consumer fun usage(subject: GroovyNamedArguments) { subject.rawMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral") subject.stringUnknownMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral") subject.stringObjectMap("foo" to 42, "bar" to 23L, "bazar" to "cathedral") subject.mapWithOtherParameters(foo = "foo", bar = 42) subject.mapWithOtherParameters("foo", 42, "bar" to 23L, "bazar" to "cathedral") subject.mapWithLastSamAndOtherParameters(foo = "foo") { println(it.toUpperCase()) } subject.mapWithLastSamAndOtherParameters("foo", "bar" to 23L, "bazar" to "cathedral") { println(it.toUpperCase()) } subject.mapWithLastSamAndOtherParameters("foo", *arrayOf("bar" to 23L, "bazar" to "cathedral")) { println(it.toUpperCase()) } subject.mapWithLastSamAndOtherParameters(foo = "foo", bar = Consumer { println(it.toUpperCase()) }) subject.mapWithLastSamAndOtherParameters(foo = "foo", bar = Consumer<String> { println(it.toUpperCase()) }) } """ ) } } @Test fun `maps mixed java-lang-Class and Groovy named arguments`() { apiKotlinExtensionsGenerationFor(ClassAndGroovyNamedArguments::class, Consumer::class) { assertGeneratedExtensions( """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClass`(`type`: kotlin.reflect.KClass<out T>, vararg `args`: Pair<String, Any?>): Unit = `mapAndClass`(mapOf(*`args`), `type`.java) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClassAndVarargs`(`type`: kotlin.reflect.KClass<out T>, `options`: kotlin.Array<String>, vararg `args`: Pair<String, Any?>): Unit = `mapAndClassAndVarargs`(mapOf(*`args`), `type`.java, *`options`) """, """ inline fun <T : Any> org.gradle.kotlin.dsl.fixtures.codegen.ClassAndGroovyNamedArguments.`mapAndClassAndSAM`(`type`: kotlin.reflect.KClass<out T>, vararg `args`: Pair<String, Any?>, `action`: java.util.function.Consumer<in T>): Unit = `mapAndClassAndSAM`(mapOf(*`args`), `type`.java, `action`) """ ) assertUsageCompilation( """ import java.util.function.Consumer fun usage(subject: ClassAndGroovyNamedArguments) { subject.mapAndClass<Number>(Int::class) subject.mapAndClass<Number>(Int::class, "foo" to 42, "bar" to "bazar") subject.mapAndClassAndVarargs<Number>(Int::class, arrayOf("foo", "bar")) subject.mapAndClassAndVarargs<Number>(Int::class, arrayOf("foo", "bar"), "bazar" to "cathedral") } """ ) } } @Test fun `maps target type, mapped function and parameters generics`() { apiKotlinExtensionsGenerationFor(ClassToKClassParameterizedType::class) { assertGeneratedExtensions( """ inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`invariantClass`(`type`: kotlin.reflect.KClass<T>, `list`: kotlin.collections.List<T>): T = `invariantClass`(`type`.java, `list`) """, """ inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantClass`(`type`: kotlin.reflect.KClass<out T>, `list`: kotlin.collections.List<T>): T = `covariantClass`(`type`.java, `list`) """, """ inline fun <T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`contravariantClass`(`type`: kotlin.reflect.KClass<in T>, `list`: kotlin.collections.List<T>): T = `contravariantClass`(`type`.java, `list`) """, """ inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedInvariantClass`(`type`: kotlin.reflect.KClass<V>, `list`: kotlin.collections.List<V>): V = `covariantMethodParameterizedInvariantClass`(`type`.java, `list`) """, """ inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedCovariantClass`(`type`: kotlin.reflect.KClass<out V>, `list`: kotlin.collections.List<out V>): V = `covariantMethodParameterizedCovariantClass`(`type`.java, `list`) """, """ inline fun <V : T, T : java.io.Serializable> org.gradle.kotlin.dsl.fixtures.codegen.ClassToKClassParameterizedType<T>.`covariantMethodParameterizedContravariantClass`(`type`: kotlin.reflect.KClass<in V>, `list`: kotlin.collections.List<out V>): V = `covariantMethodParameterizedContravariantClass`(`type`.java, `list`) """ ) assertUsageCompilation( """ import java.io.Serializable fun usage(subject: ClassToKClassParameterizedType<Number>) { subject.invariantClass(Number::class, emptyList()) subject.covariantClass(Int::class, emptyList()) subject.contravariantClass(Serializable::class, emptyList()) subject.covariantMethodParameterizedInvariantClass(Number::class, emptyList()) subject.covariantMethodParameterizedCovariantClass(Int::class, emptyList()) subject.covariantMethodParameterizedContravariantClass(Serializable::class, emptyList()) } """ ) } } private fun apiKotlinExtensionsGenerationFor(vararg classes: KClass<*>, action: ApiKotlinExtensionsGeneration.() -> Unit) = ApiKotlinExtensionsGeneration(apiJarsWith(*classes), fixturesApiMetadataJar()).apply(action) private data class ApiKotlinExtensionsGeneration(val apiJars: List<File>, val apiMetadataJar: File) { lateinit var generatedSourceFiles: List<File> } private fun ApiKotlinExtensionsGeneration.assertGeneratedExtensions(vararg expectedExtensions: String) { generatedSourceFiles = generateKotlinDslApiExtensionsSourceTo( file("src").also { it.mkdirs() }, "org.gradle.kotlin.dsl", "SourceBaseName", apiJars, emptyList(), PatternMatcher.MATCH_ALL, fixtureParameterNamesSupplier ) val generatedSourceCode = generatedSourceFiles.joinToString("") { it.readText().substringAfter("package org.gradle.kotlin.dsl\n\n") } println(generatedSourceCode) expectedExtensions.forEach { expectedExtension -> assertThat(generatedSourceCode, containsString(expectedExtension.trimIndent())) } } private fun ApiKotlinExtensionsGeneration.assertUsageCompilation(vararg extensionsUsages: String) { val useDir = file("use").also { it.mkdirs() } val usageFiles = extensionsUsages.mapIndexed { idx, usage -> useDir.resolve("usage$idx.kt").also { it.writeText( """ import org.gradle.kotlin.dsl.fixtures.codegen.* import org.gradle.kotlin.dsl.* $usage """.trimIndent() ) } } val logger = mock<Logger> { on { isTraceEnabled } doReturn false on { isDebugEnabled } doReturn false } compileKotlinApiExtensionsTo( file("out").also { it.mkdirs() }, generatedSourceFiles + usageFiles, apiJars, logger ) // Assert no warnings were emitted verify(logger, atMost(1)).isTraceEnabled verify(logger, atMost(1)).isDebugEnabled verifyNoMoreInteractions(logger) } private fun GradleApiExtensionsTest.ApiKotlinExtensionsGeneration.assertGeneratedJarHash(hash: String) = file("api-extensions.jar").let { generatedJar -> generateApiExtensionsJar( DefaultTemporaryFileProvider { newFolder("tmp") }, generatedJar, apiJars, apiMetadataJar ) {} assertThat( Hashing.md5().hashFile(generatedJar).toZeroPaddedString(32), equalTo(hash) ) } private fun apiJarsWith(vararg classes: KClass<*>): List<File> = jarClassPathWith("gradle-api.jar", *classes, org.gradle.api.Generated::class).asFiles private fun fixturesApiMetadataJar(): File = file("gradle-api-metadata.jar").also { file -> JarOutputStream( file.outputStream().buffered(), Manifest().apply { mainAttributes[Attributes.Name.MANIFEST_VERSION] = "1.0" } ).use { output -> output.putNextEntry(JarEntry("gradle-api-declaration.properties")) Properties().apply { setProperty("includes", "org/gradle/kotlin/dsl/fixtures/codegen/**") setProperty("excludes", "**/internal/**") store(output, null) } } } } private val fixtureParameterNamesSupplier = { key: String -> when { key.startsWith("${ClassToKClass::class.qualifiedName}.") -> when { key.contains("Class(") -> listOf("type") key.contains("Classes(") -> listOf("types") else -> null } key.startsWith("${GroovyNamedArguments::class.qualifiedName}.") -> when { key.contains("Map(") -> listOf("args") key.contains("Parameters(") -> listOf("args", "foo", "bar") else -> null } key.startsWith("${ClassAndGroovyNamedArguments::class.qualifiedName}.") -> when { key.contains("mapAndClass(") -> listOf("args", "type") key.contains("mapAndClassAndVarargs(") -> listOf("args", "type", "options") key.contains("mapAndClassAndSAM(") -> listOf("args", "type", "action") else -> null } key.startsWith("${ClassToKClassParameterizedType::class.qualifiedName}.") -> when { key.contains("Class(") -> listOf("type", "list") else -> null } else -> null } }
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/codegen/GradleApiExtensionsTest.kt
1982565220
/* * The MIT License (MIT) * * Copyright (c) 2017-2019 Nephy Project Team * * 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. */ @file:Suppress("UNUSED", "PublicApiImplicitType") package jp.nephy.penicillin.endpoints.accountactivity import jp.nephy.penicillin.core.request.action.EmptyApiAction import jp.nephy.penicillin.core.request.parameters import jp.nephy.penicillin.core.session.delete import jp.nephy.penicillin.endpoints.AccountActivity import jp.nephy.penicillin.endpoints.Option /** * Removes the webhook from the provided application's all activities configuration. The webhook ID can be accessed by making a call to GET /1.1/account_activity/all/webhooks. * * [Twitter API reference](https://developer.twitter.com/en/docs/accounts-and-users/subscribe-account-activity/api-reference/aaa-premium#delete-account-activity-all-env-name-webhooks-webhook-id) * * @param envName Environment name. * @param webhookId Webhook id. * @param options Optional. Custom parameters of this request. * @receiver [AccountActivity] endpoint instance. * @return [EmptyApiAction]. */ fun AccountActivity.deleteWebhook( envName: String, webhookId: String, vararg options: Option ) = client.session.delete("/1.1/account_activity/all/$envName/webhooks/$webhookId.json") { parameters(*options) }.empty()
src/main/kotlin/jp/nephy/penicillin/endpoints/accountactivity/DeleteWebhook.kt
2589176947
package com.jayrave.falkon.mapper.lib import com.jayrave.falkon.engine.Source import com.jayrave.falkon.mapper.DataProducer import com.jayrave.falkon.mapper.ReadOnlyColumn import com.jayrave.falkon.mapper.Realizer import org.assertj.core.api.Assertions.assertThat import org.junit.Test import com.jayrave.falkon.engine.CompiledStatement as CS class CompiledQueryExtnTestsForRealizer : BaseClassForCompiledQueryExtnTests() { @Test fun `extract first model from empty source returns null`() { extractAndAssertModelFromEmptySource { realizer, cs -> val model = cs.extractFirstModel(realizer, colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() model } } @Test fun `extract first model`() { extractAndAssertModel { realizer, cs -> val model = cs.extractFirstModel(realizer, colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() model } } @Test fun `extract first model and close from empty source returns null`() { extractAndAssertModelFromEmptySource { realizer, cs -> val model = cs.extractFirstModelAndClose(realizer, colNameExtractor) assertThat(cs.isClosed).isTrue() model } } @Test fun `extract first model and close`() { extractAndAssertModel { realizer, cs -> val model = cs.extractFirstModelAndClose(realizer, colNameExtractor) assertThat(cs.isClosed).isTrue() model } } @Test fun `extract all models from empty source returns empty list`() { extractAndAssertModelsFromEmptySource { realizer, cs -> val models = cs.extractAllModels(realizer, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() models } } @Test fun `extract all models`() { extractAndAssertModels { realizer, cs -> val models = cs.extractAllModels(realizer, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() models } } @Test fun `extract all models and close from empty source returns empty list`() { extractAndAssertModelsFromEmptySource { r, cs -> val models = cs.extractAllModelsAndClose(r, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isTrue() models } } @Test fun `extract all models and close`() { extractAndAssertModels { r, cs -> val models = cs.extractAllModelsAndClose(r, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isTrue() models } } @Test fun `extract models with empty source returns empty list`() { extractAndAssertModelsFromEmptySource { realizer, cs -> val models = cs.extractAllModels(realizer, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() models } } @Test fun `extract models with source not having enough rows`() { extractAndAssertModels( maxModelsToExtract = 6, numberOfRowsInSource = 4) { realizer, cs -> val models = cs.extractAllModels(realizer, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() models } } @Test fun `extract models with more rows available in source`() { extractAndAssertModels( maxModelsToExtract = 4, numberOfRowsInSource = 6) { realizer, cs -> val models = cs.extractAllModels(realizer, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isFalse() cs.close() models } } @Test fun `extract models and close with empty source returns empty list`() { extractAndAssertModelsFromEmptySource { r, cs -> val models = cs.extractAllModelsAndClose(r, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isTrue() models } } @Test fun `extract models and close with source not having enough rows`() { extractAndAssertModels(maxModelsToExtract = 6, numberOfRowsInSource = 4) { r, cs -> val models = cs.extractAllModelsAndClose(r, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isTrue() models } } @Test fun `extract models and close with more rows available in source`() { extractAndAssertModels(maxModelsToExtract = 4, numberOfRowsInSource = 6) { r, cs -> val models = cs.extractAllModelsAndClose(r, columnNameExtractor = colNameExtractor) assertThat(cs.isClosed).isTrue() models } } private fun extractAndAssertModelFromEmptySource( op: (RealizerForTest, CS<Source>) -> ModelWithCount?) { clearTestTable() val builtModel = op.invoke(RealizerForTest(), compileDistinctSelectQueryOrderedByInt()) assertThat(builtModel).isNull() } private fun extractAndAssertModelsFromEmptySource( op: (RealizerForTest, CS<Source>) -> List<ModelWithCount>) { clearTestTable() val builtModels = op.invoke(RealizerForTest(), compileDistinctSelectQueryOrderedByInt()) assertThat(builtModels).isEmpty() } private fun extractAndAssertModel(op: (table: RealizerForTest, CS<Source>) -> ModelWithCount?) { // Build source val seed = 5 clearTestTable() insertRow(seed) insertRow(seed + 1) insertRow(seed) insertRow(seed + 2) insertRow(seed) // Extract & verify model val builtModel = op.invoke(RealizerForTest(), compileDistinctSelectQueryOrderedByInt())!! assertThat(builtModel.int).isEqualTo(seed) assertThat(builtModel.string).isEqualTo("test $seed") assertThat(builtModel.occurrenceCount).isEqualTo(3) } private fun extractAndAssertModels(op: (RealizerForTest, CS<Source>) -> List<ModelWithCount>) { // Build source val seed = 5 clearTestTable() insertRow(seed) insertRow(seed + 1) insertRow(seed + 2) insertRow(seed + 1) insertRow(seed + 2) insertRow(seed) // Extract & verify model val builtModels = op.invoke(RealizerForTest(), compileDistinctSelectQueryOrderedByInt()) assertThat(builtModels.size).isEqualTo(3) builtModels.forEachIndexed { index, builtModel -> val valueForThisIteration = seed + index assertThat(builtModel.int).isEqualTo(valueForThisIteration) assertThat(builtModel.string).isEqualTo("test $valueForThisIteration") assertThat(builtModel.occurrenceCount).isEqualTo(2) } } private fun extractAndAssertModels( maxModelsToExtract: Int, numberOfRowsInSource: Int, op: (RealizerForTest, CS<Source>) -> List<ModelWithCount>) { // Build source val seed = 5 clearTestTable() val expectedNumberOfUniqueModelsExtracted = Math.min( maxModelsToExtract, numberOfRowsInSource ) (0..expectedNumberOfUniqueModelsExtracted - 1).forEach { insertRow(seed + it) insertRow(seed + it) } // Extract & verify model val builtModels = op.invoke(RealizerForTest(), compileDistinctSelectQueryOrderedByInt()) assertThat(builtModels.size).isEqualTo(expectedNumberOfUniqueModelsExtracted) builtModels.forEachIndexed { index, builtModel -> val valueForThisIteration = seed + index assertThat(builtModel.int).isEqualTo(valueForThisIteration) assertThat(builtModel.string).isEqualTo("test $valueForThisIteration") assertThat(builtModel.occurrenceCount).isEqualTo(2) } } private fun compileDistinctSelectQueryOrderedByInt(): CS<Source> { // Select column names with & without alias to make sure both // cases are handled correctly return engine.compileQuery( listOf(TABLE_NAME), "SELECT " + "$INT_COL_NAME, $STRING_COL_NAME AS $STRING_COL_NAME_ALIAS, " + "$OCCURRENCE_COUNT_COL_NAME AS $OCCURRENCE_COUNT_COL_NAME_ALIAS " + "FROM $TABLE_NAME " + "GROUP BY $STRING_COL_NAME_ALIAS " + "ORDER BY $INT_COL_NAME" ) } private class ModelWithCount(val int: Int, val string: String, val occurrenceCount: Long) private class ReadOnlyColumnForTest<out C>( override val name: String, private val propertyExtractor: (DataProducer) -> C) : ReadOnlyColumn<C> { override fun computePropertyFrom(dataProducer: DataProducer): C { return propertyExtractor.invoke(dataProducer) } } private class RealizerForTest : Realizer<ModelWithCount> { val int = ReadOnlyColumnForTest(INT_COL_NAME, { it.getInt() }) val string = TableForTest().stringCol val occurrenceCount = ReadOnlyColumnForTest(OCCURRENCE_COUNT_COL_NAME, { it.getLong() }) override fun realize(value: Realizer.Value): ModelWithCount { return ModelWithCount(value of int, value of string, value of occurrenceCount) } } companion object { private const val STRING_COL_NAME_ALIAS = "mnc_string_col" private const val OCCURRENCE_COUNT_COL_NAME = "count(string)" private const val OCCURRENCE_COUNT_COL_NAME_ALIAS = "count" private val colNameExtractor: ((ReadOnlyColumn<*>) -> String) = { when (it.name) { INT_COL_NAME -> INT_COL_NAME STRING_COL_NAME -> STRING_COL_NAME_ALIAS OCCURRENCE_COUNT_COL_NAME -> OCCURRENCE_COUNT_COL_NAME_ALIAS else -> throw IllegalArgumentException("Unrecognized col name: ${it.name}") } } } }
falkon-mapper/src/test/kotlin/com/jayrave/falkon/mapper/lib/CompiledQueryExtnTestsForRealizer.kt
3281635678
package com.jayrave.falkon.engine.android.sqlite import androidx.sqlite.db.SimpleSQLiteQuery import androidx.sqlite.db.SupportSQLiteDatabase import com.jayrave.falkon.engine.CompiledStatement import com.jayrave.falkon.engine.Source import com.jayrave.falkon.engine.Type import java.sql.SQLException import java.util.* /** * This isn't actually a compiled statement as there is no way (that Jay could find) in Android * to compile a SELECT statement!! This class just stores the sql & the bind args, and when * [execute] is called, send them off to the database * * *CAUTION: * This class is not thread-safe */ internal class CompiledQuery(override val sql: String, private val database: SupportSQLiteDatabase) : CompiledStatement<Source> { private var bindArgs: MutableMap<Int, Any?> = newArgsMap() override var isClosed = false private set override fun execute(): Source { throwIfClosed() return CursorBackedSource(database.query( SimpleSQLiteQuery( sql, Array<Any?>(bindArgs.size) { null }.also { arr -> bindArgs.forEach { (index, value) -> arr[index - 1] = value } } ) )) } override fun bindShort(index: Int, value: Short): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindInt(index: Int, value: Int): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindLong(index: Int, value: Long): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindFloat(index: Int, value: Float): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindDouble(index: Int, value: Double): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindString(index: Int, value: String): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindBlob(index: Int, value: ByteArray): CompiledStatement<Source> { bindArg(index, value) return this } override fun bindNull(index: Int, type: Type): CompiledStatement<Source> { bindArg(index, null) return this } override fun close() { isClosed = true } override fun clearBindings(): CompiledStatement<Source> { throwIfClosed() bindArgs = newArgsMap() return this } private fun bindArg(index: Int, value: Any?) { throwIfClosed() bindArgs.put(index, value) } private fun throwIfClosed() { if (isClosed) { throw SQLException("CompiledQuery has already been closed!!") } } companion object { private fun newArgsMap(): MutableMap<Int, Any?> = HashMap() } }
falkon-engine-android-sqlite/src/main/kotlin/com/jayrave/falkon/engine/android/sqlite/CompiledQuery.kt
3754000471
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalCoilApi::class, ExperimentalComposeUiApi::class) package com.example.constraintlayout import android.content.ContentResolver import android.content.Context import android.net.Uri import androidx.annotation.DrawableRes import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.Layout import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.Placeable import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import androidx.constraintlayout.compose.ConstrainScope import androidx.constraintlayout.compose.ConstraintLayout import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.Dimension import androidx.constraintlayout.compose.Motion import androidx.constraintlayout.compose.layoutId import androidx.constraintlayout.compose.rememberMotionListItems import coil.annotation.ExperimentalCoilApi import coil.compose.rememberImagePainter import coil.request.ImageRequest import kotlin.math.roundToInt private val ItemHeight = 100.dp @Preview @Composable private fun ExpandableListPreview() { val durationMs = 800 val itemsData = createItemDataList(count = 10) /** * ConstraintLayout when collapsed, Column when expanded */ var collapsedOrExpanded by remember { mutableStateOf(true) } /** * Define the items that'll be present both in ConstraintLayout and Column, since the parent * node will change from one to the other we need to use [rememberMotionListItems]. */ val items = rememberMotionListItems(count = itemsData.size) { index -> CartItem( modifier = Modifier // In this case, these Dimensions do not cause conflict with ConstraintLayout .fillMaxWidth() .height(ItemHeight) .layoutId(index.toString()) // For ConstraintLayout // ignoreAxisChanges prevents animation from triggering during scroll .motion(animationSpec = tween(durationMs), ignoreAxisChanges = true) { // We may apply keyframes to modify the items during animation keyAttributes { frame(50) { scaleX = 0.7f scaleY = 0.7f } } } .zIndex((itemsData.size - index).toFloat()), item = itemsData[index] ) } Column( Modifier .fillMaxSize() .background(Color.LightGray) .verticalScroll(rememberScrollState()) ) { Column( Modifier .fillMaxWidth() ) { // Motion Composable enables the `motion` Modifier. Motion( modifier = Modifier .fillMaxWidth() .background(Color.Gray) .padding(bottom = 8.dp) .animateContentSize(tween(durationMs)) // Match the animated content ) { // Here we'll change the Layout Composable for our items based on the // `collapsedOrExpanded` state, we may use the `emit` extension function to // simplify it. if (collapsedOrExpanded) { CollapsedCartList( modifier = Modifier .fillMaxWidth(), dataSize = items.size ) { items.emit() } } else { Column( modifier = Modifier .fillMaxWidth() .padding(8.dp), verticalArrangement = Arrangement.spacedBy(16.dp) ) { items.emit() } } } } Text(text = "Layout: " + if (collapsedOrExpanded) "ConstraintLayout" else "Column") Button(onClick = { collapsedOrExpanded = !collapsedOrExpanded }) { Text(text = "Toggle") } } } /** * Collapsed view using ConstraintLayout, will layout the first three items one below the other, all * other items will be stacked under each other. * * The content most have their [Modifier.layoutId] assigned from 0 to [dataSize] - 1. * * @see CollapsedCartListPreview */ @Composable private fun CollapsedCartList( modifier: Modifier = Modifier, dataSize: Int, content: @Composable () -> Unit ) { val itemIds: List<Int> = remember { List(dataSize) { index -> index } } val cSet = remember { val applyDimensions: ConstrainScope.() -> Unit = { width = Dimension.fillToConstraints height = Dimension.value(ItemHeight) } ConstraintSet { val itemRefsById = itemIds.associateWith { createRefFor(it.toString()) } itemRefsById.forEach { (id, ref) -> when (id) { 0, 1, 2 -> { // Stack the first three items below each other constrain(ref) { val lastRef = itemRefsById[id - 1] ?: parent applyDimensions() start.linkTo(lastRef.start, 8.dp) end.linkTo(lastRef.end, 8.dp) top.linkTo(lastRef.top, 16.dp) translationZ = (6 - (2 * id)).coerceAtLeast(0).dp } } else -> { // Stack/hide together all other items if (id > 0) { val lastRef = itemRefsById[2]!! constrain(ref) { applyDimensions() centerTo(lastRef) } } } } } } } ConstraintLayout( modifier = modifier, constraintSet = cSet ) { content() } } /** * Non-ConstraintLayout variant of [CollapsedCartList]. */ @Composable private fun CollapsedCartListCustom( modifier: Modifier = Modifier, content: @Composable () -> Unit ) { val density = LocalDensity.current Layout( measurePolicy = remember { MeasurePolicy { measurables, constraints -> var count = 2 val placeables = mutableListOf<Placeable>() var maxWidth = constraints.maxWidth var itemsToWrap = 0 measurables.forEach { measurable -> if (count-- >= 0) { itemsToWrap++ maxWidth -= with(density) { 16.dp.toPx() }.roundToInt() placeables.add( measurable.measure( Constraints.fixed( maxWidth, with(density) { 100.dp.toPx() }.roundToInt() ) ) ) } else { placeables.add( measurable.measure( Constraints.fixed( maxWidth, with(density) { 100.dp.toPx() }.roundToInt() ) ) ) } } layout( width = constraints.maxWidth, height = with(density) { itemsToWrap * 16.dp.roundToPx() + 100.dp.roundToPx() } ) { count = 2 var x = 0 var y = 0 placeables.forEach { placeable -> if (count-- >= 0) { x += with(density) { 8.dp.roundToPx() } y += with(density) { 16.dp.roundToPx() } placeable.place(x, y, (count + 1).times(2).toFloat()) } else { placeable.place(x, y, 0f) } } } } }, modifier = modifier, content = content ) } @Composable private fun CartItem(modifier: Modifier = Modifier, item: ItemData) { ConstraintLayout( modifier = modifier .background(color = Color.White, shape = RoundedCornerShape(10.dp)) .padding(8.dp), constraintSet = remember { ConstraintSet { val image = createRefFor("image") val name = createRefFor("name") val id = createRefFor("id") val cost = createRefFor("cost") constrain(image) { width = Dimension.ratio("1:1") height = Dimension.fillToConstraints top.linkTo(parent.top) bottom.linkTo(parent.bottom) start.linkTo(parent.start) } constrain(cost) { end.linkTo(parent.end) bottom.linkTo(parent.bottom) } constrain(name) { width = Dimension.fillToConstraints start.linkTo(image.end, 8.dp) end.linkTo(cost.start, 8.dp) baseline.linkTo(cost.baseline) } constrain(id) { top.linkTo(parent.top) end.linkTo(parent.end) } } } ) { Image( modifier = Modifier .layoutId("image") .clip(RoundedCornerShape(10.dp)), painter = rememberImagePainter( request = ImageRequest.Builder(LocalContext.current) .data(item.thumbnailUri) .placeholder(R.drawable.pepper) .build() ), contentDescription = null ) Text(modifier = Modifier.layoutId("name"), text = item.name) Text(modifier = Modifier.layoutId("cost"), text = "$${item.cost}") Text(modifier = Modifier.layoutId("id"), text = item.id.toString()) } } @Stable private data class ItemData( val id: Int, val thumbnailUri: Uri, val name: String, val cost: Float ) /** * Returns a list of [ItemData] objects with randomly populated values. * * @param count amount of [ItemData] generated */ @Composable private fun createItemDataList(count: Int): List<ItemData> { val context = LocalContext.current return remember(count) { List(count) { index -> ItemData( id = index, thumbnailUri = context.drawableUri(R.drawable.pepper), name = itemNames.random(), cost = IntRange(5, 50).random().toFloat() + (IntRange(0, 99).random() / 100f) ) } } } @Preview @Composable private fun CollapsedCartListPreview() { val itemsData = createItemDataList(count = 5) Column(Modifier.fillMaxWidth()) { Column(Modifier.background(Color.LightGray)) { Text(text = "ConstraintLayout") CollapsedCartList( modifier = Modifier.fillMaxWidth(), dataSize = itemsData.size ) { itemsData.forEachIndexed { index, itemData -> CartItem( modifier = Modifier .fillMaxWidth() .height(100.dp) .layoutId(index.toString()), item = itemData ) } } } Column(Modifier.background(Color.Gray)) { Text(text = "Custom Layout") CollapsedCartListCustom(modifier = Modifier.fillMaxWidth()) { itemsData.forEachIndexed { _, itemData -> CartItem(item = itemData) } } } } } @Preview @Composable private fun ExpandedCartListPreview() { val itemsData = createItemDataList(count = 5) Column( modifier = Modifier .fillMaxSize() .background(Color.LightGray), verticalArrangement = Arrangement.spacedBy(16.dp) ) { itemsData.forEach { CartItem( modifier = Modifier .fillMaxWidth() .height(100.dp), item = it ) } } } @Preview @Composable private fun CartItemPreview() { CartItem( modifier = Modifier .fillMaxWidth() .height(100.dp), item = ItemData( id = 0, thumbnailUri = LocalContext.current.drawableUri(R.drawable.pepper), name = "Pepper", cost = 5.56f ) ) } internal fun Context.drawableUri(@DrawableRes resourceId: Int): Uri = with(resources) { Uri.Builder() .scheme(ContentResolver.SCHEME_ANDROID_RESOURCE) .authority(getResourcePackageName(resourceId)) .appendPath(getResourceTypeName(resourceId)) .appendPath(getResourceEntryName(resourceId)) .build() } private val itemNames = listOf( "Fruit", "Vegetables", "Bread", "Pet Food", "Cereal", "Milk", "Eggs", "Yogurt" )
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/MotionModifierListDemo.kt
98009512
package cc.redpen.intellij.fixes import cc.redpen.config.Configuration import cc.redpen.config.ValidatorConfiguration import com.intellij.openapi.util.TextRange import com.nhaarman.mockito_kotlin.capture import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.junit.Assert.assertEquals import org.junit.Test class NumberFormatQuickFixTest : BaseQuickFixTest(NumberFormatQuickFix(createConfig("en"), "7000000,50")) { companion object { fun createConfig(lang: String) = Configuration.builder(lang).addValidatorConfig(ValidatorConfiguration("NumberFormat")).build() } @Test fun name() { assertEquals("Change to 7,000,000.50", quickFix.name) } @Test fun applyFixForUS() { whenever(document.text).thenReturn("Amount: $7000000.50") whenever(problem.textRangeInElement).thenReturn(TextRange(9, 19)) quickFix.applyFix(project, problem) verify(quickFix).writeAction(eq(project), capture { it.invoke() }) verify(document).replaceString(9, 19, "7,000,000.50") } @Test fun applyFixForUK() { (quickFix as NumberFormatQuickFix).config.validatorConfigs[0].properties["decimal_delimiter_is_comma"] = "true" whenever(document.text).thenReturn("Amount: £7000000.50") whenever(problem.textRangeInElement).thenReturn(TextRange(9, 19)) quickFix.applyFix(project, problem) verify(quickFix).writeAction(eq(project), capture { it.invoke() }) verify(document).replaceString(9, 19, "7.000.000,50") } @Test fun applyFixForJapaneseZenkaku() { (quickFix as NumberFormatQuickFix).config = createConfig("ja") whenever(document.text).thenReturn("7000000.50元") whenever(problem.textRangeInElement).thenReturn(TextRange(0, 10)) quickFix.applyFix(project, problem) verify(quickFix).writeAction(eq(project), capture { it.invoke() }) verify(document).replaceString(0, 10, "7.000.000・50") } }
test/cc/redpen/intellij/fixes/NumberFormatQuickFixTest.kt
4208573464
package tech.summerly.quiet.data.netease.result import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName /** * author : SUMMERLY * e-mail : [email protected] * time : 2017/8/25 * desc : */ data class UserDetailResultBean( @SerializedName("profile") @Expose val profile: Profile? = null, @SerializedName("level") @Expose val level: Int? = null, @SerializedName("listenSongs") @Expose val listenSongs: Long? = null, @SerializedName("userPoint") @Expose val userPoint: UserPoint? = null, // @SerializedName("mobileSign") // @Expose // val mobileSign: Boolean? = null, // @SerializedName("pcSign") // @Expose // val pcSign: Boolean? = null, // @SerializedName("peopleCanSeeMyPlayRecord") // @Expose // val peopleCanSeeMyPlayRecord: Boolean? = null, // @SerializedName("bindings") // @Expose // val bindings: List<Binding>? = null, @SerializedName("adValid") @Expose val adValid: Boolean? = null, @SerializedName("code") @Expose val code: Long, @SerializedName("createDays") @Expose val createDays: Long? = null ) { data class Profile( @SerializedName("userId") @Expose val userId: Long? = null, @SerializedName("nickname") @Expose val nickname: String? = null, @SerializedName("avatarUrl") @Expose val avatarUrl: String? = null, @SerializedName("backgroundUrl") @Expose val backgroundUrl: String? = null, @SerializedName("playlistCount") @Expose val playlistCount: Long? = null // @SerializedName("followed") // @Expose // val followed: Boolean? = null, // @SerializedName("djStatus") // @Expose // val djStatus: Long? = null, // @SerializedName("detailDescription") // @Expose // val detailDescription: String? = null, // @SerializedName("avatarImgIdStr") // @Expose // val avatarImgIdStr: String? = null, // @SerializedName("backgroundImgIdStr") // @Expose // val backgroundImgIdStr: String? = null, // @SerializedName("description") // @Expose // val description: String? = null, // @SerializedName("accountStatus") // @Expose // val accountStatus: Long? = null, // @SerializedName("province") // @Expose // val province: Long? = null, // @SerializedName("defaultAvatar") // @Expose // val defaultAvatar: Boolean? = null, // @SerializedName("gender") // @Expose // val gender: Long? = null, // @SerializedName("birthday") // @Expose // val birthday: Long? = null, // @SerializedName("city") // @Expose // val city: Long? = null, // @SerializedName("mutual") // @Expose // val mutual: Boolean? = null, // @SerializedName("remarkName") // @Expose // val remarkName: Any? = null, // @SerializedName("experts") // @Expose // val experts: Experts? = null, // @SerializedName("avatarImgId") // @Expose // val avatarImgId: Long? = null, // @SerializedName("backgroundImgId") // @Expose // val backgroundImgId: Long? = null, // @SerializedName("expertTags") // @Expose // val expertTags: Any? = null, // @SerializedName("vipType") // @Expose // val vipType: Long? = null, // @SerializedName("userType") // @Expose // val userType: Long? = null, // @SerializedName("authStatus") // @Expose // val authStatus: Long? = null, // @SerializedName("signature") // @Expose // val signature: String? = null, // @SerializedName("authority") // @Expose // val authority: Long? = null, // @SerializedName("followeds") // @Expose // val followeds: Long? = null, // @SerializedName("follows") // @Expose // val follows: Long? = null, // @SerializedName("blacklist") // @Expose // val blacklist: Boolean? = null, // @SerializedName("eventCount") // @Expose // val eventCount: Long? = null, // @SerializedName("playlistBeSubscribedCount") // @Expose // val playlistBeSubscribedCount: Long? = null ) // data class Binding( // // @SerializedName("expiresIn") // @Expose // val expiresIn: Long? = null, // @SerializedName("refreshTime") // @Expose // val refreshTime: Long? = null, // @SerializedName("userId") // @Expose // val userId: Long? = null, // @SerializedName("tokenJsonStr") // @Expose // val tokenJsonStr: String? = null, // @SerializedName("url") // @Expose // val url: String? = null, // @SerializedName("expired") // @Expose // val expired: Boolean? = null, // @SerializedName("id") // @Expose // val id: Long? = null, // @SerializedName("type") // @Expose // val type: Long? = null // ) data class UserPoint( @SerializedName("userId") @Expose val userId: Long? = null, @SerializedName("balance") @Expose val balance: Long? = null, @SerializedName("updateTime") @Expose val updateTime: Long? = null, @SerializedName("version") @Expose val version: Long? = null, @SerializedName("status") @Expose val status: Long? = null, @SerializedName("blockBalance") @Expose val blockBalance: Long? = null ) }
app/src/main/java/tech/summerly/quiet/data/netease/result/UserDetailResultBean.kt
3605497354
package com.github.ajalt.clikt.samples.repo import com.github.ajalt.clikt.core.CliktCommand import com.github.ajalt.clikt.core.requireObject import com.github.ajalt.clikt.core.subcommands import com.github.ajalt.clikt.output.TermUi import com.github.ajalt.clikt.parameters.arguments.argument import com.github.ajalt.clikt.parameters.arguments.multiple import com.github.ajalt.clikt.parameters.arguments.optional import com.github.ajalt.clikt.parameters.options.* import com.github.ajalt.clikt.parameters.types.file import java.io.File data class RepoConfig(var home: String, val config: MutableMap<String, String>, var verbose: Boolean) class Repo : CliktCommand( help = """Repo is a command line tool that showcases how to build complex command line interfaces with Clikt. This tool is supposed to look like a distributed version control system to show how something like this can be structured.""") { init { versionOption("1.0") } val repoHome: String by option(help = "Changes the repository folder location.") .default(".repo") val config: List<Pair<String, String>> by option(help = "Overrides a config key/value pair.") .pair() .multiple() val verbose: Boolean by option("-v", "--verbose", help = "Enables verbose mode.") .flag() override fun run() { val repo = RepoConfig(repoHome, HashMap(), verbose) for ((k, v) in config) { repo.config[k] = v } currentContext.obj = repo } } class Clone : CliktCommand( help = """Clones a repository. This will clone the repository at SRC into the folder DEST. If DEST is not provided this will automatically use the last path component of SRC and create that folder.""") { val repo: RepoConfig by requireObject() val src: File by argument().file() val dest: File? by argument().file().optional() val shallow: Boolean by option(help = "Makes a checkout shallow or deep. Deep by default.") .flag("--deep") val rev: String by option("--rev", "-r", help = "Clone a specific revision instead of HEAD.") .default("HEAD") override fun run() { val destName = dest?.name ?: src.name echo("Cloning repo $src to ${File(destName).absolutePath}") repo.home = destName if (shallow) { echo("Making shallow checkout") } echo("Checking out revision $rev") } } class Delete : CliktCommand( help = """Deletes a repository. This will throw away the current repository.""") { val repo: RepoConfig by requireObject() override fun run() { echo("Destroying repo ${repo.home}") echo("Deleted!") } } class SetUser : CliktCommand( name = "setuser", help = """Sets the user credentials. This will override the current user config.""") { val repo: RepoConfig by requireObject() val username: String by option(help = "The developer's shown username.") .prompt() val email: String by option(help = "The developer's email address.") .prompt(text = "E-Mail") val password: String by option(help = "The login password.") .prompt(hideInput = true, requireConfirmation = true) override fun run() { repo.config["username"] = username repo.config["email"] = email repo.config["password"] = "*".repeat(password.length) echo("Changed credentials.") } } class Commit : CliktCommand( help = """Commits outstanding changes. Commit changes to the given files into the repository. You will need to "repo push" to push up your changes to other repositories. If a list of files is omitted, all changes reported by "repo status" will be committed.""") { val repo: RepoConfig by requireObject() val message: List<String> by option("--message", "-m", help = "The commit message. If provided multiple times " + "each argument gets converted into a new line.") .multiple() val files: List<File> by argument() .file() .multiple() override fun run() { val msg: String = if (message.isNotEmpty()) { message.joinToString("\n") } else { val marker = "# Files to be committed:" val text = buildString { append("\n\n").append(marker).append("\n#") for (file in files) { append("\n# ").append(file) } } val message = TermUi.editText(text) if (message == null) { echo("Aborted!") return } message.split(marker, limit = 2)[0].trim().apply { if (this.isEmpty()) { echo("Aborting commit due to empty commit message.") return } } } echo("Files to be commited: $files") echo("Commit message:") echo(msg) } } fun main(args: Array<String>) = Repo() .subcommands(Clone(), Delete(), SetUser(), Commit()) .main(args)
samples/repo/src/main/kotlin/com/github/ajalt/clikt/samples/repo/main.kt
4173055202
package ru.smarty.post_to_chrome import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication SpringBootApplication open public class PostToChromeApplication { companion object { public fun main(args: Array<String>) { SpringApplication.run(javaClass<PostToChromeApplication>(), *args) } } } fun main(args: Array<String>) = PostToChromeApplication.main(args)
src/main/kotlin/ru/smarty/post_to_chrome/PostToChromeApplication.kt
1063411059
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.example.text.styling import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.widget.TextView import com.android.example.text.styling.parser.Parser import com.android.example.text.styling.renderer.MarkdownBuilder /** * This sample demonstrates techniques for stying text; it is not intended to be a full markdown * parser. */ class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // This is a simple markdown parser, where: // Paragraphs starting with “> ” are transformed into quotes. Quotes can't contain // other markdown elements // Text enclosed in “`” will be transformed into inline code block // Lines starting with “+ ” or “* ” will be transformed into bullet points. Bullet // points can contain nested markdown elements, like code. val bulletPointColor = getColorCompat(R.color.colorAccent) val codeBackgroundColor = getColorCompat(R.color.code_background) val codeBlockTypeface = getFontCompat(R.font.inconsolata) MarkdownBuilder(bulletPointColor, codeBackgroundColor, codeBlockTypeface, Parser) .markdownToSpans(getString(R.string.display_text)) .run { findViewById<TextView>(R.id.styledText).text = this } } }
TextStyling/app/src/main/java/com/android/example/text/styling/MainActivity.kt
3059105748
/* * Copyright 2019 Web3 Labs LTD. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package org.web3j.quorum.core import org.assertj.core.api.Assertions.assertThat import org.junit.Assert.assertTrue import org.junit.Ignore import org.junit.Test import org.web3j.quorum.nodesT import org.web3j.quorum.upCheckTessera import org.web3j.quorum.PAYLOAD import org.web3j.quorum.tessera /** * Useful integration tests for verifying Enclave transactions. * * <p> * To use, start up 2 Tessera instances with valid config and * hardcode the IPC path to connect to in constellationIpcPath1 and constellationIpcPath2 * variables below. * * <p> */ @Ignore class TesseraServiceTest : Helper() { @Test fun testUpCheck() { val upCheckResponse = upCheckTessera.upCheck() assertTrue(upCheckResponse) } @Test fun testStoreRawRequest() { val payload = PAYLOAD val from = nodesT[0].publicKeys[0] val storeResponse = tessera[0].storeRawRequest(payload, from, emptyList()) val key = storeResponse.key assertThat(key).hasSize(88) } @Test @Throws(Exception::class) fun testNodes() { for (count in 0..0) { for (i in 0..0) { val sourceNode = nodesT[i] val destNode = nodesT[(i + 1) % nodesT.size] val keyFile = "keyfiles/key" + (i + 1).toString() testRawTransactionsWithGreeterContract(sourceNode, destNode, keyFile, tessera[i]) runPrivateHumanStandardTokenTest(sourceNode, destNode, keyFile, tessera[i]) } } } }
src/integration-test/kotlin/org/web3j/quorum/core/TesseraServiceTest.kt
1620911608
package org.owntracks.android.ui import androidx.test.espresso.Espresso import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText import com.adevinta.android.barista.interaction.BaristaClickInteractions.clickBack import com.adevinta.android.barista.interaction.BaristaClickInteractions.clickOn import com.adevinta.android.barista.interaction.BaristaSleepInteractions.sleep import org.hamcrest.Matchers.allOf private const val sleepMillis = 100L fun clickOnDrawerAndWait(text: Int) { Espresso.onView( allOf( withId(com.mikepenz.materialdrawer.R.id.material_drawer_name), withText(text) ) ).perform(click()) sleep(sleepMillis) } fun clickOnAndWait(int: Int) { clickOn(int) sleep(sleepMillis) } fun clickOnAndWait(str: String) { clickOn(str) sleep(sleepMillis) } fun clickBackAndWait() { clickBack() sleep(sleepMillis) }
project/app/src/androidTest/java/org/owntracks/android/ui/clickOnPreference.kt
3652680088
package org.owntracks.android.services import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Test import org.owntracks.android.model.messages.MessageLocation import org.owntracks.android.support.Parser import java.io.File import java.nio.file.Files import kotlin.random.Random class BlockingDequeueThatAlsoSometimesPersistsThingsToDiskMaybeTest { private val parser = Parser(null) private val random = Random(1) private fun generateRandomMessageLocation(): MessageLocation { return MessageLocation().apply { longitude = random.nextDouble() latitude = random.nextDouble() accuracy = random.nextInt() } } @Test fun `given an empty queue when polling then null is returned`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) assertNull(queue.poll()) } @Test fun `given an empty queue when adding an item the queue size is 1`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) queue.offer(generateRandomMessageLocation()) assertEquals(1, queue.size) } @Test fun `given a non-empty queue, when pushing an item to the head then that same item is returned on poll`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val headItem = generateRandomMessageLocation() queue.addFirst(headItem) assertEquals(6, queue.size) val retrieved = queue.poll() assertEquals(headItem, retrieved) } @Test fun `given a file path, when initializing the queue the size is correct`() { val dir = Files.createTempDirectory("").toFile() val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val newQueue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) assertEquals(5, newQueue.size) } @Test fun `given a file path where the head slot is occupied, when initializing the queue the size is correct`() { val dir = Files.createTempDirectory("").toFile() val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val headItem = generateRandomMessageLocation() queue.addFirst(headItem) val newQueue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) assertEquals(6, newQueue.size) val retrieved = queue.poll() assertEquals(headItem, retrieved) } @Test fun `given a non-empty queue, when taking an item to the head then the item is returned`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, Files.createTempDirectory("").toFile(), parser ) repeat(5) { queue.offer(generateRandomMessageLocation()) } val headItem = generateRandomMessageLocation() queue.addFirst(headItem) assertEquals(6, queue.size) val retrieved = queue.take() assertEquals(headItem, retrieved) } @Test fun `given a corrupt file, when initializing the queue then an empty queue is created`() { val dir = Files.createTempDirectory("").toFile() dir.resolve("messageQueue.dat").writeBytes(random.nextBytes(100)) val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, dir, parser ) assertEquals(0, queue.size) } @Test fun `given an un-writable location, when initializing a queue then an in-memory empty queue is created`() { val queue = BlockingDequeThatAlsoSometimesPersistsThingsToDiskMaybe( 10, File("/"), parser ) assertEquals(0, queue.size) } }
project/app/src/test/java/org/owntracks/android/services/BlockingDequeueThatAlsoSometimesPersistsThingsToDiskMaybeTest.kt
981572747
package net.perfectdreams.loritta.cinnamon.pudding.services import kotlinx.datetime.Instant import kotlinx.datetime.toJavaInstant import kotlinx.serialization.json.JsonObject import net.perfectdreams.loritta.common.commands.ApplicationCommandType import net.perfectdreams.loritta.common.components.ComponentType import net.perfectdreams.loritta.cinnamon.pudding.Pudding import net.perfectdreams.loritta.cinnamon.pudding.tables.ExecutedComponentsLog import net.perfectdreams.loritta.cinnamon.pudding.tables.transactions.ExecutedApplicationCommandsLog import org.jetbrains.exposed.sql.insertAndGetId import org.jetbrains.exposed.sql.select class ExecutedInteractionsLogService(private val pudding: Pudding) : Service(pudding) { suspend fun insertApplicationCommandLog( userId: Long, guildId: Long?, channelId: Long, sentAt: Instant, type: ApplicationCommandType, declaration: String, executor: String, options: JsonObject, success: Boolean, latency: Double, stacktrace: String? ): Long { return pudding.transaction { ExecutedApplicationCommandsLog.insertAndGetId { it[ExecutedApplicationCommandsLog.userId] = userId it[ExecutedApplicationCommandsLog.guildId] = guildId it[ExecutedApplicationCommandsLog.channelId] = channelId it[ExecutedApplicationCommandsLog.sentAt] = sentAt.toJavaInstant() it[ExecutedApplicationCommandsLog.type] = type it[ExecutedApplicationCommandsLog.declaration] = declaration it[ExecutedApplicationCommandsLog.executor] = executor it[ExecutedApplicationCommandsLog.options] = options.toString() it[ExecutedApplicationCommandsLog.success] = success it[ExecutedApplicationCommandsLog.latency] = latency it[ExecutedApplicationCommandsLog.stacktrace] = stacktrace } }.value } suspend fun insertComponentLog( userId: Long, guildId: Long?, channelId: Long, sentAt: Instant, type: ComponentType, declaration: String, executor: String, // options: JsonObject, success: Boolean, latency: Double, stacktrace: String? ): Long { return pudding.transaction { ExecutedComponentsLog.insertAndGetId { it[ExecutedComponentsLog.userId] = userId it[ExecutedComponentsLog.guildId] = guildId it[ExecutedComponentsLog.channelId] = channelId it[ExecutedComponentsLog.sentAt] = sentAt.toJavaInstant() it[ExecutedComponentsLog.type] = type it[ExecutedComponentsLog.declaration] = declaration it[ExecutedComponentsLog.executor] = executor // it[ExecutedApplicationCommandsLog.options] = options.toString() it[ExecutedComponentsLog.success] = success it[ExecutedComponentsLog.latency] = latency it[ExecutedComponentsLog.stacktrace] = stacktrace } }.value } suspend fun getExecutedApplicationCommands(since: Instant): Long { return pudding.transaction { return@transaction ExecutedApplicationCommandsLog.select { ExecutedApplicationCommandsLog.sentAt greaterEq since.toJavaInstant() }.count() } } suspend fun getUniqueUsersExecutedApplicationCommands(since: Instant): Long { return pudding.transaction { return@transaction ExecutedApplicationCommandsLog.slice(ExecutedApplicationCommandsLog.userId).select { ExecutedApplicationCommandsLog.sentAt greaterEq since.toJavaInstant() }.groupBy(ExecutedApplicationCommandsLog.userId).count() } } }
pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/services/ExecutedInteractionsLogService.kt
3406530921
package com.androidvip.hebf.widgets import android.app.ActivityManager import android.content.Context import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.lifecycle.lifecycleScope import com.androidvip.hebf.R import com.androidvip.hebf.ui.base.BaseActivity import com.androidvip.hebf.utils.Prefs import com.androidvip.hebf.utils.RootUtils import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.topjohnwu.superuser.Shell import kotlinx.coroutines.launch //TODO class WidgetLMK : BaseActivity() { private companion object { private var MODERADO = "12288,16384,20480,25088,29696,34304" private var MULTITASK = "3072,7168,11264,15360,19456,23552" private var FREE_RAM = "6144,14336,24576,32768,40960,49152" private var GAME = "4096,8192,16384,32768,49152,65536" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val profileNames = resources.getStringArray(R.array.lmk_profiles) val am = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager? val memoryInfo = ActivityManager.MemoryInfo() lifecycleScope.launch(workerContext) { val isRooted = Shell.rootAccess() am?.getMemoryInfo(memoryInfo) val mem = memoryInfo.totalMem / 1048567 when { mem <= 512 -> { MODERADO = "6144,8192,10240,12288,14848,17408" MULTITASK = "1536,3584,5632,7680,9728,11776" FREE_RAM = "3072,7168,12288,16384,20480,24576" GAME = "2048,4096,8192,16384,24576,32768" } mem <= 768 -> { MODERADO = "9216,12288,15360,18944,22272,25600" MULTITASK = "2048,5120,8192,11264,14336,17920" FREE_RAM = "4608,10752,18432,24576,30720,36864" GAME = "3072,6144,12288,24576,36864,49152" } mem <= 1024 -> { MODERADO = "12288,16384,20480,25088,29696,34304" MULTITASK = "3072,7168,11264,15360,19456,23552" FREE_RAM = "6144,14336,24576,32768,40960,49152" GAME = "4096,8192,16384,32768,49152,65536" } mem <= 2048 -> { MODERADO = "18432,24576,30720,37632,44544,51456" MULTITASK = "4608,10752,16896,23040,29184,35328" FREE_RAM = "9216,21504,26624,36864,61440,73728" GAME = "6144,12288,24576,49152,73728,98304" } } runSafeOnUiThread { if (isRooted) { val builder = MaterialAlertDialogBuilder(this@WidgetLMK) builder.setTitle(getString(R.string.profiles)) .setSingleChoiceItems(profileNames, 1) { _, _ -> } .setPositiveButton(android.R.string.ok) { dialog, _ -> val position = (dialog as AlertDialog).listView.checkedItemPosition val prefs = Prefs(applicationContext) when (position) { 0 -> { prefs.putInt("PerfisLMK", 0) finish() } 1 -> { setProfiles(MODERADO) prefs.putInt("PerfisLMK", 1) } 2 -> { setProfiles(MULTITASK) prefs.putInt("PerfisLMK", 2) } 3 -> { setProfiles(FREE_RAM) prefs.putInt("PerfisLMK", 3) } 4 -> { setProfiles(GAME) prefs.putInt("PerfisLMK", 4) } } } .setOnDismissListener { finish() } .setNegativeButton(android.R.string.cancel) { _, _ -> finish() } builder.show() } else { Toast.makeText(this@WidgetLMK, "Only for rooted users!", Toast.LENGTH_LONG).show() finish() } } }.start() } private fun setProfiles(profile: String) { RootUtils.executeAsync("echo '$profile' > /sys/module/lowmemorykiller/parameters/minfree") Toast.makeText(this@WidgetLMK, getString(R.string.profiles_set), Toast.LENGTH_SHORT).show() } }
app/src/main/java/com/androidvip/hebf/widgets/WidgetLMK.kt
2867498557
operator fun MyDate.rangeTo(other: MyDate) = DateRange(this, other) class DateRange(override val start: MyDate, override val endInclusive: MyDate): ClosedRange<MyDate> fun checkInRange(date: MyDate, first: MyDate, last: MyDate): Boolean { return date in first..last }
lesson2/task3/src/Task.kt
1064400068
/* * Copyright (C) 2017 John Leacox * Copyright (C) 2017 Brian van de Boogaard * * 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 dev.misfitlabs.kotlinguice4 import com.google.inject.AbstractModule import com.google.inject.Binder import com.google.inject.MembersInjector import com.google.inject.Provider import com.google.inject.Scope import dev.misfitlabs.kotlinguice4.binder.KotlinAnnotatedBindingBuilder import dev.misfitlabs.kotlinguice4.binder.KotlinAnnotatedElementBuilder import dev.misfitlabs.kotlinguice4.binder.KotlinLinkedBindingBuilder import dev.misfitlabs.kotlinguice4.binder.KotlinScopedBindingBuilder import dev.misfitlabs.kotlinguice4.internal.KotlinBindingBuilder import kotlin.reflect.KProperty /** * An extension of [AbstractModule] that enhances the binding DSL to allow binding using reified * type parameters. * * By using this class instead of [AbstractModule] you can replace: * ``` * class MyModule : AbstractModule() { * override fun configure() { * bind(Service::class.java).to(ServiceImpl::class.java).`in`(Singleton::class.java) * bind(object : TypeLiteral<PaymentService<CreditCard>>() {}) * .to(CreditCardPaymentService::class.java) * } * } * ``` * with * ``` * class MyModule : KotlinModule() { * override fun configure() { * bind<Service>().to<ServiceImpl>().`in`<Singleton>() * bind<PaymentService<CreditCard>>().to<CreditCardPaymentService>() * } * } * ``` * * @see KotlinBinder * @see AbstractModule * @author John Leacox * @since 1.0 */ abstract class KotlinModule : AbstractModule() { private class KotlinLazyBinder(private val delegateBinder: () -> Binder) { private val classesToSkip = arrayOf( KotlinAnnotatedBindingBuilder::class.java, KotlinAnnotatedElementBuilder::class.java, KotlinBinder::class.java, KotlinBindingBuilder::class.java, KotlinLinkedBindingBuilder::class.java, KotlinScopedBindingBuilder::class.java ) var lazyBinder = lazyInit() var currentBinder: Binder? = null operator fun getValue(thisRef: Any?, property: KProperty<*>): KotlinBinder { if (currentBinder != delegateBinder()) { currentBinder = delegateBinder() lazyBinder = lazyInit() } return lazyBinder.value } private fun lazyInit() = lazy { KotlinBinder(delegateBinder().skipSources(*classesToSkip)) } } /** Gets direct access to the underlying [KotlinBinder]. */ protected val kotlinBinder: KotlinBinder by KotlinLazyBinder { this.binder() } /** @see KotlinBinder.bindScope */ protected inline fun <reified TAnn : Annotation> bindScope(scope: Scope) { kotlinBinder.bindScope<TAnn>(scope) } /** @see KotlinBinder.bind */ protected inline fun <reified T> bind(): KotlinAnnotatedBindingBuilder<T> { return kotlinBinder.bind<T>() } /** @see KotlinBinder.requestStaticInjection */ protected inline fun <reified T> requestStaticInjection() { kotlinBinder.requestStaticInjection<T>() } /** @see AbstractModule.requireBinding */ protected inline fun <reified T> requireBinding() { requireBinding(key<T>()) } /** @see KotlinBinder.getProvider */ protected inline fun <reified T> getProvider(): Provider<T> { return kotlinBinder.getProvider<T>() } /** @see KotlinBinder.getMembersInjector */ protected inline fun <reified T> getMembersInjector(): MembersInjector<T> { return kotlinBinder.getMembersInjector<T>() } }
kotlin-guice/src/main/kotlin/dev/misfitlabs/kotlinguice4/KotlinModule.kt
1875747797
package org.openbakery.assemble import org.openbakery.CommandRunner import org.openbakery.bundle.ApplicationBundle import org.openbakery.tools.CommandLineTools import org.openbakery.util.FileHelper import org.openbakery.xcode.Type import org.slf4j.LoggerFactory import java.io.File /** * This class creates an .xcarchive for the application bundle * Note: The implementation is not complete. Several methods must be migrated from the XcodeBuildArchiveTask to this class * * The idea is that this class just creates the xcarchive, but has no dependency and knowledge about gradle */ class Archive(applicationBundleFile: File, archiveName: String, type: Type, simulator: Boolean, tools: CommandLineTools, watchApplicationBundleFile: File? = null) { private var applications = "Applications" private var products = "Products" companion object { val logger = LoggerFactory.getLogger("AppPackage")!! } private val applicationBundleFile: File = applicationBundleFile private val watchApplicationBundleFile: File? = watchApplicationBundleFile private val tools: CommandLineTools = tools private val fileHelper: FileHelper = FileHelper(CommandRunner()) private val archiveName: String = archiveName private val type: Type = type private val simulator: Boolean = simulator fun create(destinationDirectory: File) : ApplicationBundle { return this.create(destinationDirectory, false) } fun create(destinationDirectory: File, bitcodeEnabled: Boolean) : ApplicationBundle { val archiveDirectory = getArchiveDirectory(destinationDirectory) val applicationDirectory = copyApplication(archiveDirectory) copyOnDemandResources(archiveDirectory) copyDsyms(archiveDirectory) val applicationBundle = ApplicationBundle(applicationDirectory, type, simulator, tools.plistHelper) if (type == Type.iOS) { copyFrameworks(applicationBundle, archiveDirectory, applicationBundle.platformName, bitcodeEnabled) } if (applicationBundle.watchAppBundle != null) { copyFrameworks(applicationBundle.watchAppBundle, archiveDirectory, applicationBundle.watchAppBundle.platformName, true) } return applicationBundle } private fun copyApplication(archiveDirectory: File) : File { val applicationDirectory = File(archiveDirectory, "$products/$applications") applicationDirectory.mkdirs() fileHelper.copyTo(applicationBundleFile, applicationDirectory) return File(applicationDirectory, applicationBundleFile.name) } private fun copyOnDemandResources(archiveDirectory: File) { val onDemandResources = File(applicationBundleFile.parent, "OnDemandResources") if (onDemandResources.exists()) { val destination = File(archiveDirectory, products) fileHelper.copyTo(onDemandResources, destination) } } private fun copyDsyms(archiveDirectory: File) { val dSymDirectory = File(archiveDirectory, "dSYMs") dSymDirectory.mkdirs() copyDsyms(applicationBundleFile.parentFile, dSymDirectory) if (watchApplicationBundleFile != null) { copyDsyms(watchApplicationBundleFile, dSymDirectory) } } private fun copyDsyms(archiveDirectory: File, dSymDirectory: File) { archiveDirectory.walk().forEach { if (it.isDirectory && it.extension.toLowerCase() == "dsym") { fileHelper.copyTo(it, dSymDirectory) } } } private fun getArchiveDirectory(destinationDirectory: File): File { val archiveDirectory = File(destinationDirectory, this.archiveName + ".xcarchive") archiveDirectory.mkdirs() return archiveDirectory } private fun copyFrameworks(applicationBundle: ApplicationBundle, archiveDirectory: File, platformName: String, bitcodeEnabled: Boolean) { if (!applicationBundle.frameworksPath.exists()) { logger.debug("framework path does not exists, so we are done") return } var libNames = ArrayList<String>() applicationBundle.frameworksPath.walk().forEach { if (it.extension.toLowerCase() == "dylib") { libNames.add(it.name) } } logger.debug("swift libraries to add: {}", libNames) val swiftLibraryDirectories = getSwiftLibraryDirectories(platformName) libNames.forEach { libraryName -> val library = getSwiftLibrary(swiftLibraryDirectories, libraryName) if (library != null) { val swiftSupportDirectory = getSwiftSupportDirectory(archiveDirectory, platformName) fileHelper.copyTo(library, swiftSupportDirectory) if (!bitcodeEnabled) { val destination = File(applicationBundle.frameworksPath, library.name) val commandList = listOf("/usr/bin/xcrun", "bitcode_strip", library.absolutePath, "-r", "-o", destination.absolutePath) tools.lipo.xcodebuild.commandRunner.run(commandList) } } } } private fun getSwiftLibrary(libraryDirectories: List<File>, name: String) : File? { for (directory in libraryDirectories) { val result = getSwiftLibrary(directory, name) if (result != null) { return result } } return null } private fun getSwiftLibrary(libraryDirectory: File, name: String) : File?{ val result = File(libraryDirectory, name) if (result.exists()) { return result } return null } private fun getSwiftLibraryDirectories(platformName: String) : List<File> { var result = ArrayList<File>() val baseDirectory = File(tools.lipo.xcodebuild.toolchainDirectory, "usr/lib/") baseDirectory.listFiles().forEach { if (it.isDirectory && it.name.startsWith("swift")) { val platformDirectory = File(it, platformName) if (platformDirectory.exists()) { result.add(platformDirectory) } } } return result } private fun getSwiftSupportDirectory(archiveDirectory: File, platformName: String) : File { val swiftSupportDirectory = File(archiveDirectory, "SwiftSupport/$platformName") if (!swiftSupportDirectory.exists()) { swiftSupportDirectory.mkdirs() } return swiftSupportDirectory } }
libxcodetools/src/main/kotlin/org/openbakery/assemble/Archive.kt
297716113
package icurves.algorithm import icurves.algorithm.astar.AStarGrid import icurves.algorithm.astar.NodeState import icurves.diagram.Zone import icurves.guifx.SettingsController import icurves.util.Log import javafx.scene.paint.Color import javafx.scene.shape.Circle import javafx.scene.shape.Polyline import javafx.scene.shape.Rectangle import javafx.scene.shape.Shape import javafx.scene.text.Font import javafx.scene.text.Text import math.geom2d.Point2D import math.geom2d.polygon.Polygons2D import math.geom2d.polygon.SimplePolygon2D /** * * * @author Almas Baimagambetov ([email protected]) */ class AStarEdgeRouter : EdgeRouter { private val TILES = 50 override fun route(zone1: Zone, zone2: Zone): Polyline { var union = Polygons2D.union(zone1.getPolygonShape(), zone2.getPolygonShape()) val bbox = union.boundingBox() //SettingsController.debugShapes.add(Rectangle(bbox.minX, bbox.minY, bbox.width, bbox.height)) val TILE_SIZE = (Math.min(bbox.width, bbox.height) / TILES).toInt() val grid = AStarGrid(bbox.width.toInt() / TILE_SIZE, bbox.height.toInt() / TILE_SIZE) println("Grid size: ${grid.width}x${grid.height} Tile size: $TILE_SIZE") println() println(zone1.getPolygonShape().vertices()) println(zone2.getPolygonShape().vertices()) // keep only distinct vertices union = SimplePolygon2D(union.vertices().map { P(it.x().toInt(), it.y().toInt()) }.toSet().map { Point2D(it.x.toDouble(), it.y.toDouble()) }) println(union.vertices()) println() val boundary = union.boundary() // signed, so - if inside val maxDistance: Double = try { -Math.min(boundary.signedDistance(zone1.center.x, zone1.center.y), boundary.signedDistance(zone2.center.x, zone2.center.y)) } catch (e: Exception) { 1000.0 } for (y in 0 until grid.height) { for (x in 0 until grid.width) { val tileCenter = Point2D(x.toDouble() * TILE_SIZE + TILE_SIZE / 2 + bbox.minX, y.toDouble() * TILE_SIZE + TILE_SIZE / 2 + bbox.minY) val node = grid.getNode(x, y) try { if (union.contains(tileCenter)) { val dist = -boundary.signedDistance(tileCenter).toInt() if (dist < TILE_SIZE) { node.state = NodeState.NOT_WALKABLE continue } node.state = NodeState.WALKABLE //node.gCost = 100000 - dist * 1000 //node.gCost = ((2 - dist / maxDistance) * 2500).toInt() node.gCost = ((1 - dist / maxDistance) * 5000).toInt() if (node.gCost < 0) { //println("Distance: $dist, gCost: ${node.gCost}") node.gCost = 0 } // val text = Text("${node.fCost}") // text.translateX = tileCenter.x() // text.translateY = tileCenter.y() // text.font = Font.font(36.0) // // SettingsController.debugNodes.add(text) } else { node.state = NodeState.NOT_WALKABLE } } catch (e: Exception) { Log.e(e) node.state = NodeState.NOT_WALKABLE } // if (node.state == NodeState.WALKABLE) { // val circle = Circle(tileCenter.x(), tileCenter.y(), 15.0, Color.GREEN) // //SettingsController.debugNodes.add(circle) // } else { // val circle = Circle(tileCenter.x(), tileCenter.y(), 15.0, Color.RED) // //SettingsController.debugNodes.add(circle) // } } } val startX = (zone1.center.x - bbox.minX) / TILE_SIZE val startY = (zone1.center.y - bbox.minY) / TILE_SIZE val targetX = (zone2.center.x - bbox.minX) / TILE_SIZE val targetY = (zone2.center.y - bbox.minY) / TILE_SIZE println("$startX,$startY - $targetX,$targetY") val path = grid.getPath(startX.toInt(), startY.toInt(), targetX.toInt(), targetY.toInt()) if (path.isEmpty()) { println("Edge routing A* not found") } // so that start and end vertices are exactly the same as requested val points = arrayListOf<Double>(zone1.center.x, zone1.center.y) points.addAll(path.map { arrayListOf(it.x, it.y) } .flatten() .mapIndexed { index, value -> value.toDouble() * TILE_SIZE + TILE_SIZE / 2 + (if (index % 2 == 0) bbox.minX else bbox.minY) } .dropLast(2) ) // so that start and end vertices are exactly the same as requested points.add(zone2.center.x) points.add(zone2.center.y) return Polyline(*points.toDoubleArray()) } data class P(val x: Int, val y: Int) { } }
src/main/kotlin/icurves/algorithm/AStarEdgeRouter.kt
3995598001
package se.ansman.kotshi @JsonSerializable data class ClassWithLambda(val block: (String) -> Boolean)
tests/src/main/kotlin/se/ansman/kotshi/ClassWithLambda.kt
1419023917
package com.sksamuel.kotest.property.arbitrary import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import io.kotest.property.RandomSource import io.kotest.property.arbitrary.Arb import io.kotest.property.arbitrary.multiples class MultipleTest : FunSpec({ test("multiples of k") { Arb.multiples(3, 99999).generate(RandomSource.Default).take(100).forEach { it.value % 3 shouldBe 0 } } })
kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/arbitrary/MultipleTest.kt
838724243
package com.makingiants.today.api.error_handling.exceptions.simple import com.makingiants.today.api.error_handling.ApiException class BadRequestApiException (text: String?, name: String?, cause: Throwable) : ApiException(text, name, cause)
api/src/main/kotlin/com/makingiants/today/api/error_handling/exceptions/simple/BadRequestApiException.kt
2894047321
package com.nlefler.glucloser.a.models.json import java.util.* /** * Created by nathan on 1/31/16. */ public data class BloodSugarJson( val primaryId: String, val value: Int, val date: Date ) { }
Glucloser/app/src/main/kotlin/com/nlefler/glucloser/a/models/json/BloodSugarJson.kt
1916173895
// Copyright 2020 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.gcloud.spanner.testing import java.net.ServerSocket import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.coroutines.yield import org.jetbrains.annotations.BlockingExecutor import org.wfanet.measurement.common.getRuntimePath private const val EMULATOR_HOSTNAME = "localhost" private const val INVALID_HOST_MESSAGE = "emulator host must be of the form $EMULATOR_HOSTNAME:<port>" /** * Wrapper for Cloud Spanner Emulator binary. * * @param port TCP port that the emulator should listen on, or 0 to allocate a port automatically * @param coroutineContext Context for operations that may block */ class SpannerEmulator( private val port: Int = 0, private val coroutineContext: @BlockingExecutor CoroutineContext = Dispatchers.IO ) : AutoCloseable { private val startMutex = Mutex() @Volatile private lateinit var emulator: Process val started: Boolean get() = this::emulator.isInitialized @Volatile private var _emulatorHost: String? = null val emulatorHost: String get() { check(started) { "Emulator not started" } return _emulatorHost!! } /** * Starts the emulator process if it has not already been started. * * This suspends until the emulator is ready. * * @returns the emulator host */ suspend fun start(): String { if (started) { return emulatorHost } return startMutex.withLock { // Double-checked locking. if (started) { return@withLock emulatorHost } return withContext(coroutineContext) { // Open a socket on `port`. This should reduce the likelihood that the port // is in use. Additionally, this will allocate a port if `port` is 0. val localPort = ServerSocket(port).use { it.localPort } val emulatorHost = "$EMULATOR_HOSTNAME:$localPort" _emulatorHost = emulatorHost emulator = ProcessBuilder(emulatorPath.toString(), "--host_port=$emulatorHost") .redirectError(ProcessBuilder.Redirect.INHERIT) .start() /** Suffix of line of emulator output that will tell us that it's ready. */ val readyLineSuffix = "Server address: $emulatorHost" emulator.inputStream.use { input -> input.bufferedReader().use { reader -> do { yield() check(emulator.isAlive) { "Emulator stopped unexpectedly" } val line = reader.readLine() } while (!line.endsWith(readyLineSuffix)) } } emulatorHost } } } override fun close() { if (started) { emulator.destroy() } } fun buildJdbcConnectionString(project: String, instance: String, database: String): String = buildJdbcConnectionString(emulatorHost, project, instance, database) companion object { private val emulatorPath: Path init { val runfilesRelativePath = Paths.get("cloud_spanner_emulator", "emulator") val runtimePath = getRuntimePath(runfilesRelativePath) check(runtimePath != null && Files.exists(runtimePath)) { "$runfilesRelativePath not found in runfiles" } check(Files.isExecutable(runtimePath)) { "$runtimePath is not executable" } emulatorPath = runtimePath } fun withHost(emulatorHost: String): SpannerEmulator { val lazyMessage: () -> String = { INVALID_HOST_MESSAGE } val parts = emulatorHost.split(':', limit = 2) require(parts.size == 2 && parts[0] == EMULATOR_HOSTNAME, lazyMessage) val port = requireNotNull(parts[1].toIntOrNull(), lazyMessage) return SpannerEmulator(port) } fun buildJdbcConnectionString( emulatorHost: String, project: String, instance: String, database: String ): String { return "jdbc:cloudspanner://$emulatorHost/projects/$project/instances/$instance/databases/" + "$database;usePlainText=true;autoConfigEmulator=true" } } }
src/main/kotlin/org/wfanet/measurement/gcloud/spanner/testing/SpannerEmulator.kt
1235028498
package github.nisrulz.example.usingroomorm import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query @Dao interface PersonDao { // Adds a person to the database @Insert fun insertAll(vararg people: Person) // Removes a person from the database @Delete fun delete(person: Person) // Gets all people in the database @get:Query("SELECT * FROM person") val allPeople: List<Person?>? // Gets all people in the database with a address @Query("SELECT * FROM person WHERE address LIKE :address") fun getAllPeopleWithAddress(address: String): List<Person?>? }
UsingRoomORM/app/src/main/java/github/nisrulz/example/usingroomorm/PersonDao.kt
668004588
package reactivecircus.flowbinding.android.widget import android.widget.RatingBar import androidx.annotation.CheckResult import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.conflate import reactivecircus.flowbinding.common.InitialValueFlow import reactivecircus.flowbinding.common.asInitialValueFlow import reactivecircus.flowbinding.common.checkMainThread /** * Create a [InitialValueFlow] of rating changes on the [RatingBar] instance * where the value emitted is the current rating. * * Note: Created flow keeps a strong reference to the [RatingBar] instance * until the coroutine that launched the flow collector is cancelled. * * Example of usage: * * ``` * ratingBar.ratingChanges() * .onEach { rating -> * // handle rating * } * .launchIn(uiScope) * ``` */ @CheckResult @OptIn(ExperimentalCoroutinesApi::class) public fun RatingBar.ratingChanges(): InitialValueFlow<Float> = callbackFlow { checkMainThread() val listener = RatingBar.OnRatingBarChangeListener { _, rating, _ -> trySend(rating) } onRatingBarChangeListener = listener awaitClose { onRatingBarChangeListener = null } } .conflate() .asInitialValueFlow { rating }
flowbinding-android/src/main/java/reactivecircus/flowbinding/android/widget/RatingBarRatingChangeFlow.kt
81252155
package org.gradle.kotlin.dsl import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.doAnswer import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.eq import com.nhaarman.mockito_kotlin.inOrder import com.nhaarman.mockito_kotlin.KStubbing import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import com.nhaarman.mockito_kotlin.whenever import org.gradle.api.Action import org.gradle.api.Project import org.gradle.api.artifacts.ClientModule import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.DependencyConstraint import org.gradle.api.artifacts.ExternalModuleDependency import org.gradle.api.artifacts.ProjectDependency import org.gradle.api.artifacts.dsl.DependencyConstraintHandler import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.api.plugins.ExtensionAware import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.CoreMatchers.sameInstance import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class DependencyHandlerExtensionsTest { @Test fun `given group, name, version, configuration, classifier and ext, 'create' extension will build corresponding map`() { val expectedModuleMap = mapOf( "group" to "g", "name" to "n", "version" to "v", "configuration" to "cfg", "classifier" to "cls", "ext" to "x") val dependencies = newDependencyHandlerMock() val dependency: ExternalModuleDependency = mock() whenever(dependencies.create(expectedModuleMap)).thenReturn(dependency) assertThat( dependencies.create( group = "g", name = "n", version = "v", configuration = "cfg", classifier = "cls", ext = "x"), sameInstance(dependency)) } @Test fun `given group and module, 'exclude' extension will build corresponding map`() { val dependencyHandlerMock = newDependencyHandlerMock() val dependencies = DependencyHandlerScope.of(dependencyHandlerMock) val dependency: ExternalModuleDependency = mock() val events = mutableListOf<String>() whenever(dependencyHandlerMock.create("dependency")).then { events.add("created") dependency } whenever(dependency.exclude(mapOf("group" to "g", "module" to "m"))).then { events.add("configured") dependency } whenever(dependencyHandlerMock.add("configuration", dependency)).then { events.add("added") dependency } dependencies { "configuration"("dependency") { val configuredDependency = exclude(group = "g", module = "m") assertThat( configuredDependency, sameInstance(dependency)) } } assertThat( events, equalTo(listOf("created", "configured", "added"))) } @Test fun `given path and configuration, 'project' extension will build corresponding map`() { val dependencyHandlerMock = newDependencyHandlerMock() val dependencies = DependencyHandlerScope.of(dependencyHandlerMock) val dependency: ProjectDependency = mock() val events = mutableListOf<String>() val expectedProjectMap = mapOf("path" to ":project", "configuration" to "default") whenever(dependencyHandlerMock.project(expectedProjectMap)).then { events.add("created") dependency } whenever(dependencyHandlerMock.add("configuration", dependency)).then { events.add("added") dependency } val project: Project = mock() whenever(dependency.dependencyProject).thenReturn(project) dependencies { "configuration"(project(path = ":project", configuration = "default")) { events.add("configured") assertThat( dependencyProject, sameInstance(project)) } } assertThat( events, equalTo(listOf("created", "configured", "added"))) } @Test fun `given configuration name and dependency notation, it will add the dependency`() { val dependencyHandler = newDependencyHandlerMock { on { add(any(), any()) } doReturn mock<Dependency>() } val dependencies = DependencyHandlerScope.of(dependencyHandler) dependencies { "configuration"("notation") } verify(dependencyHandler).add("configuration", "notation") } @Test fun `given configuration and dependency notation, it will add the dependency to the named configuration`() { val dependencyHandler = newDependencyHandlerMock { on { add(any(), any()) } doReturn mock<Dependency>() } val configuration = mock<Configuration> { on { name } doReturn "c" } val dependencies = DependencyHandlerScope.of(dependencyHandler) dependencies { configuration("notation") } verify(dependencyHandler).add("c", "notation") } @Test fun `client module configuration`() { val clientModule = mock<ClientModule> { on { setTransitive(any()) }.thenAnswer { it.mock } } val commonsCliDependency = mock<ExternalModuleDependency>(name = "commonsCliDependency") val antModule = mock<ClientModule>(name = "antModule") val antLauncherDependency = mock<ExternalModuleDependency>(name = "antLauncherDependency") val antJUnitDependency = mock<ExternalModuleDependency>(name = "antJUnitDependency") val dependencies = newDependencyHandlerMock { on { module("org.codehaus.groovy:groovy:2.4.7") } doReturn clientModule on { create("commons-cli:commons-cli:1.0") } doReturn commonsCliDependency val antModuleNotation = mapOf("group" to "org.apache.ant", "name" to "ant", "version" to "1.9.6") on { module(antModuleNotation) } doReturn antModule on { create("org.apache.ant:ant-launcher:1.9.6@jar") } doReturn antLauncherDependency on { create("org.apache.ant:ant-junit:1.9.6") } doReturn antJUnitDependency on { add("runtime", clientModule) } doReturn clientModule } dependencies.apply { val groovy = module("org.codehaus.groovy:groovy:2.4.7") { // Configures the module itself isTransitive = false dependency("commons-cli:commons-cli:1.0") { // Configures the external module dependency isTransitive = false } module(group = "org.apache.ant", name = "ant", version = "1.9.6") { // Configures the inner module dependencies dependencies( "org.apache.ant:ant-launcher:1.9.6@jar", "org.apache.ant:ant-junit:1.9.6") } } add("runtime", groovy) } verify(clientModule).isTransitive = false verify(clientModule).addDependency(commonsCliDependency) verify(clientModule).addDependency(antModule) verify(commonsCliDependency).isTransitive = false verify(antModule).addDependency(antLauncherDependency) verify(antModule).addDependency(antJUnitDependency) } @Test fun `dependency on configuration using string notation doesn't cause IllegalStateException`() { val dependencyHandler = newDependencyHandlerMock { on { add(any(), any()) }.thenReturn(null) } val baseConfig = mock<Configuration>() val dependencies = DependencyHandlerScope.of(dependencyHandler) dependencies { "configuration"(baseConfig) } verify(dependencyHandler).add("configuration", baseConfig) } @Test fun `dependency on configuration doesn't cause IllegalStateException`() { val dependencyHandler = newDependencyHandlerMock { on { add(any(), any()) }.thenReturn(null) } val configuration = mock<Configuration> { on { name } doReturn "configuration" } val baseConfig = mock<Configuration>() val dependencies = DependencyHandlerScope.of(dependencyHandler) dependencies { configuration(baseConfig) } verify(dependencyHandler).add("configuration", baseConfig) } @Test fun `can declare dependency constraints`() { val constraint = mock<DependencyConstraint>() val constraintHandler = mock<DependencyConstraintHandler> { on { add(any(), any()) } doReturn constraint on { add(any(), any(), any()) } doReturn constraint } val dependenciesHandler = newDependencyHandlerMock { on { constraints } doReturn constraintHandler on { constraints(any()) } doAnswer { (it.getArgument(0) as Action<DependencyConstraintHandler>).execute(constraintHandler) } } val dependencies = DependencyHandlerScope.of(dependenciesHandler) // using the api dependencies { constraints { it.add("api", "some:thing:1.0") it.add("api", "other:thing") { it.version { it.strictly("1.0") } } } } // using generated accessors fun DependencyConstraintHandler.api(dependencyConstraintNotation: Any): DependencyConstraint? = add("api", dependencyConstraintNotation) fun DependencyConstraintHandler.api(dependencyConstraintNotation: Any, configuration: DependencyConstraint.() -> Unit): DependencyConstraint? = add("api", dependencyConstraintNotation, configuration) dependencies { constraints { it.api("some:thing:1.0") it.api("other:thing") { version { it.strictly("1.0") } } } } // using the string invoke syntax (requires extra parentheses around the `constraints` property) dependencies { (constraints) { "api"("some:thing:1.0") "api"("other:thing") { version { it.strictly("1.0") } } } } inOrder(constraintHandler) { repeat(3) { verify(constraintHandler).add(eq("api"), eq("some:thing:1.0")) verify(constraintHandler).add(eq("api"), eq("other:thing"), any()) } verifyNoMoreInteractions() } } } fun newDependencyHandlerMock(stubbing: KStubbing<DependencyHandler>.(DependencyHandler) -> Unit = {}) = mock<DependencyHandler>(extraInterfaces = arrayOf(ExtensionAware::class), stubbing = stubbing)
subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/DependencyHandlerExtensionsTest.kt
3637027128
package screenswitchersample.core.view import android.view.View class DebouncingClickListener(private val clickListener: (View) -> Unit) : View.OnClickListener { override fun onClick(v: View) { if (denyClick) { return } // This order matters. The post needs to happen before running the click listener to ensure resetting deny click // happens (due to the view being attached). denyClick = true v.post { denyClick = false } clickListener(v) } companion object { private var denyClick = false } }
sample-core/src/main/java/screenswitchersample/core/view/DebouncingClickListener.kt
1261857674
package app.lawnchair.views import android.annotation.SuppressLint import android.appwidget.AppWidgetProviderInfo import android.content.Context import android.util.Log import android.view.ContextThemeWrapper import android.view.Gravity import android.view.View import android.view.ViewGroup.LayoutParams.WRAP_CONTENT import android.widget.FrameLayout import androidx.annotation.UiThread import androidx.annotation.WorkerThread import com.android.launcher3.InvariantDeviceProfile import com.android.launcher3.LauncherAppState import com.android.launcher3.LauncherSettings.Favorites.* import com.android.launcher3.R import com.android.launcher3.graphics.LauncherPreviewRenderer import com.android.launcher3.model.BgDataModel import com.android.launcher3.model.GridSizeMigrationTaskV2 import com.android.launcher3.model.LoaderTask import com.android.launcher3.model.ModelDelegate import com.android.launcher3.util.ComponentKey import com.android.launcher3.util.Executors.MAIN_EXECUTOR import com.android.launcher3.util.Executors.MODEL_EXECUTOR import com.android.launcher3.util.RunnableList import com.android.launcher3.util.Themes import com.google.android.material.progressindicator.CircularProgressIndicator import kotlin.math.min @SuppressLint("ViewConstructor") class LauncherPreviewView( context: Context, private val idp: InvariantDeviceProfile, private val dummySmartspace: Boolean = false, private val dummyInsets: Boolean = false, private val appContext: Context = context.applicationContext ) : FrameLayout(context) { private val onReadyCallbacks = RunnableList() private val onDestroyCallbacks = RunnableList() private var destroyed = false private var rendererView: View? = null private val spinner = CircularProgressIndicator(context).apply { val themedContext = ContextThemeWrapper(context, Themes.getActivityThemeRes(context)) val textColor = Themes.getAttrColor(themedContext, R.attr.workspaceTextColor) isIndeterminate = true setIndicatorColor(textColor) trackCornerRadius = 1000 alpha = 0f animate() .alpha(1f) .withLayer() .setStartDelay(100) .setDuration(300) .start() } init { addView(spinner, LayoutParams(WRAP_CONTENT, WRAP_CONTENT).apply { gravity = Gravity.CENTER }) loadAsync() } fun addOnReadyCallback(runnable: Runnable) { onReadyCallbacks.add(runnable) } @UiThread fun destroy() { destroyed = true onDestroyCallbacks.executeAllAndDestroy() removeAllViews() } private fun loadAsync() { MODEL_EXECUTOR.execute(this::loadModelData) } @WorkerThread private fun loadModelData() { val migrated = doGridMigrationIfNecessary() val inflationContext = ContextThemeWrapper(appContext, Themes.getActivityThemeRes(context)) if (migrated) { val previewContext = LauncherPreviewRenderer.PreviewContext(inflationContext, idp) object : LoaderTask( LauncherAppState.getInstance(previewContext), null, BgDataModel(), ModelDelegate(), null ) { override fun run() { loadWorkspace( emptyList(), PREVIEW_CONTENT_URI, "$SCREEN = 0 or $CONTAINER = $CONTAINER_HOTSEAT" ) MAIN_EXECUTOR.execute { renderView(previewContext, mBgDataModel, mWidgetProvidersMap) onDestroyCallbacks.add { previewContext.onDestroy() } } } }.run() } else { LauncherAppState.getInstance(inflationContext).model.loadAsync { dataModel -> if (dataModel != null) { MAIN_EXECUTOR.execute { renderView(inflationContext, dataModel, null) } } else { onReadyCallbacks.executeAllAndDestroy() Log.e("LauncherPreviewView", "Model loading failed") } } } } @WorkerThread private fun doGridMigrationIfNecessary(): Boolean { val needsToMigrate = GridSizeMigrationTaskV2.needsToMigrate(context, idp) if (!needsToMigrate) { return false } return GridSizeMigrationTaskV2.migrateGridIfNeeded(context, idp) } @UiThread private fun renderView( inflationContext: Context, dataModel: BgDataModel, widgetProviderInfoMap: Map<ComponentKey, AppWidgetProviderInfo>? ) { if (destroyed) { return } val renderer = LauncherPreviewRenderer(inflationContext, idp, null, dummyInsets) if (dummySmartspace) { renderer.setWorkspaceSearchContainer(R.layout.smartspace_widget_placeholder) } val view = renderer.getRenderedView(dataModel, widgetProviderInfoMap) updateScale(view) view.pivotX = if (layoutDirection == LAYOUT_DIRECTION_RTL) view.measuredWidth.toFloat() else 0f view.pivotY = 0f view.layoutParams = LayoutParams(view.measuredWidth, view.measuredHeight) removeView(spinner) rendererView = view addView(view) onReadyCallbacks.executeAllAndDestroy() } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) rendererView?.let { updateScale(it) } } private fun updateScale(view: View) { // This aspect scales the view to fit in the surface and centers it val scale: Float = min( measuredWidth / view.measuredWidth.toFloat(), measuredHeight / view.measuredHeight.toFloat() ) view.scaleX = scale view.scaleY = scale } }
lawnchair/src/app/lawnchair/views/LauncherPreviewView.kt
2565390160
package com.elpassion.android.commons.espresso import android.app.Activity import android.os.Bundle import android.widget.Button import android.widget.FrameLayout import androidx.test.rule.ActivityTestRule import junit.framework.AssertionFailedError import org.hamcrest.core.IsEqual.equalTo import org.hamcrest.core.IsNull.nullValue import org.junit.Rule import org.junit.Test class HasTagTest { @JvmField @Rule val activityRule = ActivityTestRule(FakeActivity::class.java) @Test fun shouldConfirmHasTestTag() { onId(R.id.first).hasTag(equalTo(testTag)) } @Test(expected = AssertionFailedError::class) fun shouldFailWithNullTagMatcher() { onId(R.id.first).hasTag(nullValue()) } @Test(expected = AssertionFailedError::class) fun shouldFailWithAnyOtherTag() { onId(R.id.first).hasTag(equalTo("anyOtherTag")) } @Test fun shouldConfirmHasNullTag() { onId(R.id.second).hasTag(nullValue()) } @Test(expected = AssertionFailedError::class) fun shouldFailWithTestTag() { onId(R.id.second).hasTag(equalTo(testTag)) } class FakeActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(FrameLayout(this).apply { addView(Button(this.context).apply { id = R.id.first tag = testTag }) addView(Button(this.context).apply { id = R.id.second }) }) } } companion object { private val testTag = "tag" } }
espresso/src/androidTest/java/com/elpassion/android/commons/espresso/HasTagTest.kt
3123843419
package com.supercilex.robotscouter.feature.settings import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.viewModelScope import com.bumptech.glide.Glide import com.supercilex.robotscouter.core.CrashLogger import com.supercilex.robotscouter.core.RobotScouter import com.supercilex.robotscouter.core.data.SimpleViewModelBase import com.supercilex.robotscouter.core.data.cleanup import com.supercilex.robotscouter.shared.client.idpSignOut import kotlinx.coroutines.launch internal class SettingsViewModel(state: SavedStateHandle) : SimpleViewModelBase(state) { private val _signOutListener = MutableLiveData<Exception?>() val signOutListener: LiveData<Exception?> = _signOutListener fun signOut() { cleanup() Glide.get(RobotScouter).clearMemory() viewModelScope.launch { try { idpSignOut() _signOutListener.value = null } catch (e: Exception) { _signOutListener.value = e CrashLogger.onFailure(e) } } } }
feature/settings/src/main/java/com/supercilex/robotscouter/feature/settings/SettingsViewModel.kt
3518484831
/** * DO NOT EDIT THIS FILE. * * This source code was autogenerated from source code within the `app/src/gms` directory * and is not intended for modifications. If any edits should be made, please do so in the * corresponding file under the `app/src/gms` directory. */ // Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.kotlindemos import android.Manifest import android.content.pm.PackageManager import android.location.Location import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback import androidx.core.content.ContextCompat import com.example.kotlindemos.PermissionUtils.PermissionDeniedDialog.Companion.newInstance import com.example.kotlindemos.PermissionUtils.isPermissionGranted import com.example.kotlindemos.PermissionUtils.requestPermission import com.google.android.libraries.maps.GoogleMap import com.google.android.libraries.maps.GoogleMap.OnMyLocationButtonClickListener import com.google.android.libraries.maps.GoogleMap.OnMyLocationClickListener import com.google.android.libraries.maps.OnMapReadyCallback import com.google.android.libraries.maps.SupportMapFragment /** * This demo shows how GMS Location can be used to check for changes to the users location. The * "My Location" button uses GMS Location to set the blue dot representing the users location. * Permission for [Manifest.permission.ACCESS_FINE_LOCATION] is requested at run * time. If the permission has not been granted, the Activity is finished with an error message. */ class MyLocationDemoActivity : AppCompatActivity(), OnMyLocationButtonClickListener, OnMyLocationClickListener, OnMapReadyCallback, OnRequestPermissionsResultCallback { /** * Flag indicating whether a requested permission has been denied after returning in * [.onRequestPermissionsResult]. */ private var permissionDenied = false private lateinit var map: GoogleMap override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.my_location_demo) val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment? mapFragment?.getMapAsync(this) } override fun onMapReady(googleMap: GoogleMap?) { map = googleMap ?: return googleMap.setOnMyLocationButtonClickListener(this) googleMap.setOnMyLocationClickListener(this) enableMyLocation() } /** * Enables the My Location layer if the fine location permission has been granted. */ private fun enableMyLocation() { if (!::map.isInitialized) return // [START maps_check_location_permission] if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { map.isMyLocationEnabled = true } else { // Permission to access the location is missing. Show rationale and request permission requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, true ) } // [END maps_check_location_permission] } override fun onMyLocationButtonClick(): Boolean { Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show() // Return false so that we don't consume the event and the default behavior still occurs // (the camera animates to the user's current position). return false } override fun onMyLocationClick(location: Location) { Toast.makeText(this, "Current location:\n$location", Toast.LENGTH_LONG).show() } // [START maps_check_location_permission_result] override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) return } if (isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) { // Enable the my location layer if the permission has been granted. enableMyLocation() } else { // Permission was denied. Display an error message // [START_EXCLUDE] // Display the missing permission error dialog when the fragments resume. permissionDenied = true // [END_EXCLUDE] } } // [END maps_check_location_permission_result] override fun onResumeFragments() { super.onResumeFragments() if (permissionDenied) { // Permission was not granted, display error dialog. showMissingPermissionError() permissionDenied = false } } /** * Displays a dialog with error message explaining that the location permission is missing. */ private fun showMissingPermissionError() { newInstance(true).show(supportFragmentManager, "dialog") } companion object { /** * Request code for location permission request. * * @see .onRequestPermissionsResult */ private const val LOCATION_PERMISSION_REQUEST_CODE = 1 } }
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/MyLocationDemoActivity.kt
1498190193
package com.zhuinden.simplestackexamplekotlinfragment.screens import com.zhuinden.simplestackextensions.fragments.DefaultFragmentKey import kotlinx.parcelize.Parcelize /** * Created by Owner on 2017.11.13. */ @Parcelize data object HomeKey : DefaultFragmentKey() { // generate reliable `toString()` for no-args data class override fun instantiateFragment() = HomeFragment() }
samples/basic-samples/simple-stack-example-basic-kotlin-fragment/src/main/java/com/zhuinden/simplestackexamplekotlinfragment/screens/HomeKey.kt
2114352090
package com.eden.orchid.groovydoc.pages import com.copperleaf.groovydoc.json.models.GroovydocPackageDoc import com.eden.orchid.api.OrchidContext import com.eden.orchid.api.options.annotations.Archetype import com.eden.orchid.api.options.annotations.Description import com.eden.orchid.api.options.archetypes.ConfigArchetype import com.eden.orchid.groovydoc.GroovydocGenerator import com.eden.orchid.groovydoc.resources.PackageDocResource @Archetype(value = ConfigArchetype::class, key = "${GroovydocGenerator.GENERATOR_KEY}.packagePages") @Description(value = "Documentation for a Groovy package.", name = "Groovy Package") class GroovydocPackagePage( context: OrchidContext, val packageDoc: GroovydocPackageDoc, val classes: List<GroovydocClassPage> ) : BaseGroovydocPage(PackageDocResource(context, packageDoc), "groovydocPackage", packageDoc.name) { val innerPackages: MutableList<GroovydocPackagePage> = ArrayList() fun hasInterfaces(): Boolean { return classes.any { it.classDoc.kind == "interface" } } val interfaces: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "interface" } } fun hasTraits(): Boolean { return classes.any { it.classDoc.kind == "trait" } } val traits: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "trait" } } fun hasAnnotations(): Boolean { return classes.any { it.classDoc.kind == "@interface" } } val annotations: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "@interface" } } fun hasEnums(): Boolean { return classes.any { it.classDoc.kind == "enum" } } val enums: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "enum" } } fun hasExceptions(): Boolean { return classes.any { it.classDoc.kind == "exception" } } val exceptions: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "exception" } } fun hasOrdinaryClasses(): Boolean { return classes.any { it.classDoc.kind == "class" } } val ordinaryClasses: List<GroovydocClassPage> get() { return classes.filter { it.classDoc.kind == "class" } } }
plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/pages/GroovydocPackagePage.kt
3206475132
package com.github.kory33.signvote.ui.player import com.github.kory33.chatgui.command.RunnableInvoker import com.github.kory33.chatgui.tellraw.MessagePartsList import com.github.kory33.signvote.configurable.JSONConfiguration import com.github.kory33.signvote.constants.MessageConfigNodes import com.github.kory33.signvote.exception.VotePointNotVotedException import com.github.kory33.signvote.session.VoteSession import com.github.kory33.signvote.ui.player.defaults.DefaultClickableInterface import com.github.kory33.signvote.vote.VotePoint import com.github.ucchyocean.messaging.tellraw.MessageParts import org.bukkit.entity.Player /** * Represents an interface which confirms and executes player's un-vote. * @author Kory */ class UnvoteInterface(targetPlayer: Player, private val session: VoteSession, private val votePoint: VotePoint, messageConfig: JSONConfiguration, runnableInvoker: RunnableInvoker) : DefaultClickableInterface(targetPlayer, runnableInvoker, messageConfig) { private fun unVote() { if (!this.isValidSession) { return } try { this.session.voteManager.removeVote(this.targetPlayer.uniqueId, votePoint) targetPlayer.sendMessage( this.messageConfig.getFormatted(MessageConfigNodes.F_UNVOTED, this.votePoint.name)) } catch (e: VotePointNotVotedException) { this.targetPlayer.sendMessage(this.messageConfig.getString(MessageConfigNodes.NOT_VOTED)) } this.revokeSession() } /** * Get a message formatted with the given array of Object arguments(optional) * @param configurationNode configuration node from which the message should be fetched * * * @param objects objects used in formatting the fetched string * * * @return formatted message component */ private fun getFormattedMessagePart(configurationNode: String, vararg objects: Any): MessageParts { return MessageParts(this.messageConfig.getFormatted(configurationNode, *objects)) } private val heading: String get() { val votedScore = this.session.voteManager.getVotedScore(this.targetPlayer.uniqueId, this.votePoint) ?: throw IllegalStateException("Player Unvote Interface has been invoked against a non-voted votepoint!") return messageConfig.getFormatted(MessageConfigNodes.UNVOTE_UI_HEADING, this.votePoint.name, votedScore) } private val sessionClosedMessage: MessagePartsList get() { val message = this.messageConfig.getString(MessageConfigNodes.VOTE_SESSION_CLOSED) return MessagePartsList(message + "\n") } private fun cancelAction() { super.cancelAction(this.messageConfig.getString(MessageConfigNodes.UI_CANCELLED)) } override val bodyMessages: MessagePartsList get() { if (!this.session.isOpen) { return this.sessionClosedMessage } val defaultButtonMessage = this.messageConfig.getString(MessageConfigNodes.UI_BUTTON) val messagePartsList = MessagePartsList() messagePartsList.addLine(this.heading) messagePartsList.add(this.getButton({ this.unVote() }, defaultButtonMessage)) messagePartsList.addLine(this.getFormattedMessagePart(MessageConfigNodes.UNVOTE_UI_COMFIRM)) messagePartsList.add(this.getButton({ this.cancelAction() }, defaultButtonMessage)) messagePartsList.add(this.getFormattedMessagePart(MessageConfigNodes.UI_CANCEL)) return messagePartsList } }
src/main/kotlin/com/github/kory33/signvote/ui/player/UnvoteInterface.kt
622898479
package net.yslibrary.monotweety.setting.adapter import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.EditText import android.widget.TextView import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.SwitchCompat import androidx.recyclerview.widget.RecyclerView import com.hannesdorfmann.adapterdelegates4.AdapterDelegate import net.yslibrary.monotweety.R import net.yslibrary.monotweety.base.findById import net.yslibrary.monotweety.base.inflate import timber.log.Timber class FooterEditorAdapterDelegate( private val listener: Listener, ) : AdapterDelegate<List<SettingAdapter.Item>>() { override fun isForViewType(items: List<SettingAdapter.Item>, position: Int): Boolean { return items[position] is Item } override fun onBindViewHolder( items: List<SettingAdapter.Item>, position: Int, holder: RecyclerView.ViewHolder, payloads: MutableList<Any>, ) { val item = items[position] as Item if (holder is ViewHolder) { val context = holder.itemView.context val res = context.resources val subTitle = if (item.checked) res.getString(R.string.sub_label_footer_on, item.footerText) else res.getString(R.string.sub_label_footer_off) holder.title.text = res.getString(R.string.label_footer) holder.subTitle.text = subTitle holder.itemView.isEnabled = item.enabled holder.itemView.setOnClickListener { onClick(context, item) } } } override fun onCreateViewHolder(parent: ViewGroup): RecyclerView.ViewHolder { return ViewHolder.create(parent) } private fun onClick(context: Context, item: Item) { // show dialog val view = context.inflate(R.layout.dialog_footer_editor) val enabledSwitch = view.findById<SwitchCompat>(R.id.switch_button) val input = view.findById<EditText>(R.id.input) enabledSwitch.isChecked = item.checked input.setText(item.footerText, TextView.BufferType.EDITABLE) input.isEnabled = item.checked enabledSwitch.setOnCheckedChangeListener { _, checked -> input.isEnabled = checked } Timber.tag("Dialog").i("onClick - Edit Footer") AlertDialog.Builder(context) .setTitle(R.string.title_edit_footer) .setView(view) .setPositiveButton(R.string.label_confirm) { _, _ -> val enabled = enabledSwitch.isChecked val footerText = input.text.toString() listener.onFooterUpdated(enabled, footerText) }.show() } class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val title = view.findById<TextView>(R.id.title) val subTitle = view.findById<TextView>(R.id.sub_title) companion object { fun create(parent: ViewGroup): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.vh_2line_text, parent, false) return ViewHolder(view) } } } data class Item( val enabled: Boolean, val checked: Boolean, val footerText: String, override val type: SettingAdapter.ViewType, ) : SettingAdapter.Item interface Listener { fun onFooterUpdated(enabled: Boolean, footerText: String) } }
app/src/main/java/net/yslibrary/monotweety/setting/adapter/FooterEditorAdapterDelegate.kt
3408407344
package org.misuzilla.agqrplayer4tv.component.fragment.guidedstep import android.os.Bundle import android.support.v17.leanback.app.GuidedStepSupportFragment import android.support.v17.leanback.widget.GuidanceStylist import android.support.v17.leanback.widget.GuidedAction import org.misuzilla.agqrplayer4tv.R import org.misuzilla.agqrplayer4tv.infrastracture.extension.addCheckAction import org.misuzilla.agqrplayer4tv.model.preference.ApplicationPreference import org.misuzilla.agqrplayer4tv.model.preference.PlayerType /** * 設定: プレイヤー設定のGuidedStepクラスです。 */ class PlayerSettingGuidedStepFragment : GuidedStepSupportFragment() { override fun onCreateGuidance(savedInstanceState: Bundle?): GuidanceStylist.Guidance { return GuidanceStylist.Guidance(context!!.getString(R.string.guidedstep_player_title), context!!.getString(R.string.guidedstep_player_description), context!!.getString(R.string.guidedstep_settings_title), null) } override fun onCreateActions(actions: MutableList<GuidedAction>, savedInstanceState: Bundle?) { with (actions) { addCheckAction(context!!, PlayerType.EXO_PLAYER.value, context!!.getString(R.string.guidedstep_player_type_exoplayer), context!!.getString(R.string.guidedstep_player_type_exoplayer_description), ApplicationPreference.playerType.get() == PlayerType.EXO_PLAYER) addCheckAction(context!!, PlayerType.ANDROID_DEFAULT.value, context!!.getString(R.string.guidedstep_player_type_default), context!!.getString(R.string.guidedstep_player_type_default_description), ApplicationPreference.playerType.get() == PlayerType.ANDROID_DEFAULT) addCheckAction(context!!, PlayerType.WEB_VIEW.value, context!!.getString(R.string.guidedstep_player_type_webview), context!!.getString(R.string.guidedstep_player_type_webview_description), ApplicationPreference.playerType.get() == PlayerType.WEB_VIEW) } } override fun onGuidedActionClicked(action: GuidedAction) { actions.forEach { it.isChecked = it == action } ApplicationPreference.playerType.set(PlayerType.fromInt(action.id.toInt())) fragmentManager!!.popBackStack() } }
AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/component/fragment/guidedstep/PlayerSettingGuidedStepFragment.kt
1694854225
package com.orgecc.test import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity fun ResponseEntity<*>.exportToMap() = linkedMapOf( "http-status" to statusCode.name, "body" to body.toString() ) fun toResponseEntity(m: Map<String, String>): ResponseEntity<String> = ResponseEntity( m["body"] ?: "", m["http-status"]?.let { HttpStatus.valueOf(it) } ?: HttpStatus.OK ) open class MockableCallHelperForResponseEntity(mockFilePropName: String) : MockableCallHelper<ResponseEntity<String>>(mockFilePropName) { final override val importResultFromMapFun = ::toResponseEntity }
src/com/github/elifarley/kotlin/SpringTestKit.kt
3862957823
/* * Copyright (c) 2012-2017 Frederic Julian * * 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:></http:>//www.gnu.org/licenses/>. */ package net.fred.taskgame.views import android.content.Context import android.util.AttributeSet import android.view.View import android.widget.AdapterView import android.widget.Spinner /** * A Spinner will normally call it's OnItemSelectedListener * when you use setSelection(...) in your initialization code. * This is usually unwanted behavior, and a common work-around * is to use spinner.post(...) with a Runnable to assign the * OnItemSelectedListener after layout. * * If you do not call setSelection(...) manually, the callback * may be called with the first item in the adapter you have * set. The common work-around for that is to count callbacks. * * While these workarounds usually *seem* to work, the callback * may still be called repeatedly for other reasons while the * selection hasn't actually changed. This will happen for * example, if the user has accessibility options enabled - * which is more common than you might think as several apps * use this for different purposes, like detecting which * notifications are active. * * Ideally, your OnItemSelectedListener callback should be * coded defensively so that no problem would occur even * if the callback was called repeatedly with the same values * without any user interaction, so no workarounds are needed. * * This class does that for you. It keeps track of the values * you have set with the setSelection(...) methods, and * proxies the OnItemSelectedListener callback so your callback * only gets called if the selected item's position differs * from the one you have set by code, or the first item if you * did not set it. * * This also means that if the user actually clicks the item * that was previously selected by code (or the first item * if you didn't set a selection by code), the callback will * not fire. */ class BugFixedSpinner : Spinner { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) private var lastPosition = -1 private var firstTrigger = true override fun setOnItemSelectedListener(listener: OnItemSelectedListener?) { if (listener == null) { super.setOnItemSelectedListener(null) } else { firstTrigger = true super.setOnItemSelectedListener(object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) { if (firstTrigger) { firstTrigger = false lastPosition = position } else { if (position != lastPosition) { lastPosition = position listener.onItemSelected(parent, view, position, id) } } } override fun onNothingSelected(parent: AdapterView<*>?) { if (firstTrigger) { firstTrigger = false } else { if (-1 != lastPosition) { lastPosition = -1 listener.onNothingSelected(parent) } } } }) } } }
TaskGame/src/main/java/net/fred/taskgame/views/BugFixedSpinner.kt
488478653
package com.github.shynixn.blockball.api.business.enumeration /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ enum class MaterialType( /** * Numeric internal minecraft id. */ val MinecraftNumericId: Int ) { /** * Material air. */ AIR(0), /** * Skull item. */ SKULL_ITEM(397), /** * Oak fence. */ OAK_FENCE(85), /** * Oak fence gate. */ OAK_FENCE_GATE(107), /** * Nether fence. */ NETHER_FENCE(113), /** * Cobble stone wall. */ COBBLESTONE_WALL(139), /** * Stained glass pane. */ STAINED_GLASS_PANE(160), /** * Golden axe. */ GOLDEN_AXE(286), /** * Iron Bars. */ IRON_BARS(101), /** * Simple glass pane. */ GLASS_PANE(102) }
blockball-api/src/main/java/com/github/shynixn/blockball/api/business/enumeration/MaterialType.kt
3110059172
package me.mrkirby153.KirBot.database.models.guild import com.mrkirby153.bfs.model.Model import com.mrkirby153.bfs.model.annotations.Column import com.mrkirby153.bfs.model.annotations.Table import com.mrkirby153.bfs.model.annotations.Timestamps import com.mrkirby153.bfs.model.enhancers.TimestampEnhancer import java.sql.Timestamp @Table("log_settings") @Timestamps class LogSettings : Model() { var id: String = "" @Column("server_id") var serverId: String = "" @Column("channel_id") var channelId: String = "" var included: Long = 0L var excluded: Long = 0L @TimestampEnhancer.CreatedAt @Column("created_at") var createdAt: Timestamp? = null @TimestampEnhancer.UpdatedAt @Column("updated_at") var updatedAt: Timestamp? = null }
src/main/kotlin/me/mrkirby153/KirBot/database/models/guild/LogSettings.kt
3242040172
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.devtools.ksp.processor import com.google.devtools.ksp.getClassDeclarationByName import com.google.devtools.ksp.processing.Resolver import com.google.devtools.ksp.symbol.KSAnnotated import com.google.devtools.ksp.symbol.KSClassDeclaration class DeclarationInconsistencyProcessor : AbstractTestProcessor() { val results = mutableListOf<String>() override fun process(resolver: Resolver): List<KSAnnotated> { val numberClass = resolver.getClassDeclarationByName("kotlin.Number")!! val serializable = numberClass.superTypes.first { it.resolve().declaration.qualifiedName?.asString() == "java.io.Serializable" }.resolve().declaration as KSClassDeclaration val serizableDirect = resolver.getClassDeclarationByName("java.io.Serializable")!! results.add("via type: ${serializable.qualifiedName?.asString()}") serializable.getAllFunctions().forEach { results.add(it.simpleName.asString()) } results.add("via find declaration: ${serizableDirect.qualifiedName?.asString()}") serizableDirect.getAllFunctions().forEach { results.add(it.simpleName.asString()) } return emptyList() } override fun toResult(): List<String> { return results } }
test-utils/src/main/kotlin/com/google/devtools/ksp/processor/DeclarationInconsistencyProcessor.kt
3683912680
/* This file is part of Privacy Friendly App Example. Privacy Friendly App Example 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 any later version. Privacy Friendly App Example 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 Privacy Friendly App Example. If not, see <http://www.gnu.org/licenses/>. */ package org.secuso.privacyfriendlyexample.ui import android.content.Intent import android.content.SharedPreferences import android.os.Build import android.os.Bundle import android.os.Handler import android.preference.PreferenceActivity import android.preference.PreferenceManager import com.google.android.material.navigation.NavigationView import com.google.android.material.navigation.NavigationView.OnNavigationItemSelectedListener import androidx.core.app.TaskStackBuilder import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import android.view.MenuItem import android.view.View import org.secuso.privacyfriendlyexample.R /** * This class is a parent class of all activities that can be accessed from the * Navigation Drawer (example see MainActivity.java) * * The default NavigationDrawer functionality is implemented in this class. If you wish to inherit * the default behaviour, make sure the content view has a NavigationDrawer with the id 'nav_view', * the header should point to 'nav_header_main' and the menu should be loaded from 'main_drawer'. * * Also the main layout that holds the content of the activity should have the id 'main_content'. * This way it will automatically fade in and out every time a transition is happening. * * @author Christopher Beckmann (Kamuno), Karola Marky (yonjuni) * @version 20161225 */ abstract class BaseActivity : AppCompatActivity(), OnNavigationItemSelectedListener { companion object { // delay to launch nav drawer item, to allow close animation to play internal const val NAVDRAWER_LAUNCH_DELAY = 250 // fade in and fade out durations for the main content when switching between // different Activities of the app through the Nav Drawer internal const val MAIN_CONTENT_FADEOUT_DURATION = 150 internal const val MAIN_CONTENT_FADEIN_DURATION = 250 } // Navigation drawer: private var mDrawerLayout: DrawerLayout? = null private var mNavigationView: NavigationView? = null // Helper private val mHandler: Handler = Handler() protected val mSharedPreferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(this) } protected abstract val navigationDrawerID: Int override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition(0, 0) } override fun onBackPressed() { val drawer = findViewById<View>(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onNavigationItemSelected(item: MenuItem): Boolean = goToNavigationItem(item.itemId) protected fun goToNavigationItem(itemId: Int): Boolean { if (itemId == navigationDrawerID) { // just close drawer because we are already in this activity mDrawerLayout?.closeDrawer(GravityCompat.START) return true } // delay transition so the drawer can close mHandler.postDelayed({ callDrawerItem(itemId) }, NAVDRAWER_LAUNCH_DELAY.toLong()) mDrawerLayout?.closeDrawer(GravityCompat.START) selectNavigationItem(itemId) // fade out the active activity val mainContent = findViewById<View>(R.id.main_content) mainContent?.animate()!!.alpha(0f).duration = MAIN_CONTENT_FADEOUT_DURATION.toLong() return true } // set active navigation item private fun selectNavigationItem(itemId: Int) { mNavigationView ?: return for (i in 0 until mNavigationView!!.menu.size()) { val b = itemId == mNavigationView!!.menu.getItem(i).itemId mNavigationView!!.menu.getItem(i).isChecked = b } } /** * Enables back navigation for activities that are launched from the NavBar. See * `AndroidManifest.xml` to find out the parent activity names for each activity. * @param intent */ private fun createBackStack(intent: Intent) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { val builder = TaskStackBuilder.create(this) builder.addNextIntentWithParentStack(intent) builder.startActivities() } else { startActivity(intent) finish() } } /** * This method manages the behaviour of the navigation drawer * Add your menu items (ids) to res/menu/main_drawer.xmlparam itemId Item that has been clicked by the user */ private fun callDrawerItem(itemId: Int) { val intent: Intent when (itemId) { R.id.nav_example -> { intent = Intent(this, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP } startActivity(intent) } R.id.nav_game -> { intent = Intent(this, GameActivity::class.java) createBackStack(intent) } R.id.nav_about -> { intent = Intent(this, AboutActivity::class.java) createBackStack(intent) } R.id.nav_help -> { intent = Intent(this, HelpActivity::class.java) createBackStack(intent) } R.id.nav_tutorial -> { intent = Intent(this, TutorialActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TOP } startActivity(intent) } R.id.nav_settings -> { intent = Intent(this, SettingsActivity::class.java) intent.putExtra(PreferenceActivity.EXTRA_SHOW_FRAGMENT, SettingsActivity.GeneralPreferenceFragment::class.java.name) intent.putExtra(PreferenceActivity.EXTRA_NO_HEADERS, true) createBackStack(intent) } } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) val toolbar = findViewById<View>(R.id.toolbar) as Toolbar if (supportActionBar == null) { setSupportActionBar(toolbar) } mDrawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout val toggle = ActionBarDrawerToggle( this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) mDrawerLayout!!.addDrawerListener(toggle) toggle.syncState() mNavigationView = findViewById<View>(R.id.nav_view) as NavigationView mNavigationView!!.setNavigationItemSelectedListener(this) selectNavigationItem(navigationDrawerID) val mainContent = findViewById<View>(R.id.main_content) if (mainContent != null) { mainContent.alpha = 0f mainContent.animate().alpha(1f).duration = MAIN_CONTENT_FADEIN_DURATION.toLong() } } }
app/src/main/java/org/secuso/privacyfriendlyexample/ui/BaseActivity.kt
1031286530
package pinboard import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.test.autoconfigure.json.AutoConfigureJsonTesters import org.springframework.boot.test.context.SpringBootTest import org.springframework.http.HttpMethod import org.springframework.http.MediaType import org.springframework.test.web.client.ExpectedCount import org.springframework.test.web.client.ExpectedCount.manyTimes import org.springframework.test.web.client.MockRestServiceServer import org.springframework.test.web.client.ResponseCreator import org.springframework.test.web.client.match.MockRestRequestMatchers.method import org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo import org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess import org.springframework.web.client.RestTemplate import pinboard.format.FormatUtils import java.time.Instant import java.time.ZoneId import java.time.temporal.ChronoField import java.time.temporal.ChronoUnit import java.util.* /** * @author <a href="mailto:[email protected]">Josh Long</a> */ @SpringBootTest( classes = [MockPinboardClientTest.Config::class], properties = ["pinboard.token=1234"] ) @AutoConfigureJsonTesters class MockPinboardClientTest( @Autowired val restTemplate: RestTemplate, @Autowired val pinboardClient: PinboardClient ) { @SpringBootApplication class Config private var mockRestServiceServer: MockRestServiceServer? = null private val auth = "1234" private val commonUriParams = """ format=json&auth_token=${auth} """.trim() private val testTag = "pbctest" private val testTag2 = "pbctest2" private val bookmark = Bookmark("http:/" + "/garfield.com", "description", "extended", "hash", "meta", Date(), true, true, arrayOf(this.testTag, this.testTag2)) private val pinboardClientTestTag: Array<String> by lazy { bookmark.tags } @BeforeEach fun setUp() { this.mockRestServiceServer = MockRestServiceServer.bindTo(this.restTemplate).build() } @Test fun getTheLast10Days() { val tenDaysAgo = Instant.now().minus(10, ChronoUnit.DAYS) val fromdt = Date.from(tenDaysAgo) val moreRecent = tenDaysAgo.plus(2, ChronoUnit.DAYS).atZone(ZoneId.systemDefault()) val month = moreRecent.get(ChronoField.MONTH_OF_YEAR) val date = moreRecent.get(ChronoField.DAY_OF_MONTH) val year = moreRecent.get(ChronoField.YEAR_OF_ERA) val json = """ [ {"tags":"pbctest pbctest2", "time":"${year}-${month}-${date}T08:21:11Z","shared":"yes","toread":"yes", "href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"} ] """ mockReply("/posts/all?fromdt=${FormatUtils.encodeDate(fromdt)}&meta=0&format=json&start=0&tag=twis&auth_token=$auth&results=-1", json) val postsByDate = pinboardClient!!.getAllPosts(arrayOf("twis"), fromdt = fromdt) val comparator = Comparator<Bookmark> { a, b -> a.time!!.compareTo(b.time) } val minBookmark = postsByDate.minWith(comparator) assert(minBookmark!!.time!!.after(fromdt)) } @Test fun addPost() { val encodeDate = FormatUtils.encodeDate(bookmark.time!!) mockReply(""" /posts/add?dt=$encodeDate&shared=yes&toread=yes&format=json&replace=yes&description=description&auth_token=$auth&url=http://garfield.com&extended=extended&tags=pbctest%20pbctest2 """ , """ { "status" : "done"} """) val post = pinboardClient.addPost(bookmark.href!!, bookmark.description!!, bookmark.extended!!, bookmark.tags, bookmark.time!!, true, true, true) assert(post, { "the bookmark has not been added." }) } @Test fun getPosts() { val json = """ { "user" : "starbuxman" , "date" : "${FormatUtils.encodeDate(Date())}", "posts": [ {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes", "href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"} ] } """ mockReply("/posts/get?format=json&auth_token=$auth&url=http://garfield.com", json) val result = pinboardClient.getPosts(bookmark.href) val href = result.posts.first().href assert(href == bookmark.href) } @Test fun getRecentPostsByTag() { val json = """ { "user" : "starbuxman" , "date" : "${FormatUtils.encodeDate(Date())}", "posts": [ {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes", "href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"} ] } """ val uri = """ /posts/recent?format=json&count=15&tag=pbctest%20pbctest2&auth_token=$auth """ mockReply(uri, json) val result = pinboardClient.getRecentPosts(tag = bookmark.tags) val href = result.posts.first().href assert(href == bookmark.href) mockRestServiceServer!!.verify() } @Test fun deletePost() { val json = """ [ {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com/b","description":"description","extended":"extended","hash":"hash","meta":"meta"} ] """ mockReply("/posts/all?meta=0&format=json&start=0&tag=pbctest%20pbctest2&auth_token=$auth&results=-1", json) assert(bookmark.href != null) assert(this.pinboardClient.getAllPosts(bookmark.tags).size == 1) } @Test fun getNoOfPostsByDate() { val json = """{"tag":"twis cats","user":"starbuxman","dates":{"2017-08-16T08:31:25.755+0000":5}} """ mockReply("/posts/dates?format=json&tag=twis&auth_token=$auth", json) val tagName = "twis" val result = pinboardClient.getCountOfPostsByDate(arrayOf(tagName)) assert(result.user!!.toLowerCase() == "starbuxman") assert(result.dates!!.isNotEmpty()) assert(result.tag!!.contains(tagName)) mockRestServiceServer!!.verify() } @Test fun deleteTag() { val first = this.pinboardClientTestTag.first() val uri = """ tags/delete?format=json&tag=${first}&auth_token=${auth} """ mockReply(uri, """ { "status" : "done" } """) assert(pinboardClient.deleteTag(first)) } @Test fun secret() { mockReply("/user/secret?format=json&auth_token=${auth}", """ { "result" : "1234" } """) val userSecret = pinboardClient!!.getUserSecret() assert(userSecret.isNotBlank(), { "the userSecret should not be null" }) } @Test fun apiToken() { mockReply("/user/api_token/?format=json&auth_token=${auth}", """ { "result" : "${auth}" } """) val token = pinboardClient!!.getApiToken() assert(token.isNotBlank(), { "the token should not be null" }) } @Test fun getAllBookmarksByTag() { val twisTag = "twis" val json = """ [ {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com/a","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com/b","description":"description","extended":"extended","hash":"hash","meta":"meta"} ] """ val uri = """ /posts/all?meta=0&format=json&start=0&tag=${twisTag}&auth_token=${auth}&results=-1 """.trimIndent() mockReply(uri, json) val postsByTag = pinboardClient!!.getAllPosts(arrayOf(twisTag)) assert(postsByTag.isNotEmpty()) assert(postsByTag.size > 1) } @Test fun get10Records() { val json = """ [ {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"}, {"tags":"pbctest pbctest2","time":"2017-08-16T08:21:11Z","shared":"yes","toread":"yes","href":"http://garfield.com","description":"description","extended":"extended","hash":"hash","meta":"meta"} ] """ mockReply("/posts/all?meta=0&format=json&start=0&tag=twis&auth_token=$auth&results=10", json) val maxResults = 10 val postsByTag = pinboardClient!!.getAllPosts(arrayOf("twis"), 0, maxResults) assert(postsByTag.size == maxResults, { "there should be no more than 10 getAllPosts." }) } @Test fun notes() { val noteDate = FormatUtils.encodeNoteDate(Date()) val noteId = "123" val noteJson = """ { "id": "${noteId}" , "title" : "title" , "length" : 2, "created_at" : "${noteDate}", "updated_at" : "${noteDate}", "hash" : "1234" } """ val notesJson = """ { "count" : 3, "notes" : [ ${noteJson} ,${noteJson}, ${noteJson}] } """ mockReply("/notes/list?format=json&auth_token=${auth}", notesJson) mockReply("/notes/${noteId}?format=json&auth_token=${auth}", noteJson) val userNotes = pinboardClient!!.getUserNotes() assert(userNotes.count == userNotes.notes!!.size) val firstNote = userNotes.notes!![0] val firstId = firstNote.id val userNote = pinboardClient!!.getUserNote(firstId!!) assert(userNote.id == firstId) assert(userNote.created == firstNote.created) assert(userNote.updated == firstNote.updated) assert(userNote.length == firstNote.length) assert(userNote.title == firstNote.title) mockRestServiceServer!!.verify() } @Test fun getUserTags() { val json = """ { "twis" : 2, "politics" : 4 } """ mockReply("tags/get?${commonUriParams}", json) val tagCloud = pinboardClient!!.getUserTags() val twisCount = tagCloud["twis"]!! assert(twisCount > 0) mockRestServiceServer!!.verify() } @Test fun suggestTagsForPost() { val json = """ [ { "recommended" :[ "politics" , "trump" ] } , { "popular" : [] } ] """ val url = "http://infoq.com".trim() mockReply(""" posts/suggest?format=json&auth_token=${auth}&url=${url} """, json) val tagsForPost = pinboardClient!!.suggestTagsForPost(url) assert(tagsForPost.recommended!!.isNotEmpty()) mockRestServiceServer!!.verify() } private fun mockReply(uri: String, json: String, rc: ResponseCreator = withSuccess(json.trim(), MediaType.APPLICATION_JSON_UTF8), method: HttpMethod = HttpMethod.GET, count: ExpectedCount = manyTimes()) { val correctedUri: String by lazy { val x = uri.trim() if (x.startsWith("/")) x.substring(1) else x } this.mockRestServiceServer!! .expect(count, requestTo("https://api.pinboard.in/v1/${correctedUri}")) .andExpect(method(method)) .andRespond(rc) } }
src/test/kotlin/pinboard/MockPinboardClientTest.kt
2413196951
/* * Copyright (c) 2017 Fabio Berta * * 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 ch.berta.fabio.popularmovies.features.base import android.arch.lifecycle.LifecycleFragment import android.content.Context abstract class BaseFragment<T : BaseFragment.ActivityListener> : LifecycleFragment() { lateinit var activityListener: T override fun onAttach(context: Context?) { super.onAttach(context) @Suppress("UNCHECKED_CAST") activityListener = context as T } interface ActivityListener }
app/src/main/java/ch/berta/fabio/popularmovies/features/base/BaseFragment.kt
3456757135
package org.testng.internal.samples.classhelper.issue1339; open class PapaBearSample : GrandpaBearSample() { private fun secretMethod(foo: String) {} fun announcer(foo: String) {} fun inheritable(foo: String) {} }
testng-core/src/test/kotlin/org/testng/internal/samples/classhelper/issue1339/PapaBearSample.kt
2340955331
/* * Copyright (c) 2022, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be * used to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package no.nordicsemi.android.service import android.bluetooth.BluetoothDevice import android.content.Context import android.content.Intent import dagger.hilt.android.qualifiers.ApplicationContext import no.nordicsemi.ui.scanner.DiscoveredBluetoothDevice import javax.inject.Inject const val DEVICE_DATA = "device-data" class ServiceManager @Inject constructor( @ApplicationContext private val context: Context ) { fun <T> startService(service: Class<T>, device: DiscoveredBluetoothDevice) { val intent = Intent(context, service).apply { putExtra(DEVICE_DATA, device) } context.startService(intent) } fun <T> startService(service: Class<T>, device: BluetoothDevice) { val intent = Intent(context, service).apply { putExtra(DEVICE_DATA, device) } context.startService(intent) } fun <T> startService(service: Class<T>) { val intent = Intent(context, service) context.startService(intent) } fun <T> stopService(service: Class<T>) { val intent = Intent(context, service) context.stopService(intent) } }
lib_service/src/main/java/no/nordicsemi/android/service/ServiceManager.kt
3153431393
/* * The MIT License * * Copyright 2015 Nathan Templon. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package com.jupiter.europa.screen.dialog import com.badlogic.gdx.graphics.g2d.TextureAtlas import com.badlogic.gdx.scenes.scene2d.Actor import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle import com.badlogic.gdx.scenes.scene2d.ui.TextField.TextFieldStyle import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener import com.badlogic.gdx.scenes.scene2d.utils.Drawable import com.badlogic.gdx.scenes.scene2d.utils.SpriteDrawable import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.jupiter.europa.EuropaGame import com.jupiter.europa.entity.EuropaEntity import com.jupiter.europa.entity.Mappers import com.jupiter.europa.entity.Party import com.jupiter.europa.entity.component.MovementResourceComponent import com.jupiter.europa.entity.effects.Effect import com.jupiter.europa.entity.stats.AttributeSet import com.jupiter.europa.entity.stats.SkillSet.Skills import com.jupiter.europa.entity.stats.characterclass.CharacterClass import com.jupiter.europa.entity.stats.race.PlayerRaces import com.jupiter.europa.entity.stats.race.Race import com.jupiter.europa.entity.traits.EffectPool import com.jupiter.europa.entity.traits.feat.Feat import com.jupiter.europa.io.FileLocations import com.jupiter.europa.scene2d.ui.AttributeSelector import com.jupiter.europa.scene2d.ui.EuropaButton import com.jupiter.europa.scene2d.ui.EuropaButton.ClickEvent import com.jupiter.europa.scene2d.ui.MultipleNumberSelector import com.jupiter.europa.scene2d.ui.MultipleNumberSelector.MultipleNumberSelectorStyle import com.jupiter.europa.scene2d.ui.ObservableDialog import com.jupiter.europa.screen.MainMenuScreen import com.jupiter.europa.screen.MainMenuScreen.DialogExitStates import com.jupiter.ganymede.event.Listener import java.util.ArrayList import java.util.Arrays import java.util.Collections import java.util.HashSet /** * @author Nathan Templon */ public class CreateCharacterDialog : ObservableDialog(CreateCharacterDialog.DIALOG_NAME, CreateCharacterDialog.getDefaultSkin().get(javaClass<Window.WindowStyle>())) { // Enumerations public enum class CreateCharacterExitStates { OK, CANCELED } // Properties private val selectRaceClass: SelectRaceClassAttributesDialog private var selectSkills: SelectSkillsDialog? = null private var selectFeats: SelectTraitDialog<Feat>? = null private var manager: DialogManager? = null private val otherPools = ArrayList<EffectPool<out Effect>>() private val skinInternal: Skin = getDefaultSkin() public var exitState: CreateCharacterExitStates = CreateCharacterExitStates.CANCELED private set public var createdEntity: EuropaEntity? = null private set private var lastDialog: Dialog? = null private var widthInternal: Float = 0.toFloat() private var heightInternal: Float = 0.toFloat() public fun getDialogs(): Collection<ObservableDialog> { val dialogs = HashSet<ObservableDialog>(3) dialogs.add(this.selectRaceClass) dialogs.add(this.selectSkills) dialogs.add(this.selectFeats) return dialogs.filterNotNull().toSet() } init { this.selectRaceClass = SelectRaceClassAttributesDialog(skinInternal) this.selectRaceClass.addDialogListener({ args -> this.onSelectRaceClassHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.selectSkills = SelectSkillsDialog(skinInternal, 8, 4, Arrays.asList(*Skills.values())) this.selectSkills?.addDialogListener({ args -> this.onSelectSkillsHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.lastDialog = this.selectRaceClass this.addDialogListener({ args -> this.onShown(args) }, ObservableDialog.DialogEvents.SHOWN) } // Public Methods override fun setSize(width: Float, height: Float) { super.setSize(width, height) this.getDialogs().forEach { it.setSize(width, height) } this.manager?.dialogs?.forEach { it.setSize(width, height) } this.widthInternal = width this.heightInternal = height } // Private Methods private fun onShown(args: ObservableDialog.DialogEventArgs) { val last = this.lastDialog if (last != null) { if (last is SelectTraitDialog<*>) { val manager = this.manager if (manager != null && manager.dialogs.contains(last)) { manager.index = manager.dialogs.indexOf(last) manager.start() } else { this.showDialog(last) } } else { this.showDialog(last) } } } private fun onSelectRaceClassHide(args: ObservableDialog.DialogEventArgs) { if (this.selectRaceClass.exitState === DialogExitStates.NEXT) { this.createEntity() val skills = Mappers.skills.get(this.createdEntity) val skillList = skills.classSkills val classComp = Mappers.characterClass.get(this.createdEntity) this.selectSkills = SelectSkillsDialog(this.skinInternal, classComp.characterClass.availableSkillPoints - skills.getSkillPointsSpent(), classComp.characterClass.maxPointsPerSkill, skillList) this.selectSkills!!.addDialogListener({ args -> this.onSelectSkillsHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.showDialog(this.selectSkills) } else { this.exitState = CreateCharacterExitStates.CANCELED this.concludeDialog() } } private fun onSelectSkillsHide(args: ObservableDialog.DialogEventArgs) { if (this.selectSkills!!.exitState === DialogExitStates.NEXT) { // Debug Code this.selectFeats = SelectTraitDialog("Select Feats", this.skinInternal, Mappers.characterClass.get(this.createdEntity).characterClass.featPool) selectFeats!!.setDialogBackground(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.selectFeats!!.addDialogListener({ args -> this.onSelectFeatsHide(args) }, ObservableDialog.DialogEvents.HIDDEN) this.showDialog(selectFeats) } else { this.showDialog(this.selectRaceClass) } } private fun onSelectFeatsHide(args: ObservableDialog.DialogEventArgs) { if (this.selectFeats!!.exitState === DialogExitStates.NEXT) { this.selectFeats!!.applyChanges() val charClass = Mappers.characterClass.get(this.createdEntity).characterClass this.otherPools.clear() this.otherPools.addAll(charClass.abilityPools .filter { it != charClass.featPool } .toList()) val dialogs = this.otherPools.map { pool -> SelectTraitDialog("Select " + pool.name, this.skinInternal, pool) as SelectTraitDialog<*> // Unnecessary cast due to java-kotlin interop quirk }.toList() // Switch to a DialogManager that can handle the "back" button if (dialogs.size() > 0) { for (dialog in dialogs) { dialog.setDialogBackground(this.skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) } val manager = DialogManager(dialogs, { dialog -> this.showDialog(dialog) }) manager.onForward = { this.exitState = CreateCharacterExitStates.OK this.concludeDialog() } manager.onBack = { // Going back one dialog this.showDialog(this.selectFeats) } manager.start() this.manager = manager } else { this.exitState = CreateCharacterExitStates.OK this.concludeDialog() } } else { // Going back one dialog this.showDialog(this.selectSkills) } } private fun showDialog(dialog: Dialog?) { if (dialog != null) { dialog.show(this.getStage()) dialog.setSize(this.widthInternal, this.heightInternal) this.lastDialog = dialog } } private fun concludeDialog() { if (this.createdEntity != null) { val comp = Mappers.skills.get(this.createdEntity) if (comp != null) { val skills = comp.skills val skillLevels = this.selectSkills!!.getSelectedSkills() for ((skill, value) in skillLevels) { skills.setSkill(skill, value) } } for (dialog in this.manager?.dialogs ?: listOf()) { dialog.applyChanges() } } this.hide() } private fun createEntity() { this.createdEntity = Party.createPlayer(this.selectRaceClass.getCharacterName(), CharacterClass.CLASS_LOOKUP.get(this.selectRaceClass.getSelectedClass())!!, this.selectRaceClass.getSelectedRace(), this.selectRaceClass.getAttributes()) } // Nested Classes private class SelectRaceClassAttributesDialog(private val skinInternal: Skin) : ObservableDialog(CreateCharacterDialog.SelectRaceClassAttributesDialog.DIALOG_NAME, skinInternal.get(javaClass<Window.WindowStyle>())) { private var mainTable: Table? = null private var selectBoxTable: Table? = null private var nameTable: Table? = null private var nameLabel: Label? = null private var nameField: TextField? = null private var raceSelectBox: SelectBox<Race>? = null private var classSelectBox: SelectBox<String>? = null private var titleLabelInternal: Label? = null private var raceLabel: Label? = null private var classLabel: Label? = null private var raceClassPreview: Image? = null private var backButton: EuropaButton? = null private var nextButton: EuropaButton? = null private var attributeSelector: AttributeSelector? = null public var exitState: DialogExitStates = DialogExitStates.BACK private set public fun getSelectedClass(): String { return this.classSelectBox!!.getSelected() } public fun getSelectedRace(): Race { return this.raceSelectBox!!.getSelected() } public fun getCharacterPortrait(): Drawable { return this.raceClassPreview!!.getDrawable() } public fun getCharacterName(): String { return this.nameField!!.getText() } public fun getAttributes(): AttributeSet { return this.attributeSelector!!.getAttributes() } init { this.initComponents() this.addDialogListener({ args -> this.nextButton?.setChecked(false) this.backButton?.setChecked(false) }, ObservableDialog.DialogEvents.SHOWN) } // Private Methods private fun initComponents() { this.titleLabelInternal = Label(TITLE, skinInternal.get(javaClass<LabelStyle>())) this.raceLabel = Label("Race: ", skinInternal.get(javaClass<LabelStyle>())) this.classLabel = Label("Class: ", skinInternal.get(javaClass<LabelStyle>())) this.nameLabel = Label("Name: ", skinInternal.get(javaClass<LabelStyle>())) this.nameField = TextField("default", skinInternal.get(javaClass<TextFieldStyle>())) this.raceClassPreview = Image(EuropaGame.game.assetManager!!.get(FileLocations.SPRITES_DIRECTORY.resolve("CharacterSprites.atlas").toString(), javaClass<TextureAtlas>()).findRegion(PlayerRaces.Human.textureString + "-champion-" + MovementResourceComponent.FRONT_STAND_TEXTURE_NAME)) this.raceClassPreview?.setScale(IMAGE_SCALE.toFloat()) this.raceSelectBox = SelectBox<Race>(skinInternal.get(javaClass<SelectBox.SelectBoxStyle>())) this.raceSelectBox?.setItems(*PlayerRaces.values()) this.raceSelectBox?.addListener(object : ChangeListener() { override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) { [email protected]() } }) this.classSelectBox = SelectBox<String>(skinInternal.get(javaClass<SelectBox.SelectBoxStyle>())) this.classSelectBox?.setItems(*CharacterClass.AVAILABLE_CLASSES.toTypedArray()) this.classSelectBox?.addListener(object : ChangeListener() { override fun changed(event: ChangeListener.ChangeEvent, actor: Actor) { [email protected]() } }) this.backButton = EuropaButton("Back", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.backButton?.addClickListener({ args -> this.onRaceClassBackButton(args) }) this.nextButton = EuropaButton("Next", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.nextButton!!.addClickListener({ args -> this.onRaceClassNextButton(args) }) this.attributeSelector = AttributeSelector(50, skinInternal.get(javaClass<MultipleNumberSelectorStyle>()), 2) this.nameTable = Table() this.nameTable!!.add<Label>(this.nameLabel).left().space(MainMenuScreen.COMPONENT_SPACING.toFloat()) this.nameTable!!.add<TextField>(this.nameField).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).padTop(10f).expandX().fillX() this.mainTable = Table() this.selectBoxTable = Table() this.selectBoxTable!!.add<Label>(this.raceLabel).fillX().space(MainMenuScreen.COMPONENT_SPACING.toFloat()) this.selectBoxTable!!.add<Label>(this.classLabel).fillX().space(MainMenuScreen.COMPONENT_SPACING.toFloat()).spaceLeft((5 * MainMenuScreen.COMPONENT_SPACING).toFloat()) this.selectBoxTable!!.row() this.selectBoxTable!!.add<SelectBox<Race>>(this.raceSelectBox).minWidth(MainMenuScreen.TITLE_BUTTON_WIDTH.toFloat()).fillX() this.selectBoxTable!!.add<SelectBox<String>>(this.classSelectBox).minWidth(MainMenuScreen.TITLE_BUTTON_WIDTH.toFloat()).fillX().spaceLeft((5 * MainMenuScreen.COMPONENT_SPACING).toFloat()) this.selectBoxTable!!.row() this.mainTable!!.add<Label>(this.titleLabelInternal).center().colspan(2) this.mainTable!!.row() this.mainTable!!.add(Image()).expandY().fillY() this.mainTable!!.row() this.mainTable!!.add<Table>(this.nameTable).colspan(2).expandX().fillX().bottom() this.mainTable!!.row() this.mainTable!!.add<Table>(this.selectBoxTable).left() this.mainTable!!.add<Image>(this.raceClassPreview).center() this.mainTable!!.row() this.mainTable!!.add<AttributeSelector>(this.attributeSelector).colspan(2).center().top().padTop(40f) this.mainTable!!.row() this.mainTable!!.add(Image()).expandY().fillY() this.mainTable!!.row() val buttonTable = Table() buttonTable.add<EuropaButton>(this.backButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX() buttonTable.add<EuropaButton>(this.nextButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.mainTable!!.add(buttonTable).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).right().colspan(2).expandX().fillX() this.mainTable!!.row() this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.background(skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).expand().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat()) } private fun updateNewCharacterPreview() { val race = this.raceSelectBox?.getSelected() val charClass = CharacterClass.CLASS_LOOKUP.get(this.classSelectBox?.getSelected()) try { val classInstance = charClass?.newInstance() val textureClassString = classInstance?.textureSetName val texture = race?.textureString + "-" + textureClassString + "-" + MovementResourceComponent.FRONT_STAND_TEXTURE_NAME val drawable = TextureRegionDrawable(EuropaGame.game.assetManager!!.get(FileLocations.SPRITES_DIRECTORY.resolve("CharacterSprites.atlas").toString(), javaClass<TextureAtlas>()).findRegion(texture)) this.raceClassPreview!!.setDrawable(drawable) } catch (ex: IllegalAccessException) { } catch (ex: InstantiationException) { } } private fun onRaceClassBackButton(event: ClickEvent) { this.exitState = DialogExitStates.BACK this.hide() } private fun onRaceClassNextButton(event: ClickEvent) { this.exitState = DialogExitStates.NEXT this.hide() } companion object { // Constants private val DIALOG_NAME = "" private val TITLE = "Select a Race and Class" private val IMAGE_SCALE = 4 } } private class SelectSkillsDialog(private val skinInternal: Skin, private val skillPointsAvailable: Int, public val maxPointsPerSkill: Int, private val selectableSkills: List<Skills>) : ObservableDialog(CreateCharacterDialog.SelectSkillsDialog.DIALOG_TITLE, skinInternal.get(javaClass<Window.WindowStyle>())) { private var mainTable: Table? = null private var titleLabelInternal: Label? = null private var skillSelector: MultipleNumberSelector? = null private var buttonTableInternal: Table? = null private var nextButton: EuropaButton? = null private var backButton: EuropaButton? = null public var exitState: DialogExitStates? = null private set public fun getSelectedSkills(): Map<Skills, Int> = this.skillSelector?.getValues()?.map { entry -> val skill = Skills.getByDisplayName(entry.getKey()) if (skill != null) { Pair(skill, entry.getValue()) } else { null } }?.filterNotNull()?.toMap() ?: mapOf() init { this.initComponent() } // Private Methods private fun initComponent() { this.titleLabelInternal = Label(TITLE, skinInternal.get(javaClass<LabelStyle>())) this.mainTable = Table() // Create Attribute Selector val skillNames = this.selectableSkills.map { skill -> skill.displayName }.toList() this.skillSelector = MultipleNumberSelector(this.skillPointsAvailable, this.skinInternal.get(javaClass<MultipleNumberSelectorStyle>()), Collections.unmodifiableList<String>(skillNames), 2) this.skillSelector?.setUseMaximumNumber(true) this.skillSelector?.maximumNumber = this.maxPointsPerSkill this.skillSelector?.setIncrement(5) this.nextButton = EuropaButton("Next", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.nextButton?.addClickListener { args -> this.onNextButton(args) } this.backButton = EuropaButton("Back", skinInternal.get(javaClass<TextButton.TextButtonStyle>())) this.backButton!!.addClickListener { args -> this.onBackButton(args) } this.buttonTableInternal = Table() this.buttonTableInternal!!.add<EuropaButton>(this.backButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right().expandX() this.buttonTableInternal!!.add<EuropaButton>(this.nextButton).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).width(MainMenuScreen.DIALOG_BUTTON_WIDTH.toFloat()).right() this.mainTable!!.add<Label>(this.titleLabelInternal).center().top() this.mainTable!!.row() this.mainTable!!.add<MultipleNumberSelector>(this.skillSelector).expandY().center().top() this.mainTable!!.row() this.mainTable!!.add<Table>(buttonTableInternal).space(MainMenuScreen.COMPONENT_SPACING.toFloat()).bottom().right().expandX().fillX() this.mainTable!!.row() this.mainTable!!.pad(MainMenuScreen.TABLE_PADDING.toFloat()) this.mainTable!!.background(skinInternal.get(MainMenuScreen.DIALOG_BACKGROUND_KEY, javaClass<SpriteDrawable>())) this.getContentTable().add<Table>(this.mainTable).expand().fillY().width(MainMenuScreen.DIALOG_WIDTH.toFloat()) } private fun onNextButton(event: ClickEvent) { this.exitState = DialogExitStates.NEXT this.hide() } private fun onBackButton(event: ClickEvent) { this.exitState = DialogExitStates.BACK this.hide() } companion object { // Constants private val DIALOG_TITLE = "" private val TITLE = "Select Skills" } }// Properties private class DialogManager(internal val dialogs: List<SelectTraitDialog<*>>, private val show: (ObservableDialog) -> Unit) : Listener<ObservableDialog.DialogEventArgs> { internal var index: Int = 0 public var onForward: () -> Unit = {} public var onBack: () -> Unit = {} public fun start() { if (dialogs.size() > 0) { this.show(this.index) } else { this.onForward() } } private fun show(index: Int) { val dialog = this.dialogs[index] dialog.addDialogListener(this, ObservableDialog.DialogEvents.HIDDEN) this.show(dialog) } override fun handle(args: ObservableDialog.DialogEventArgs) { this.dialogs[this.index].removeDialogListener(this) when (this.dialogs[this.index].exitState) { DialogExitStates.BACK -> this.index-- DialogExitStates.NEXT -> this.index++ } if (this.index <= 0) { this.onBack() } else if (this.index >= this.dialogs.size()) { this.onForward() } else { this.show(this.index) } } } companion object { // Constants public val DIALOG_NAME: String = "Create a Character" // Static Methods private fun getDefaultSkin(): Skin { return MainMenuScreen.createMainMenuSkin() } } }
core/src/com/jupiter/europa/screen/dialog/CreateCharacterDialog.kt
3176277135
package com.garpr.android.data.database import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.garpr.android.data.models.Endpoint @Dao interface SmashCompetitorDao { @Query("DELETE FROM smashCompetitors") fun deleteAll() @Query("SELECT * FROM smashCompetitors WHERE endpoint = :endpoint AND id = :id LIMIT 1") fun get(endpoint: Endpoint, id: String): DbSmashCompetitor? @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(dbSmashCompetitors: List<DbSmashCompetitor>) }
smash-ranks-android/app/src/main/java/com/garpr/android/data/database/SmashCompetitorDao.kt
1211084828
package com.am5800.polyglot.app.sentenceGeneration.commonAttributes enum class Person { First, Second, Third, }
app/src/main/kotlin/com/am5800/polyglot/app/sentenceGeneration/commonAttributes/Person.kt
1347845718
package com.cyrillrx.utils import android.util.Base64 import java.math.BigInteger import java.security.SecureRandom import javax.crypto.Mac import javax.crypto.spec.SecretKeySpec /** * @author Cyril Leroux * Created on 20/09/2018 */ /** Keyed-Hash Message Authentication Code (HMAC) key using SHA-512 as the hash. */ private const val ALGORITHM_HMAC_SHA512 = "HmacSHA512" /** Maximum length of the new `BigInteger` in bits. */ private const val NUM_BITS = 130 /** Radix base to be used for the string representation. */ private const val RADIX = 32 fun String.base64Encode(): String? = try { val byteArray = toByteArray(Charsets.UTF_8) Base64.encodeToString(byteArray, Base64.NO_WRAP) } catch (e: Exception) { null } fun String.signature(secret: String): String? = try { val key = SecretKeySpec(secret.toByteArray(Charsets.UTF_8), ALGORITHM_HMAC_SHA512) val hMacSha512 = Mac.getInstance(ALGORITHM_HMAC_SHA512) hMacSha512.init(key) val byteArray = toByteArray(Charsets.UTF_8) val macData = hMacSha512.doFinal(byteArray) Base64.encodeToString(macData, Base64.NO_WRAP) } catch (e: Exception) { null } fun buildNonce(): String = BigInteger(NUM_BITS, SecureRandom()).toString(RADIX)
core/src/main/java/com/cyrillrx/utils/Security.kt
2078256632
package moe.feng.nhentai.ui.main.fragment import android.os.Bundle import android.view.View import me.drakeet.multitype.MultiTypeAdapter import moe.feng.nhentai.R import moe.feng.nhentai.databinding.FragmentNewHomeBinding import moe.feng.nhentai.ui.adapter.BookCardBinder import moe.feng.nhentai.ui.common.NHBindingFragment import moe.feng.nhentai.ui.common.setOnLoadMoreListener import moe.feng.nhentai.util.extension.* class HomeFragment: NHBindingFragment<FragmentNewHomeBinding>() { override val LAYOUT_RES_ID: Int = R.layout.fragment_new_home private val adapter by lazy { MultiTypeAdapter().apply { registerOne(BookCardBinder()) } } private val viewModel = HomeViewModel() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding?.vm = viewModel binding?.init() } private fun FragmentNewHomeBinding.init() { recyclerView.adapter = adapter recyclerView.setOnLoadMoreListener(viewModel::onNext) swipeRefreshLayout.setColorSchemeResources(R.color.deep_purple_500) swipeRefreshLayout.setOnRefreshListener(viewModel::onRefresh) } }
app/src/main/kotlin/moe/feng/nhentai/ui/main/fragment/HomeFragment.kt
3469517225
package kodando.react.native import kodando.react.Configurer import kodando.react.unsafelyCreateObject @JsName("createStyle") fun createStyle(): Style = unsafelyCreateObject() @JsName("createStyleAndConfigure") fun createStyle(configure: Configurer<Style>): Style = createStyle().also(configure)
kodando-react-native/src/main/kotlin/kodando/react/native/CreateStyle.kt
1634892302
package lt.vilnius.tvarkau.dagger.module import android.arch.persistence.room.Room import android.os.Debug import dagger.Module import dagger.Provides import lt.vilnius.tvarkau.TvarkauApplication import lt.vilnius.tvarkau.database.AppDatabase import javax.inject.Singleton @Module class DatabaseModule { @Singleton @Provides fun provideDatabase(context: TvarkauApplication): AppDatabase { val builder = Room.databaseBuilder( context, AppDatabase::class.java, "app_database.db" ) .fallbackToDestructiveMigration() if (Debug.isDebuggerConnected()) { builder.allowMainThreadQueries() } return builder.build() } @Singleton @Provides fun provideReportsDao(db: AppDatabase) = db.reportsDao() @Singleton @Provides fun provideReportTypesDao(db: AppDatabase) = db.reportTypesDao() @Singleton @Provides fun provideReportStatusesDao(db: AppDatabase) = db.reportStatusesDao() }
app/src/main/java/lt/vilnius/tvarkau/dagger/module/DatabaseModule.kt
1978716215
package com.nearsoft.pomodorokotlin.timer import android.support.design.widget.FloatingActionButton import android.widget.RadioButton import android.widget.TextView import com.nearsoft.pomodorokotlin.R import org.codehaus.plexus.util.StringUtils import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf import org.robolectric.shadows.support.v4.SupportFragmentTestUtil @RunWith(RobolectricTestRunner::class) class TimerFragmentTest { private lateinit var timerText: TextView private lateinit var breakSmallOption: RadioButton private lateinit var breakLargeOption: RadioButton private lateinit var workOption: RadioButton private lateinit var fab: FloatingActionButton private lateinit var presenter: TimerPresenter @Before fun setup() { presenter = TimerPresenter() val fragment = TimerFragment() SupportFragmentTestUtil.startVisibleFragment(fragment) fragment.setPresenter(presenter) val view = fragment.view!! timerText = view.findViewById(R.id.timerTextView) breakSmallOption = view.findViewById(R.id.breakSmallRadioButton) breakLargeOption = view.findViewById(R.id.breakLargeRadioButton) workOption = view.findViewById(R.id.workRadioButton) fab = view.findViewById(R.id.fab) } @Test fun timerTextShouldHaveAnInitialValue() { assertFalse(StringUtils.isEmpty(timerText.text.toString())) } @Test fun selectingPomodoroShouldChangeText() { breakLargeOption.performClick() assertEquals("05:00", timerText.text) breakSmallOption.performClick() assertEquals("01:00", timerText.text) workOption.performClick() assertEquals("05:00", timerText.text) } @Test fun fabShouldHaveCorrectImageDependingOnState() { // Should begin with play icon var drawable = shadowOf(fab.drawable) Assert.assertEquals(android.R.drawable.ic_media_play, drawable.createdFromResId) presenter.startTimer() drawable = shadowOf(fab.drawable) Assert.assertEquals(android.R.drawable.ic_media_pause, drawable.createdFromResId) presenter.pauseTimer() drawable = shadowOf(fab.drawable) Assert.assertEquals(android.R.drawable.ic_media_play, drawable.createdFromResId) presenter.startTimer() drawable = shadowOf(fab.drawable) Assert.assertEquals(android.R.drawable.ic_media_pause, drawable.createdFromResId) presenter.resetTimer() drawable = shadowOf(fab.drawable) Assert.assertEquals(android.R.drawable.ic_media_play, drawable.createdFromResId) } }
2017/oct/unit-testing/PomodoroKotlin/app/src/test/java/com/nearsoft/pomodorokotlin/timer/TimerFragmentTest.kt
154537430
/* * Copyright 2017 Farbod Salamat-Zadeh * * 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 co.timetableapp.model import android.content.Context import android.database.Cursor import android.os.Parcel import android.os.Parcelable import co.timetableapp.data.TimetableDbHelper import co.timetableapp.data.handler.DataNotFoundException import co.timetableapp.data.schema.TermsSchema import org.threeten.bp.LocalDate /** * Represents a term (or semester) in a student's timetable. * * A `Term` does not have any links with classes, assignments, exams, or any other model except * from the [Timetable] to which it belongs to. This means that [Class]es must set their own start * and end dates. * * @property timetableId the identifier of the [Timetable] this term belongs to * @property name the name for this term (e.g. First Semester, Summer Term, etc.) * @property startDate the start date of this term * @property endDate the end date of this term */ data class Term( override val id: Int, override val timetableId: Int, val name: String, val startDate: LocalDate, val endDate: LocalDate ) : TimetableItem, Comparable<Term> { init { if (startDate.isAfter(endDate)) { throw IllegalArgumentException("the start date cannot be after the end date") } } companion object { /** * Constructs a [Term] using column values from the cursor provided * * @param cursor a query of the terms table * @see [TermsSchema] */ @JvmStatic fun from(cursor: Cursor): Term { val startDate = LocalDate.of( cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_START_DATE_YEAR)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_START_DATE_MONTH)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_START_DATE_DAY_OF_MONTH))) val endDate = LocalDate.of( cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_END_DATE_YEAR)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_END_DATE_MONTH)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_END_DATE_DAY_OF_MONTH))) return Term( cursor.getInt(cursor.getColumnIndex(TermsSchema._ID)), cursor.getInt(cursor.getColumnIndex(TermsSchema.COL_TIMETABLE_ID)), cursor.getString(cursor.getColumnIndex(TermsSchema.COL_NAME)), startDate, endDate) } /** * Creates a [Term] from the [termId] and corresponding data in the database. * * @throws DataNotFoundException if the database query returns no results * @see from */ @JvmStatic @Throws(DataNotFoundException::class) fun create(context: Context, termId: Int): Term { val db = TimetableDbHelper.getInstance(context).readableDatabase val cursor = db.query( TermsSchema.TABLE_NAME, null, "${TermsSchema._ID}=?", arrayOf(termId.toString()), null, null, null) if (cursor.count == 0) { cursor.close() throw DataNotFoundException(this::class.java, termId) } cursor.moveToFirst() val term = Term.from(cursor) cursor.close() return term } @Suppress("unused") @JvmField val CREATOR: Parcelable.Creator<Term> = object : Parcelable.Creator<Term> { override fun createFromParcel(source: Parcel): Term = Term(source) override fun newArray(size: Int): Array<Term?> = arrayOfNulls(size) } } private constructor(source: Parcel) : this( source.readInt(), source.readInt(), source.readString(), source.readSerializable() as LocalDate, source.readSerializable() as LocalDate ) override fun compareTo(other: Term): Int { return startDate.compareTo(other.startDate) } override fun describeContents() = 0 override fun writeToParcel(dest: Parcel?, flags: Int) { dest?.writeInt(id) dest?.writeInt(timetableId) dest?.writeString(name) dest?.writeSerializable(startDate) dest?.writeSerializable(endDate) } }
app/src/main/java/co/timetableapp/model/Term.kt
1792617644
/* * Copyright (c) 2019. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ package nl.adaptivity.process.engine.test.loanOrigination.datatypes import kotlinx.serialization.Serializable @Serializable open class LoanProductBundle(val name: String, val id: String) { fun withPrice(customerId: String, amount: Double, price: Double): PricedLoanProductBundle { return PricedLoanProductBundle( name, id, customerId, amount, price, false ) } override fun toString(): String { return "LoanProductBundle(name='$name', id='$id')" } } @Serializable class PricedLoanProductBundle : LoanProductBundle { val customerId: String val price: Double val approvedOffer: Boolean val amount: Double constructor(name: String, id: String, customerId: String, amount: Double, price: Double, approvedOffer: Boolean) : super(name, id) { this.customerId = customerId this.price = price this.approvedOffer = approvedOffer this.amount = amount } fun approve(): PricedLoanProductBundle { return PricedLoanProductBundle(name, id, customerId, amount, price, true) } override fun toString(): String { return "PricedLoanProductBundle(name='$name', id='$id', customerId='$customerId', price=$price, approvedOffer=$approvedOffer, amount=$amount)" } }
ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/datatypes/LoanProductBundle.kt
1924622666
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.dagger.login import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.example.android.dagger.user.UserManager /** * LoginViewModel is the ViewModel that [LoginActivity] uses to * obtain information of what to show on the screen and handle complex logic. */ class LoginViewModel(private val userManager: UserManager) { private val _loginState = MutableLiveData<LoginViewState>() val loginState: LiveData<LoginViewState> get() = _loginState fun login(username: String, password: String) { if (userManager.loginUser(username, password)) { _loginState.value = LoginSuccess } else { _loginState.value = LoginError } } fun unregister() { userManager.unregister() } fun getUsername(): String = userManager.username }
app/src/main/java/com/example/android/dagger/login/LoginViewModel.kt
3319458302
package jeb import jeb.util.Try import java.io.BufferedReader import java.io.File import java.nio.file.Paths import java.time.LocalDateTime val usage = "Usage: jeb-k <init|backup [--force] <dir>>" fun main(args: Array<String>) { when { args.size == 0 -> println(usage) args[0] == "init" -> init() args[0] == "backup" -> { val force = args[1] == "--force" val dir = if (force) { args[2] } else { args[1] } backup(File(dir), LocalDateTime.now(), force) } else -> println(usage) } } fun init() { val currentDir = System.getProperty("user.dir").withTailingSlash() val sourceDirs = readSourceDirs(currentDir) val backupDirDefault = if (sourceDirs.contains(currentDir)) null else currentDir val backupDir = readLine("Backups directory", backupDirDefault) val disksCount = readLine("Backups count", "10").toInt() val state = State(backupDir, sourceDirs.map(::Source), Hanoi(disksCount)) State.saveState(File(backupDir, "jeb.json"), state) } private fun backup(backupDir: File, time: LocalDateTime, force: Boolean) { var config = File(backupDir, "jeb.json") if (!config.exists()) { config = backupDir } if (!config.exists()) { println("jeb-k config is not found at ${config.absolutePath}") return } val state = State.loadState(config) when (state) { is Try.Success -> doBackup(config, state.result, time, force) is Try.Failure -> println(state.reason.message) } } private fun doBackup(config: File, state: State, time: LocalDateTime, force: Boolean) { try { var excludesFile = Paths.get(state.backupsDir, "excludes.txt") if (!excludesFile.toFile().exists()) { excludesFile = Paths.get(config.parent, "excludes.txt") if (!excludesFile.toFile().exists()) { excludesFile = null } } val newState = Backuper(Storage(), time).doBackup(state, force, excludesFile) when (newState) { is Try.Success -> newState.result?.let { State.saveState(config, it) } is Try.Failure -> log.error(newState.reason) } } catch(e: JebExecException) { log.error(e) } } private fun readSourceDirs(currentDir: String): List<String> { val sources = arrayListOf<String>() var defaultSourceDir: String? = currentDir do { val invitation = if (sources.size == 0) "Source directory (add trailing slash to backup directory content or leave it blank to backup directory)\n" else "Source directory" val source = readLine(invitation, defaultSourceDir) if (source == defaultSourceDir) { defaultSourceDir = null } sources.add(source) } while (readLine("Add another source? [yes/No]", "no").toLowerCase() == "yes") return sources } // Hack for tests: do not recreate buffered reader on each call var inReader: BufferedReader? = null get() { if (field == null) field = System.`in`.bufferedReader() return field } private fun readLine(invitation: String, default: String?): String { val defaultMsg = if (default != null) " [Leave empty to use $default]" else "" print("$invitation$defaultMsg:") val line = inReader!!.readLine() return if (line.length > 0 || default == null) line else default } private fun String.withTailingSlash() = if (this.endsWith("/")) this else this + "/"
src/main/kotlin/jeb/jeb.kt
1918413861
package org.strykeforce.telemetry.grapher import mu.KotlinLogging import okio.Buffer import java.net.DatagramPacket import java.net.DatagramSocket import java.net.InetSocketAddress import java.util.concurrent.Executors import java.util.concurrent.ScheduledExecutorService import java.util.concurrent.TimeUnit.MILLISECONDS private const val PERIOD = 5L // milliseconds private val logger = KotlinLogging.logger {} /** Handles data streaming with Grapher client. */ class ClientHandler(private val port: Int, private val socket: DatagramSocket) { private var scheduler: ScheduledExecutorService? = null /** * Start streaming the `Measurable` items specified in the subscription. * * @param subscription items to stream to client */ fun start(subscription: Subscription) { if (scheduler != null) return val address = InetSocketAddress(subscription.client, port) val packet = DatagramPacket(ByteArray(0), 0, address) val buffer = Buffer() val runnable = { subscription.measurementsToJson(buffer) val bytes = buffer.readByteArray() packet.setData(bytes, 0, bytes.size) socket.send(packet) } scheduler = Executors.newSingleThreadScheduledExecutor().also { it.scheduleAtFixedRate(runnable, 0, PERIOD, MILLISECONDS) } logger.info { "sending graph data to ${subscription.client}:$port" } } /** Stop streaming to client. */ fun shutdown() { scheduler?.let { it.shutdown() } scheduler = null logger.info("stopped streaming graph data") } }
src/main/kotlin/org/strykeforce/telemetry/grapher/ClientHandler.kt
1411106638
/* * Copyright (c) 2017. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the * GNU Lesser General Public License as published by the Free Software Foundation. * * ProcessManager 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 ProcessManager. If not, * see <http://www.gnu.org/licenses/>. */ /** * Generic utility methods for use in kotlin */ package net.devrieze.util inline fun <T> T?.valIfNot(alternate:T, condition:T.()->Boolean):T = if (this!=null && condition()) this else alternate inline fun <T> T.valIf(alternate:T, condition:T.()->Boolean):T = if (condition()) alternate else this inline fun <T> T?.valIfNullOr(alternate:T, condition:T.()->Boolean):T = if (this==null || condition()) alternate else this inline fun <T> T?. nullIfNot(condition:T.()->Boolean):T? = if (this?.condition() == true) this else null interface __Override__<T> { infix fun by(alternative:T):T } class __Override__T<T> : __Override__<T> { override infix fun by(alternative: T):T { return alternative } } class __Override__F<T>(val value:T):__Override__<T> { override infix fun by(alternative: T):T { return value } } inline fun <T> T?.overrideIf(crossinline condition: T.() -> Boolean): __Override__<T> { return if (this==null || condition()) __Override__T() else __Override__F(this) }
darwin/src/commonMain/kotlin/net/devrieze/util/util.kt
1346325667
package com.github.hkokocin.atheris.android import android.os.Bundle import android.support.v4.app.DialogFragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.github.hkokocin.atheris.interactor.DialogFragmentInteractor abstract class ViperDialogFragment : DialogFragment() { abstract val interactor: DialogFragmentInteractor abstract val layout: Int lateinit var lifecycle: FragmentLifecycle override fun onCreate(savedInstanceState: Bundle?) { interactor.router.dialog = this lifecycle = interactor.router.lifecycle super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(layout, container).apply { interactor.presenter.create(this) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) lifecycle.onCreate(savedInstanceState) } override fun onStart() { super.onStart() lifecycle.onStart() } override fun onResume() { super.onResume() lifecycle.onResume() } override fun onPause() { super.onPause() lifecycle.onPause() } override fun onStop() { super.onStop() lifecycle.onStop() } override fun onDestroy() { super.onDestroy() lifecycle.onDestroy() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) lifecycle.onSaveInstanceState(outState) } }
library/src/main/java/com/github/hkokocin/atheris/android/ViperDialogFragment.kt
2809481663
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.kingdom.deploy.gcloud.spanner import org.junit.Rule import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.wfanet.measurement.common.identity.IdGenerator import org.wfanet.measurement.gcloud.spanner.testing.SpannerEmulatorDatabaseRule import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.testing.Schemata import org.wfanet.measurement.kingdom.service.internal.testing.PublicKeysServiceTest @RunWith(JUnit4::class) class SpannerPublicKeysServiceTest : PublicKeysServiceTest<SpannerPublicKeysService>() { @get:Rule val spannerDatabase = SpannerEmulatorDatabaseRule(Schemata.KINGDOM_CHANGELOG_PATH) override fun newServices(idGenerator: IdGenerator): Services<SpannerPublicKeysService> { val spannerServices = SpannerDataServices(clock, idGenerator, spannerDatabase.databaseClient).buildDataServices() return Services( spannerServices.publicKeysService as SpannerPublicKeysService, spannerServices.measurementConsumersService, spannerServices.dataProvidersService, spannerServices.certificatesService, spannerServices.accountsService ) } }
src/test/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/SpannerPublicKeysServiceTest.kt
620901310
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.api.v2alpha import org.wfanet.measurement.common.ResourceNameParser import org.wfanet.measurement.common.api.ResourceKey /** [ResourceKey] of a Measurement Consumer. */ data class MeasurementConsumerKey(val measurementConsumerId: String) : ResourceKey { override fun toName(): String { return parser.assembleName(mapOf(IdVariable.MEASUREMENT_CONSUMER to measurementConsumerId)) } companion object FACTORY : ResourceKey.Factory<MeasurementConsumerKey> { const val COLLECTION_NAME = "measurementConsumers" val defaultValue = MeasurementConsumerKey("") private val parser = ResourceNameParser("$COLLECTION_NAME/{measurement_consumer}") override fun fromName(resourceName: String): MeasurementConsumerKey? { return parser.parseIdVars(resourceName)?.let { MeasurementConsumerKey(it.getValue(IdVariable.MEASUREMENT_CONSUMER)) } } } }
src/main/kotlin/org/wfanet/measurement/api/v2alpha/MeasurementConsumerKey.kt
4105055205
/* * Copyright (C) 2017 The sxxxxxxxxxu's Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.shunwang.accoumanagersample import android.accounts.Account import android.content.AbstractThreadedSyncAdapter import android.content.ContentProviderClient import android.content.Context import android.content.SyncResult import android.os.Bundle /** * SyncAdapter不会自动做数据传输,它只是封装你的代码,以便框架可以在后台调用,而不需要你的应用介入。 * 当同步框架准备要同步应用的数据时候,他会调用 [onPerformSync] * * Created by sxx.xu on 9/29/2017. */ class SyncAdapter(context: Context, boolean: Boolean) : AbstractThreadedSyncAdapter(context, boolean) { private var mContentResolver = context.contentResolver /** * 连接服务器 * 下载上次数据 * 处理数据冲突 * 清理临时文件和缓存 * * @param account 与本次触发事件关联的[Account]对象,如果你的服务器不需要账号,直接无视即可 * @param extras 包含一些标志位的[Bundle] 对象 * @param authority 系统中 ContentProvider ,一般是你自己应用中的 ContentProvider 对应的authority * @param provider authority对应的 [ContentProviderClient],它是ContentProvider的一个轻量接口, * 具有与 ContentResolver 相同的功能。如果是用ContentProvider保存的数据,你可以用这个对象连接到 * ContentProvider,否则无视就好 * @param syncResult 用来将同步的结果传给同步框架 */ override fun onPerformSync(account: Account?, extras: Bundle?, authority: String?, provider: ContentProviderClient?, syncResult: SyncResult?) { //模拟和服务器的交互 } }
accoumanagersample/src/main/java/com/shunwang/accoumanagersample/SyncAdapter.kt
196867909
package nl.hannahsten.texifyidea.index.stub import com.intellij.psi.stubs.* import nl.hannahsten.texifyidea.BibtexLanguage import nl.hannahsten.texifyidea.index.BibtexEntryIndex import nl.hannahsten.texifyidea.psi.BibtexEntry import nl.hannahsten.texifyidea.psi.impl.BibtexEntryImpl open class BibtexEntryStubElementType(debugName: String) : IStubElementType<BibtexEntryStub, BibtexEntry>(debugName, BibtexLanguage) { override fun createPsi(stub: BibtexEntryStub): BibtexEntry { return BibtexEntryImpl(stub, this) } override fun serialize(stub: BibtexEntryStub, dataStream: StubOutputStream) { dataStream.writeName(stub.identifier) dataStream.writeName(stub.title) dataStream.writeName(stub.authors.joinToString(";")) dataStream.writeName(stub.year) } override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): BibtexEntryStub { val name = dataStream.readName()?.string ?: "" val title = dataStream.readName()?.string ?: "" val authors = (dataStream.readName()?.string ?: "").split(";") val year = dataStream.readName()?.string ?: "" return BibtexEntryStubImpl(parentStub, this, name, authors, year, title) } override fun createStub(entry: BibtexEntry, parentStub: StubElement<*>?): BibtexEntryStub { return BibtexEntryStubImpl(parentStub, this, entry.identifier, entry.authors, entry.year, entry.title) } override fun getExternalId() = "ENTRY" override fun indexStub(stub: BibtexEntryStub, sink: IndexSink) { sink.occurrence(BibtexEntryIndex.key, stub.name ?: "") } }
src/nl/hannahsten/texifyidea/index/stub/BibtexEntryStubElementType.kt
1370278559
package com.jamieadkins.gwent.base import android.content.Context import android.util.DisplayMetrics fun Context.convertDpToPixel(dp: Float): Float { val metrics = resources.displayMetrics val px = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT) return px }
base/src/main/java/com/jamieadkins/gwent/base/Extensions.kt
4020350826
package com.github.ykrank.androidtools.ui.adapter.delegate import android.content.Context import androidx.annotation.CallSuper import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import com.hannesdorfmann.adapterdelegates3.AdapterDelegate abstract class LibBaseAdapterDelegate<T, in VH : androidx.recyclerview.widget.RecyclerView.ViewHolder> (context: Context, protected val entityClass: Class<T>? = null) : AdapterDelegate<MutableList<Any>>() { protected val mLayoutInflater: LayoutInflater = LayoutInflater.from(context) public override fun isForViewType(items: MutableList<Any>, position: Int): Boolean { checkNotNull(entityClass, {"Should pass class from constructor , or override getTClass or isForViewType"}) return entityClass == items[position].javaClass } @CallSuper override fun onBindViewHolder(items: MutableList<Any>, position: Int, holder: androidx.recyclerview.widget.RecyclerView.ViewHolder, payloads: List<Any>) { onBindViewHolderData(items[position] as T, position, holder as VH, payloads) } abstract fun onBindViewHolderData(t: T, position: Int, holder: VH, payloads: List<Any>) }
library/src/main/java/com/github/ykrank/androidtools/ui/adapter/delegate/LibBaseAdapterDelegate.kt
2699014164
package com.polito.sismic.Presenters.ReportActivity import android.app.Activity import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import com.polito.sismic.R import kotlinx.android.synthetic.main.activity_note.* //Custom activity to take a note class NoteActivity : AppCompatActivity() { private lateinit var mUserName : String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_note) mUserName = intent.getStringExtra("username") note_save.setOnClickListener { exitWithSuccess() } } private fun exitWithSuccess() { val intent = Intent() intent.putExtra("note", note.text.toString()) setResult(Activity.RESULT_OK, intent) finish() } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (item?.itemId == android.R.id.home) { val intent = Intent() intent.putExtra("username", mUserName) setResult(Activity.RESULT_CANCELED, intent) finish() return true } return false } }
app/src/main/java/com/polito/sismic/Presenters/ReportActivity/NoteActivity.kt
2528183426
package com.hartwig.hmftools.paddle.dnds import com.hartwig.hmftools.paddle.Gene import java.io.File import java.nio.file.Files data class DndsCv(val n: Int, val wCv: Double) { fun expectedDrivers(variantCount: Int): Double { return variantCount * probability(n, wCv) } private fun probability(n: Int, wCv: Double): Double { return if (n > 0) { ((wCv - 1) / wCv).coerceAtLeast(0.0) } else { 0.0 } } } data class DndsCvGene(val gene: Gene, val nSynonymous: Int, val missense: DndsCv, val nonsense: DndsCv, val splice: DndsCv, val indel: DndsCv) { companion object { fun fromFile(file: String): List<DndsCvGene> { return Files.readAllLines(File(file).toPath()).drop(1).map { fromString(it) } } private fun fromString(line: String): DndsCvGene { val lineArray = line.split("\t") return DndsCvGene(lineArray[0], lineArray[1].toInt(), DndsCv(lineArray[2].toInt(), lineArray[6].toDouble()), DndsCv(lineArray[3].toInt(), lineArray[7].toDouble()), DndsCv(lineArray[4].toInt(), lineArray[8].toDouble()), DndsCv(lineArray[5].toInt(), lineArray[9].toDouble())) } } }
paddle/src/main/kotlin/com/hartwig/hmftools/paddle/dnds/Dnds.kt
1470913538
/** * Copyright (C) 2017 Devexperts LLC * * 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/gpl-3.0.html>. */ package com.devexperts.usages.api import com.fasterxml.jackson.annotation.JsonProperty import java.util.* data class Member( @JsonProperty("memberName") val qualifiedMemberName: String, @JsonProperty("paramTypes") val parameterTypes: List<String>, @JsonProperty("type") val type: MemberType ) { fun packageName(): String { if (type == MemberType.PACKAGE) return qualifiedMemberName; val className = className(); val lastDotIndex = className.lastIndexOf('.') return if (lastDotIndex == -1) qualifiedMemberName else qualifiedMemberName.substring(0, lastDotIndex) } fun className() = when (type) { MemberType.PACKAGE -> throw IllegalStateException("Cannot return class name for package member") MemberType.CLASS -> qualifiedMemberName else -> qualifiedMemberName.substring(0, qualifiedMemberName.indexOf('#')) } fun simpleClassName() = simpleNonPackageName(className()) fun simpleName(): String { if (type == MemberType.PACKAGE) return qualifiedMemberName var simpleName = simpleNonPackageName(qualifiedMemberName) if (type == MemberType.METHOD) simpleName += "(${simpleParameters()})" return simpleName } fun simpleMemberName(): String { if (type == MemberType.PACKAGE || type == MemberType.CLASS) throw IllegalStateException("Simple member name is allowed for fields and methods only, current member is $this") var simpleMemberName = qualifiedMemberName.substring(qualifiedMemberName.indexOf("#") + 1) if (type == MemberType.METHOD && !parameterTypes.isEmpty()) simpleMemberName += "(${simpleParameters()})" return simpleMemberName } private fun simpleNonPackageName(qualifiedName: String): String { val lastDotIndex = qualifiedName.lastIndexOf('.') return if (lastDotIndex < 0) qualifiedName else qualifiedName.substring(lastDotIndex + 1) } private fun simpleParameters(): String { val paramsJoiner = StringJoiner(", ") for (p in parameterTypes) { paramsJoiner.add(simpleNonPackageName(p)) } return paramsJoiner.toString() } override fun toString(): String { var res = qualifiedMemberName if (type == MemberType.METHOD) { res = "$res(${simpleParameters()})" } return res } override fun hashCode(): Int { var result = qualifiedMemberName.hashCode() result = 31 * result + parameterTypes.hashCode() result = 31 * result + type.hashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Member if (qualifiedMemberName != other.qualifiedMemberName) return false if (parameterTypes != other.parameterTypes) return false if (type != other.type) return false return true } companion object { fun fromPackage(packageName: String) = Member(packageName, emptyList(), MemberType.PACKAGE) fun fromClass(className: String) = Member(className, emptyList(), MemberType.CLASS) fun fromField(className: String, fieldName: String) = Member( "$className#$fieldName", emptyList(), MemberType.FIELD) fun fromMethod(className: String, methodName: String, parameterTypes: List<String>) = Member( "$className#$methodName", parameterTypes, MemberType.METHOD) } } enum class MemberType constructor(val typeName: String) { PACKAGE("package"), CLASS("class"), METHOD("method"), FIELD("field"); override fun toString(): String { return typeName } } data class MemberUsage( @JsonProperty("member") val member: Member, @JsonProperty("usageKind") val usageKind: UsageKind, @JsonProperty("location") val location: Location ) data class Location( @JsonProperty("artifact") val artifact: Artifact, @JsonProperty("member") val member: Member, // class or method @JsonProperty("file") val file: String?, // content file, do not use it for equals and hashCode! @JsonProperty("line") val lineNumber: Int? // line number of usage in the file ) { init { // if (member.type != MemberType.CLASS && member.type != MemberType.METHOD) // throw IllegalArgumentException("Only methods and classes could be used as location, current member $member") } override fun equals(other: Any?): Boolean { if (this === other) return true if (other?.javaClass != javaClass) return false other as Location if (artifact != other.artifact) return false if (member != other.member) return false if (lineNumber != other.lineNumber) return false return true } override fun hashCode(): Int { var result = artifact.hashCode() result = 31 * result + member.hashCode() if (lineNumber != null) result = 31 * result + lineNumber return result } } data class Artifact( @JsonProperty("groupId") val groupId: String, @JsonProperty("artifactId") val artifactId: String, @JsonProperty("version") val version: String, @JsonProperty("type") val type: String?, @JsonProperty("classifier") val classifier: String? ) { override fun toString() = "$groupId:$artifactId:${type ?: ""}:${classifier ?: ""}:$version" } // Do not rename enum values for backwards compatibility enum class UsageKind constructor(val description: String) { UNCLASSIFIED("Unclassified"), SIGNATURE("Signature"), CLASS_DECLARATION("Class declaration"), EXTEND_OR_IMPLEMENT("Usage in inheritance (extends or implements)"), OVERRIDE("Method overriding"), METHOD_DECLARATION("Method declaration"), METHOD_PARAMETER("Method parameter"), METHOD_RETURN("Method return type"), ANNOTATION("Annotation"), THROW("Throw"), CATCH("Catch"), CONSTANT("Constant"), FIELD("Field"), ASTORE("Local variable"), NEW("New instance"), ANEWARRAY("New array"), CAST("Type cast"), GETFIELD("Read field"), PUTFIELD("Write field"), GETSTATIC("Read static field"), PUTSTATIC("Write static field"), INVOKEVIRTUAL("Invoke virtual method"), INVOKESPECIAL("Invoke special method"), INVOKESTATIC("Invoke static method"), INVOKEINTERFACE("Invoke interface method"), INVOKEDYNAMIC("Invoke dynamic") }
api/src/main/kotlin/com/devexperts/usages/api/Model.kt
3390196020
package yotkaz.thimman.backend.model import yotkaz.thimman.backend.app.JPA_EMPTY_CONSTRUCTOR import javax.persistence.* @Entity data class JobOfferChallenge( @Id @GeneratedValue(strategy = GenerationType.TABLE) var id: Long? = null, @ManyToOne(fetch = FetchType.EAGER) var jobOffer: JobOffer?, @ManyToOne(fetch = FetchType.EAGER) var challenge: Challenge?, @Embedded var challengeAttributes: ChallengeAttributes? = null ) { @Deprecated(JPA_EMPTY_CONSTRUCTOR) constructor() : this( jobOffer = null, challenge = null ) }
thimman-backend/src/main/kotlin/yotkaz/thimman/backend/model/JobOfferChallenge.kt
3546905297
package com.tumpaca.tp.util import android.app.DownloadManager import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Environment import android.util.DisplayMetrics import android.util.Log import com.tumpaca.tp.R import com.tumpaca.tp.activity.MainActivity import com.tumpaca.tp.model.TPRuntime import io.reactivex.Observable import io.reactivex.ObservableEmitter import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import java.net.URL class DownloadUtils { companion object { private const val TAG = "DownloadUtils" // 外部ストレージ許可のダイアログから戻ってきたときにダウンロードを再開するために // 対象の URL をこれに保存しておく。なお、画面が回転されたりしたら復元しないがそれは諦める。 private var urlToSave: String? = null @JvmStatic fun downloadPhoto(url: String): Observable<Bitmap> { return Observable .create { emitter: ObservableEmitter<Bitmap> -> try { val photo = TPRuntime.bitMapCache.getIfNoneAndSet(url) { URL(url).openStream().use { stream -> val options = BitmapFactory.Options() options.inDensity = DisplayMetrics.DENSITY_MEDIUM BitmapFactory.decodeStream(stream, null, options) } } photo?.let { emitter.onNext(it) } emitter.onComplete() } catch (e: Exception) { Log.e("downloadPhoto", e.message.orEmpty(), e) emitter.onError(e) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } @JvmStatic fun downloadGif(url: String): Observable<ByteArray> { return Observable .create { emitter: ObservableEmitter<ByteArray> -> try { val gif = TPRuntime.gifCache.getIfNoneAndSet(url) { URL(url).openStream().use { stream -> stream.readBytes() } } gif?.let { emitter.onNext(gif) } emitter.onComplete() } catch (e: Exception) { Log.e("downloadGif", e.message.orEmpty(), e) emitter.onError(e) } } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } @JvmStatic fun saveImage(activity: MainActivity, url: String) { if (!activity.checkStoragePermissions()) { urlToSave = url activity.requestStoragePermissions() return } val target = Uri.parse(url) val request = DownloadManager.Request(target) val fileName = target.lastPathSegment request.setDescription(activity.resources.getString(R.string.download_image)) request.setTitle(fileName) request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName) request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) val manager = activity.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager? manager?.enqueue(request) Log.d(TAG, "startDownload started... fileName=$fileName,url=$url") } @JvmStatic fun resumeSaveImage(activity: MainActivity) { if (urlToSave != null) { val url: String = urlToSave as String urlToSave = null saveImage(activity, url) } } } }
app/src/main/kotlin/com/tumpaca/tp/util/DownloadUtils.kt
2145027296
package com.ternaryop.photoshelf.tumblr.ui.draft.fragment import android.view.Menu import android.view.MenuItem import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.ternaryop.photoshelf.fragment.BottomMenuListener import com.ternaryop.photoshelf.tumblr.ui.draft.R class DraftRefreshBottomMenuListener( private val draftListFragment: DraftListFragment ) : BottomMenuListener { override val title: String get() = draftListFragment.resources.getString(R.string.refresh) override val menuId: Int get() = R.menu.draft_refresh override fun setupMenu(menu: Menu, sheet: BottomSheetDialogFragment) = Unit override fun onItemSelected(item: MenuItem, sheet: BottomSheetDialogFragment) { when (item.itemId) { R.id.clear_draft_cache -> { draftListFragment.draftCache.clear() draftListFragment.fetchPosts(false) } R.id.reload_draft -> { draftListFragment.fetchPosts(false) } } } }
tumblr-ui-draft/src/main/java/com/ternaryop/photoshelf/tumblr/ui/draft/fragment/DraftRefreshBottomMenuListener.kt
1731031232
package cc.aoeiuv020.pager /** * * Created by AoEiuV020 on 2017.12.07-23:54:07. */ abstract class PagerDrawer : IPagerDrawer { var pager: Pager? = null protected lateinit var backgroundSize: Size protected lateinit var contentSize: Size override fun attach(pager: Pager, backgroundSize: Size, contentSize: Size) { this.pager = pager this.backgroundSize = backgroundSize this.contentSize = contentSize } override fun detach() { this.pager = null } }
pager/src/main/java/cc/aoeiuv020/pager/PagerDrawer.kt
2417903485
package cc.aoeiuv020.panovel.api.site import org.junit.Test class KsswTest : BaseNovelContextText(Kssw::class) { @Test fun search() { search("都市") search("我真不是邪神走狗", "万劫火", "2588") } @Test fun detail() { detail( "2588", "2588", "我真不是邪神走狗", "万劫火", "https://pc.kssw.net/files/article/image/2/2588/2588s.jpg", "", "2020-10-07 01:19:00" ) } @Test fun chapters() { chapters( "2588", "001-欢迎光临", "2588/21098411", null, "255-“季”与A16庄园(第三更)", "2588/24265713", "2020-10-07 01:19:00", 257 ) } @Test fun content() { content( "2588/24265713", "就在胡德与安德曾两人在哲罗姆办么室当中,商量着怎么把自家基地连锅端的时候。另一边,同在中央区的a16号住宅之中,此刻却发生了一件或许将要改变-些什么的事情。a16号住宅,姓季", "费很够,但是你再不去书店拜访,别人就都把羹分完了。季博农把那份文件拿过来翻了翻,心里-惊,眉头皱“这次真理会?”wuhl他的目光不由得移到了桌子的右上角,那里同样也有一模一样类型的纸质文件记录了每一次不同组织、个人和书店的接触,以及各自的结果。最近的一份情报,还是关于太阳神教的建立。在那之前,季博农依靠的还是自己的情报网,但是现在,女儿情报却比自己还要先了", 10 ) } }
api/src/test/java/cc/aoeiuv020/panovel/api/site/KsswTest.kt
861031385
package com.nextfaze.devfun.demo import com.google.android.material.textfield.TextInputEditText val TextInputEditText.value get() = text?.trim() ?: ""
demo/src/main/java/com/nextfaze/devfun/demo/ViewExtensions.kt
848517068
package ademar.study.template.navigation import android.content.Intent import javax.inject.Inject class IntentFactory @Inject constructor() { fun makeIntent() = Intent() }
Template/app/src/main/java/ademar/study/template/navigation/IntentFactory.kt
2015627258
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.device.datatypes class WidgetTestHelper { // TODO Fix tests companion object { /*@JvmStatic private fun newGenWidget(args: Map<String, Any>, widgetGenIndex: Int): Widget { assert(widgetGenIndex >= 1) val genArgs = args.toMutableMap() // @formatter:off genArgs["uid"] = args["uid"] ?: getIdsList(widgetGenIndex).last() genArgs["text"] = args["text"] ?: getTextsList(widgetGenIndex, (0 until widgetGenIndex).map { _ -> genArgs["uid"] as String? ?: "" }).last() genArgs["bounds"] = args["bounds"] ?: getBoundsList(widgetGenIndex).last() genArgs["className"] = args["className"] ?: getClassesList(widgetGenIndex).last() genArgs["enabled"] = args["enabled"] ?: true // @formatter:on return newWidget(genArgs) } @Suppress("UNCHECKED_CAST") @JvmStatic fun newWidgets(widgetCount: Int, packageName: String, props: Map<String, Any>, widgetIdPrefix: String = ""): List<Widget> { assert(widgetCount >= 1) val propIdsList = props["idsList"] val idsList = if ( (propIdsList == null) || (propIdsList as List<String>).isEmpty() ) getIdsList(widgetCount, widgetIdPrefix) else propIdsList val textsList = props["textsList"] as List<String>? ?: getTextsList(widgetCount, idsList) val boundsList = props["boundsList"] as List<List<Int>>? ?: getBoundsList(widgetCount) val classesList = props["classList"] as List<String>? ?: getClassesList(widgetCount) val enabledList = props["enabledList"] as List<Boolean>? ?: (0..widgetCount).map { _ -> true } assert(arrayListOf(idsList, textsList, boundsList, classesList, enabledList).all { it.size == widgetCount }) val widgets = (0 until widgetCount).map { i -> newWidget(mutableMapOf( "uid" to idsList[i], "text" to textsList[i], "bounds" to boundsList[i], "className" to classesList[i], "packageName" to packageName, "clickable" to true, "check" to false, "enabled" to enabledList[i] )) } assert(widgets.size == widgetCount) return widgets } @JvmStatic private fun getIdsList(idsCount: Int, widgetIdPrefix: String = ""): List<String> = (0 until idsCount).map { i -> getNextWidgetId(i, widgetIdPrefix) } @JvmStatic private fun getTextsList(textsCount: Int, widgetIds: List<String>): List<String> { assert(widgetIds.size == textsCount) return (0 until textsCount).map { i -> "txt:uid/${widgetIds[i]}" } } @JvmStatic private fun getClassesList(classesCount: Int): List<String> { val classesList = androidWidgetClassesForTesting return (0 until classesCount).map { index -> val classNameIndex = index % classesList.size classesList[classNameIndex] } } @JvmStatic private fun getBoundsList(boundsCount: Int): List<List<Int>> { var lowX = 5 + getBoundsListCallGen var lowY = 6 + getBoundsListCallGen getBoundsListCallGen++ var highX = lowX + 20 var highY = lowY + 30 val bounds: MutableList<List<Int>> = mutableListOf() (0 until boundsCount).forEach { _ -> bounds.update(arrayListOf(lowX, lowY, highX, highY)) lowX += 25 lowY += 35 highX = lowX + 20 highY = lowY + 30 } return bounds } @JvmStatic private var dummyNameGen = 0 @JvmStatic private var getBoundsListCallGen = 0 @JvmStatic private fun getNextWidgetId(index: Int, widgetIdPrefix: String = ""): String { return if (widgetIdPrefix.isEmpty()) "${index}_uniq${dummyNameGen++}" else "${widgetIdPrefix}_W$index" } @JvmStatic private val androidWidgetClassesForTesting = arrayListOf( "android.view.View", "android.widget.Button", "android.widget.CheckBox", "android.widget.CheckedTextView", "android.widget.CompoundButton", "android.widget.EditText", "android.widget.GridView", "android.widget.ImageButton", "android.widget.ImageView", "android.widget.LinearLayout", "android.widget.ListView", "android.widget.RadioButton", "android.widget.RadioGroup", "android.widget.Spinner", "android.widget.Switch", "android.widget.TableLayout", "android.widget.TextView", "android.widget.ToggleButton" ) @JvmStatic fun newClickableButton(args: MutableMap<String, Any> = HashMap()): Widget { val newArgs: MutableMap<String, Any> = args.toMutableMap() .apply { putAll(hashMapOf("clickable" to true, "check" to true, "enabled" to true)) } return newButton(newArgs) } @JvmStatic private fun newButton(args: Map<String, Any>): Widget { val newArgs: MutableMap<String, Any> = args.toMutableMap() .apply { putAll(hashMapOf("className" to "android.widget.Button")) } return newWidget(newArgs) } @JvmStatic @Suppress("unused") fun newTopLevelWidget(packageName: String): Widget { return newWidget(mapOf("uid" to "topLevelFrameLayout", "packageName" to packageName, "class" to "android.widget.FrameLayout", "bounds" to arrayListOf(0, 0, 800, 1205)) .toMutableMap()) } @JvmStatic fun newClickableWidget(args: MutableMap<String, Any> = HashMap(), widgetGenIndex: Int = 0): Widget { val newArgs: MutableMap<String, Any> = args.toMutableMap() .apply { putAll(hashMapOf("clickable" to true, "enabled" to true)) } return if (widgetGenIndex > 0) newWidget(newArgs) else newGenWidget(newArgs, widgetGenIndex + 1) } @Suppress("UNCHECKED_CAST") @JvmStatic private fun newWidget(args: MutableMap<String, Any>): Widget { val bounds = if (args["bounds"] != null) args["bounds"] as List<Int> else arrayListOf(10, 20, 101, 202) if (args["className"] == null) args["className"] = androidWidgetClassesForTesting[1] assert(bounds.size == 4) assert(bounds[0] < bounds[2]) assert(bounds[1] < bounds[3]) val lowX = bounds[0] val lowY = bounds[1] val highX = bounds[2] val highY = bounds[3] val xpath = "//${args["className"] as String? ?: "fix_cls"}[${(args["index"] as Int? ?: 0) + 1}]" return OldWidget(args["uid"] as String? ?: "", args["index"] as Int? ?: 0, args["text"] as String? ?: "fix_text", args["resourceId"] as String? ?: "fix_resId", args["className"] as String? ?: "fix_cls", args["packageName"] as String? ?: "fix_pkg", args["contentDesc"] as String? ?: "fix_contDesc", args["xpath"] as String? ?: xpath, args["check"] as Boolean? ?: false, args["check"] as Boolean? ?: false, args["clickable"] as Boolean? ?: false, args["enabled"] as Boolean? ?: false, args["focusable"] as Boolean? ?: false, args["focus"] as Boolean? ?: false, args["scrollable"] as Boolean? ?: false, args["longClickable"] as Boolean? ?: false, args["password"] as Boolean? ?: false, args["selected"] as Boolean? ?: false, Rectangle(lowX, lowY, highX - lowX, highY - lowY), null) // @formatter:on }*/ } }
project/pcComponents/core/src/test/kotlin/org/droidmate/device/datatypes/WidgetTestHelper.kt
921343140
package io.github.detekt.metrics.processors import io.gitlab.arturbosch.detekt.api.DetektVisitor import org.jetbrains.kotlin.com.intellij.openapi.util.Key import org.jetbrains.kotlin.psi.KtFile class KtFileCountProcessor : AbstractProjectMetricProcessor() { override val visitor = KtFileCountVisitor() override val key = numberOfFilesKey } val numberOfFilesKey = Key<Int>("number of kt files") class KtFileCountVisitor : DetektVisitor() { override fun visitKtFile(file: KtFile) { file.putUserData(numberOfFilesKey, 1) } }
detekt-metrics/src/main/kotlin/io/github/detekt/metrics/processors/KtFileCountProcessor.kt
3306993048
import io.mockk.verify import org.apollo.game.command.Command import org.apollo.game.model.Animation 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.assertions.contains 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 AnimateCommandTests { @TestMock lateinit var world: World @TestMock lateinit var player: Player @Test fun `Plays the animation provided as input`() { player.privilegeLevel = PrivilegeLevel.MODERATOR world.commandDispatcher.dispatch(player, Command("animate", arrayOf("1"))) verify { player.playAnimation(Animation(1)) } } @Test fun `Help message sent on invalid syntax`() { player.privilegeLevel = PrivilegeLevel.ADMINISTRATOR world.commandDispatcher.dispatch(player, Command("animate", arrayOf("<garbage>"))) verify { player.sendMessage(contains("Invalid syntax")) } } }
game/plugin/cmd/test/AnimateCommandTests.kt
2241147877
package nl.sogeti.android.gpstracker.service.dagger import dagger.Component import nl.sogeti.android.gpstracker.service.integration.ServiceCommanderInterface import nl.sogeti.android.gpstracker.service.integration.ServiceManagerInterface import nl.sogeti.android.gpstracker.service.util.PermissionRequester import javax.inject.Named @Component(modules = [(ServiceModule::class)]) interface ServiceComponent { @Named("providerAuthority") fun providerAuthority(): String @Named("stateBroadcastAction") fun stateBroadcastAction(): String fun serviceManagerInterface(): ServiceManagerInterface fun serviceCommanderInterface(): ServiceCommanderInterface fun inject(injectable: PermissionRequester) }
studio/service/src/main/java/nl/sogeti/android/gpstracker/service/dagger/ServiceComponent.kt
195735915
package com.cout970.magneticraft.features.multiblocks.structures import com.cout970.magneticraft.misc.vector.plus import com.cout970.magneticraft.misc.vector.rotateBox import com.cout970.magneticraft.misc.vector.times import com.cout970.magneticraft.misc.vector.vec3Of import com.cout970.magneticraft.systems.multiblocks.* import com.cout970.magneticraft.systems.tilerenderers.PIXEL import net.minecraft.util.EnumFacing import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Vec3d import net.minecraft.util.text.ITextComponent import com.cout970.magneticraft.features.multiblocks.Blocks as Multiblocks object MultiblockHydraulicPress : Multiblock() { override val name: String = "hydraulic_press" override val size: BlockPos = BlockPos(3, 5, 3) override val scheme: List<MultiblockLayer> override val center: BlockPos = BlockPos(1, 0, 0) init { val I = IgnoreBlockComponent val R = corrugatedIronBlock() val G = grateBlock() val C = copperCoilBlock() val Y = strippedBlock() val U = columnBlock(EnumFacing.UP) val H = columnBlock(EnumFacing.EAST) val M = mainBlockOf(controllerBlock) scheme = yLayers( zLayers( listOf(I, I, I), // y = 4 listOf(H, H, H), listOf(I, I, I)), zLayers( listOf(I, I, I), // y = 3 listOf(U, R, U), listOf(I, I, I)), zLayers( listOf(I, I, I), // y = 2 listOf(U, Y, U), listOf(I, I, I)), zLayers( listOf(G, G, G), // y = 1 listOf(C, R, C), listOf(G, G, G)), zLayers( listOf(G, M, G), // y = 0 listOf(G, G, G), listOf(G, G, G)) ) } override fun getControllerBlock() = Multiblocks.hydraulicPress override fun getGlobalCollisionBoxes(): List<AxisAlignedBB> = hitboxes val hitboxes = listOf( Vec3d(-14.000, 4.000, 1.000) * PIXEL to Vec3d(-3.000, 20.000, 15.000) * PIXEL, Vec3d(2.000, 16.000, 2.000) * PIXEL to Vec3d(14.000, 30.000, 14.000) * PIXEL, Vec3d(2.000, 40.000, 13.000) * PIXEL to Vec3d(14.000, 58.000, 14.000) * PIXEL, Vec3d(0.000, 40.000, 12.000) * PIXEL to Vec3d(3.000, 58.000, 13.000) * PIXEL, Vec3d(0.000, 40.000, 3.000) * PIXEL to Vec3d(3.000, 58.000, 4.000) * PIXEL, Vec3d(2.000, 40.000, 2.000) * PIXEL to Vec3d(14.000, 58.000, 3.000) * PIXEL, Vec3d(-7.000, 44.000, 12.100) * PIXEL to Vec3d(23.000, 47.000, 15.100) * PIXEL, Vec3d(-6.000, 43.000, 12.000) * PIXEL to Vec3d(-3.000, 48.000, 16.000) * PIXEL, Vec3d(-11.000, 20.000, 3.000) * PIXEL to Vec3d(-1.000, 51.000, 13.000) * PIXEL, Vec3d(15.000, 42.000, 4.000) * PIXEL to Vec3d(25.000, 70.000, 12.000) * PIXEL, Vec3d(19.000, 43.000, 12.000) * PIXEL to Vec3d(22.000, 48.000, 16.000) * PIXEL, Vec3d(19.000, 4.000, 1.000) * PIXEL to Vec3d(30.000, 20.000, 15.000) * PIXEL, Vec3d(17.000, 20.000, 3.000) * PIXEL to Vec3d(27.000, 51.000, 13.000) * PIXEL, Vec3d(-11.000, 70.000, 2.000) * PIXEL to Vec3d(27.000, 78.000, 14.000) * PIXEL, Vec3d(-9.000, 42.000, 4.000) * PIXEL to Vec3d(1.000, 70.000, 12.000) * PIXEL, Vec3d(-7.000, 44.000, 0.900) * PIXEL to Vec3d(23.000, 47.000, 3.900) * PIXEL, Vec3d(19.000, 43.000, 0.000) * PIXEL to Vec3d(22.000, 48.000, 4.000) * PIXEL, Vec3d(-6.000, 43.000, 0.000) * PIXEL to Vec3d(-3.000, 48.000, 4.000) * PIXEL, Vec3d(13.000, 40.000, 3.000) * PIXEL to Vec3d(16.000, 58.000, 4.000) * PIXEL, Vec3d(13.000, 40.000, 12.000) * PIXEL to Vec3d(16.000, 58.000, 13.000) * PIXEL, Vec3d(-2.000, 0.000, 3.000) * PIXEL to Vec3d(-1.000, 1.000, 13.000) * PIXEL, Vec3d(17.000, 0.000, 3.000) * PIXEL to Vec3d(18.000, 1.000, 13.000) * PIXEL, Vec3d(27.000, 18.000, 4.000) * PIXEL to Vec3d(31.000, 30.000, 12.000) * PIXEL, Vec3d(31.000, 22.000, 6.000) * PIXEL to Vec3d(32.000, 26.000, 10.000) * PIXEL, Vec3d(3.000, 38.000, 3.000) * PIXEL to Vec3d(13.000, 52.000, 13.000) * PIXEL, Vec3d(6.500, 52.000, 6.500) * PIXEL to Vec3d(9.500, 80.000, 9.500) * PIXEL, Vec3d(-16.000, 0.000, -16.000) * PIXEL to Vec3d(0.000, 4.000, 32.000) * PIXEL, Vec3d(16.000, 0.000, -16.000) * PIXEL to Vec3d(32.000, 4.000, 32.000) * PIXEL, Vec3d(0.000, 12.000, -12.000) * PIXEL to Vec3d(16.000, 20.000, -4.000) * PIXEL, Vec3d(1.000, 11.460, -15.654) * PIXEL to Vec3d(15.000, 14.000, -11.593) * PIXEL, Vec3d(0.000, 0.000, -16.000) * PIXEL to Vec3d(1.000, 20.000, -12.000) * PIXEL, Vec3d(15.000, 0.000, -16.000) * PIXEL to Vec3d(16.000, 20.000, -12.000) * PIXEL, Vec3d(1.000, 19.000, -16.000) * PIXEL to Vec3d(15.000, 20.000, -12.000) * PIXEL, Vec3d(-10.000, 12.000, -11.000) * PIXEL to Vec3d(8.000, 24.000, 27.000) * PIXEL, Vec3d(8.000, 12.000, -11.000) * PIXEL to Vec3d(26.000, 24.000, 27.000) * PIXEL, Vec3d(-12.000, 0.000, -12.000) * PIXEL to Vec3d(8.000, 12.000, 8.000) * PIXEL, Vec3d(8.000, 0.000, -12.000) * PIXEL to Vec3d(28.000, 12.000, 8.000) * PIXEL, Vec3d(8.000, 0.000, 8.000) * PIXEL to Vec3d(28.000, 12.000, 28.000) * PIXEL, Vec3d(-12.000, 0.000, 8.000) * PIXEL to Vec3d(8.000, 12.000, 28.000) * PIXEL, Vec3d(-14.500, 18.000, 4.000) * PIXEL to Vec3d(-10.500, 30.000, 12.000) * PIXEL, Vec3d(-15.500, 22.000, 6.000) * PIXEL to Vec3d(-14.500, 26.000, 10.000) * PIXEL, Vec3d(0.000, 0.000, 24.000) * PIXEL to Vec3d(16.000, 15.000, 32.000) * PIXEL ).map { EnumFacing.SOUTH.rotateBox(vec3Of(0.5), it) + vec3Of(0, 0, 1) } override fun checkExtraRequirements(data: MutableList<BlockData>, context: MultiblockContext): List<ITextComponent> = emptyList() }
src/main/kotlin/com/cout970/magneticraft/features/multiblocks/structures/MultiblockHydraulicPress.kt
1510779002
/*------------------------------------------------------------------------------ ** Ident: Sogeti Smart Mobile Solutions ** Author: rene ** Copyright: (c) 2017 Sogeti Nederland B.V. All Rights Reserved. **------------------------------------------------------------------------------ ** Sogeti Nederland B.V. | No part of this file may be reproduced ** Distributed Software Engineering | or transmitted in any form or by any ** Lange Dreef 17 | means, electronic or mechanical, for the ** 4131 NJ Vianen | purpose, without the express written ** The Netherlands | permission of the copyright holder. *------------------------------------------------------------------------------ * * This file is part of OpenGPSTracker. * * OpenGPSTracker 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. * * OpenGPSTracker 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 OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>. * */ package nl.sogeti.android.gpstracker.ng.features.gpximport import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.databinding.ObservableBoolean import androidx.fragment.app.DialogFragment import androidx.lifecycle.ViewModelProviders import nl.sogeti.android.gpstracker.utils.FragmentResultLambda import nl.sogeti.android.gpstracker.v2.sharedwear.util.observe import nl.sogeti.android.opengpstrack.ng.features.R import nl.sogeti.android.opengpstrack.ng.features.databinding.FragmentImportTracktypeDialogBinding class ImportTrackTypeDialogFragment : DialogFragment() { private lateinit var presenter: ImportTrackTypePresenter fun show(manager: androidx.fragment.app.FragmentManager, tag: String, resultLambda: (String) -> Unit) { val lambdaHolder = FragmentResultLambda<String>() lambdaHolder.resultLambda = resultLambda manager.beginTransaction().add(lambdaHolder, TAG_LAMBDA_FRAGMENT).commit() setTargetFragment(lambdaHolder, 324) super.show(manager, tag) } override fun dismiss() { fragmentManager?.let { fragmentManager -> val fragment = fragmentManager.findFragmentByTag(TAG_LAMBDA_FRAGMENT) if (fragment != null) { fragmentManager.beginTransaction() .remove(fragment) .commit() } } super.dismiss() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) presenter = ViewModelProviders.of(this).get(ImportTrackTypePresenter::class.java) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val binding = DataBindingUtil.inflate<FragmentImportTracktypeDialogBinding>(inflater, R.layout.fragment_import_tracktype_dialog, container, false) val importTrackTypePresenter = ViewModelProviders.of(this).get(ImportTrackTypePresenter::class.java) binding.presenter = importTrackTypePresenter binding.model = presenter.model presenter.model.dismiss.observe { sender -> if (sender is ObservableBoolean && sender.get()) { dismiss() } } binding.fragmentImporttracktypeSpinner.onItemSelectedListener = importTrackTypePresenter.onItemSelectedListener if (targetFragment is FragmentResultLambda<*>) { importTrackTypePresenter.resultLambda = (targetFragment as FragmentResultLambda<String>).resultLambda } presenter = importTrackTypePresenter return binding.root } companion object { private const val TAG_LAMBDA_FRAGMENT = "TAG_LAMBDA_FRAGMENT" } }
studio/features/src/main/java/nl/sogeti/android/gpstracker/ng/features/gpximport/ImportTrackTypeDialogFragment.kt
569568110
package net.nemerosa.ontrack.extension.scm.catalog.ui import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import net.nemerosa.ontrack.extension.scm.catalog.CatalogFixtures import net.nemerosa.ontrack.extension.scm.catalog.CatalogLinkService import net.nemerosa.ontrack.model.structure.ID import net.nemerosa.ontrack.model.structure.NameDescription import net.nemerosa.ontrack.model.structure.Project import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertTrue class SCMCatalogEntryLabelProviderTest { private lateinit var catalogLinkService: CatalogLinkService private lateinit var provider: SCMCatalogEntryLabelProvider private lateinit var project: Project @Before fun init() { project = Project.of(NameDescription.nd("PRJ", "")).withId(ID.of(1)) catalogLinkService = mock() provider = SCMCatalogEntryLabelProvider(catalogLinkService) } @Test fun properties() { assertTrue(provider.isEnabled) assertEquals("SCM Catalog Entry", provider.name) } @Test fun `Label for linked project`() { whenever(catalogLinkService.getSCMCatalogEntry(project)).thenReturn(CatalogFixtures.entry()) val labels = provider.getLabelsForProject(project) assertEquals(1, labels.size) val label = labels.first() with(label) { assertEquals("scm-catalog", category) assertEquals("entry", name) assertEquals("#33cc33", color) } } @Test fun `Label for unlinked project`() { whenever(catalogLinkService.getSCMCatalogEntry(project)).thenReturn(null) val labels = provider.getLabelsForProject(project) assertEquals(1, labels.size) val label = labels.first() with(label) { assertEquals("scm-catalog", category) assertEquals("no-entry", name) assertEquals("#a9a9a9", color) } } }
ontrack-extension-scm/src/test/java/net/nemerosa/ontrack/extension/scm/catalog/ui/SCMCatalogEntryLabelProviderTest.kt
121994270
package com.iyanuadelekan.kanary.app import com.iyanuadelekan.kanary.app.framework.lifecycle.Context import com.iyanuadelekan.kanary.app.router.RouteNode typealias RouterAction = (Context) -> Unit typealias LifeCycleEvent = () -> Unit internal typealias RouteList = ArrayList<RouteNode>
src/main/com/iyanuadelekan/kanary/app/Aliases.kt
1271546015
package net.nemerosa.ontrack.model.support import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.boot.context.properties.ConfigurationProperties import org.springframework.boot.convert.DataSizeUnit import org.springframework.boot.convert.DurationUnit import org.springframework.stereotype.Component import org.springframework.util.unit.DataSize import org.springframework.util.unit.DataUnit import org.springframework.validation.annotation.Validated import java.time.Duration import java.time.temporal.ChronoUnit import javax.annotation.PostConstruct import javax.validation.Valid import javax.validation.constraints.Min /** * Configuration properties for Ontrack. */ @Component @ConfigurationProperties(prefix = OntrackConfigProperties.PREFIX) @Validated class OntrackConfigProperties { private val logger: Logger = LoggerFactory.getLogger(OntrackConfigProperties::class.java) /** * Root URL for this Ontrack location. */ var url: String = "http://localhost:8080" /** * Maximum number of days to keep the log entries */ var applicationLogRetentionDays = 7 /** * Number of fatal errors to notify into the GUI. * * @see ApplicationLogEntryLevel.FATAL */ @Min(1) var applicationLogInfoMax = 10 /** * Maximum number of builds which can be returned by a build filter */ @Min(1) var buildFilterCountMax = 200 /** * Home directory */ var applicationWorkingDir = "work/files" /** * Testing the configurations of external configurations */ var configurationTest = true /** * Job configuration */ @Valid var jobs: JobConfigProperties = JobConfigProperties() /** * Label provider collection job activation */ var jobLabelProviderEnabled = false /** * Search configuration */ var search = SearchConfigProperties() /** * Security configuration */ var security = SecurityProperties() /** * Document storage properties */ var documents = DocumentProperties() /** * Key store settings */ var fileKeyStore = FileKeyStoreProperties() @PostConstruct fun log() { if (!configurationTest) { logger.warn("[config] Tests of external configurations are disabled") } logger.info("[security] Tokens validity: ${security.tokens.validity}") logger.info("[search] Index immediate refresh = ${search.index.immediate}") logger.info("[search] Index batch size = ${search.index.batch}") logger.info("[search] Index batch logging = ${search.index.logging}") logger.info("[search] Index batch tracing = ${search.index.tracing}") logger.info("[search] Index creation error ignoring = ${search.index.ignoreExisting}") logger.info("[document] Documents engine = ${documents.engine}") } /** * File key store settings */ class FileKeyStoreProperties { /** * Directory where to store the secret files. * * If empty, the [applicationWorkingDir] will be used as a root instead. */ var directory: String = "" } /** * Document storage properties */ class DocumentProperties { /** * Engine to be used */ var engine: String = DEFAULT /** * Maximum size */ @DataSizeUnit(DataUnit.KILOBYTES) var maxSize: DataSize = DataSize.ofKilobytes(16) /** * Properties & default values */ companion object { /** * JDBC based */ const val JDBC = "jdbc" /** * Default value */ const val DEFAULT = JDBC } } /** * Security settings */ class SecurityProperties { /** * Security token settings */ val tokens = TokensProperties() } /** * Security token settings */ class TokensProperties { /** * Default validity duration for the tokens. * * If set to 0 or negative, the generated tokens do not expire. * * By default, the tokens do not expire. */ @DurationUnit(ChronoUnit.DAYS) var validity: Duration = Duration.ofDays(0) /** * Allows the token to be used as passwords. */ var password: Boolean = true /** * Cache properties */ var cache = TokensCacheProperties() } /** * Token cache properties */ class TokensCacheProperties { /** * Is caching of the tokens enabled? */ var enabled = true /** * Cache validity period */ @DurationUnit(ChronoUnit.MINUTES) var validity: Duration = Duration.ofDays(30) /** * Maximum number of items in the cache. Should be aligned with the * number of sessions. Note that the objects stored in the cache are tiny. */ var maxCount: Long = 1_000 } companion object { /** * Properties prefix */ const val PREFIX = "ontrack.config" /** * Search service key */ internal const val SEARCH = "search" /** * Documents service key */ internal const val DOCUMENTS = "documents" /** * Documents engine */ const val DOCUMENTS_ENGINE = "$DOCUMENTS.engine" /** * Search complete key */ const val SEARCH_PROPERTY = "$PREFIX.$SEARCH" /** * Key store type */ const val KEY_STORE = "ontrack.config.key-store" } }
ontrack-model/src/main/java/net/nemerosa/ontrack/model/support/OntrackConfigProperties.kt
2792416263