content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
interface Z {
open fun foo(a: Int, b: Int)
}
open class A {
open fun foo(a: Int, b: Int) {
}
}
open class B: A(), Z {
override fun foo(a: Int, b: Int) {
}
}
class C: A() {
override fun foo(a: Int, b: Int) {
}
}
class D: B(), Z {
override fun foo(<caret>a: Int, b: Int) {
}
}
class U {
fun bar(a: A) {
a.foo(1, 2)
}
fun bar(b: B) {
b.foo(3, 4)
}
fun bar(c: C) {
c.foo(5, 6)
}
fun bar(d: D) {
d.foo(7, 8)
}
fun bar(z: Z) {
z.foo(9, 10)
}
} | plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteValueParameter/kotlinValueParameter/hierarchyWithSafeUsages5.kt | 559877733 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.spellchecker.grazie.dictionary
import ai.grazie.spell.lists.WordList
import ai.grazie.spell.utils.Distances
import com.intellij.util.containers.CollectionFactory
import kotlin.collections.LinkedHashSet
class SimpleWordList(private val container: Set<String>) : WordList {
companion object {
const val MAX_LEVENSHTEIN_DISTANCE = 3
}
private val invariants = container.mapTo(CollectionFactory.createSmallMemoryFootprintSet()) { it.lowercase() }
override fun contains(word: String, caseSensitive: Boolean): Boolean {
return if (caseSensitive) container.contains(word) else invariants.contains(word.lowercase())
}
override fun suggest(word: String) = container.filterTo(LinkedHashSet()) {
Distances.levenshtein.distance(it, word, MAX_LEVENSHTEIN_DISTANCE + 1) <= MAX_LEVENSHTEIN_DISTANCE
}
}
| spellchecker/src/com/intellij/spellchecker/grazie/dictionary/SimpleWordList.kt | 1984586184 |
/*
* Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package com.intellij.openapi.updateSettings.impl
import com.intellij.openapi.components.BaseState
import com.intellij.util.xmlb.annotations.CollectionBean
import com.intellij.util.xmlb.annotations.OptionTag
internal class UpdateOptions : BaseState() {
@get:CollectionBean
val pluginHosts by list<String>()
@get:CollectionBean
val ignoredBuildNumbers by list<String>()
@get:CollectionBean
val enabledExternalComponentSources by list<String>()
@get:CollectionBean
val knownExternalComponentSources by list<String>()
@get:CollectionBean
val externalUpdateChannels by map<String, String>()
@get:OptionTag("CHECK_NEEDED")
var isCheckNeeded by property(false)
@get:OptionTag("LAST_TIME_CHECKED")
var lastTimeChecked by property(0L)
@get:OptionTag("LAST_BUILD_CHECKED")
var lastBuildChecked by string()
@get:OptionTag("UPDATE_CHANNEL_TYPE")
var updateChannelType by string(ChannelStatus.RELEASE.code)
@get:OptionTag("SECURE_CONNECTION")
var isUseSecureConnection by property(true)
} | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateOptions.kt | 3538877040 |
/*
* Copyright 2016-2021 Julien Guerinet
*
* 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.guerinet.room
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
/**
* Logs a date/time the app was updates
* @author Julien Guerinet
* @since 4.4.0
*
* @param version App version that the user has updated to
* @param timestamp Date/time that the user has updated to this version, defaults to now
* @param id Auto-generated Id
*/
@Entity
data class AppUpdate(
val version: String,
val timestamp: Instant = Clock.System.now(),
@PrimaryKey(autoGenerate = true) val id: Int = 0
) {
companion object {
/**
* Saves an [AppUpdate] with the [name] and [code] to the Db using the [updateDao]
*/
fun log(updateDao: UpdateDao, name: String, code: Int) =
updateDao.insert(AppUpdate(getVersion(name, code)))
/**
* Returns the version String to use for the app [name] and [code]
*/
fun getVersion(name: String, code: Int): String = "$name ($code)"
}
}
| room/src/main/java/AppUpdate.kt | 1288474259 |
impor<caret> | plugins/kotlin/completion/tests/testData/handlers/keywords/SpaceAfterImport.kt | 2388736611 |
package com.psenchanka.comant.dto
import com.psenchanka.comant.model.User
class DetailedUserDto(
username: String,
firstname: String,
lastname: String,
role: String,
var instructedCourses: List<BasicCourseDto>,
var listenedCourses: List<BasicCourseDto>)
: BasicUserDto(username, firstname, lastname, role) {
companion object {
fun from(user: User) = DetailedUserDto(
user.username,
user.firstname,
user.lastname,
user.role.toString().toLowerCase(),
user.coursesInstructed.map { BasicCourseDto.from(it) },
user.coursesListened.map { BasicCourseDto.from(it) });
}
} | comant-site/src/main/kotlin/com/psenchanka/comant/dto/DetailedUserDto.kt | 2530194231 |
inline class InlineClass(val x: Int) : IFace {
override fun <caret>foo() {}
} | plugins/kotlin/idea/tests/testData/multiFileLocalInspections/unusedSymbol/inlineClassesImplInterface/before/test.kt | 650338948 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.injection.general
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.psi.PsiElement
import org.jetbrains.annotations.ApiStatus
/**
* Checks additional preconditions on IntelliLang injection configured via config XML.
* Implement it when you need to insert a chameleon injection that uses different language depending on additional arguments or parameters.
*/
@ApiStatus.Experimental
interface LanguageInjectionCondition {
/**
* @return ID that should be set to injections condition-id attribute
*/
fun getId(): String
/**
* @param injection settings including language
* @param target place where injection is detected by element pattern, often it is injection host or variable containing actual code
* @return false to prevent injection for target
*/
fun isApplicable(injection: Injection, target: PsiElement): Boolean
companion object {
@JvmField
val EP_NAME: ExtensionPointName<LanguageInjectionCondition> = ExtensionPointName.create("com.intellij.languageInjectionCondition")
}
} | platform/core-api/src/com/intellij/lang/injection/general/LanguageInjectionCondition.kt | 2196587083 |
package one.two
fun write() {
KotlinObject.Nested.isVariable = 4
} | plugins/kotlin/refIndex/tests/testData/compilerIndex/properties/fromObject/nestedObject/isVariable/Write.kt | 2743014468 |
// "Import" "true"
// ERROR: Unresolved reference: Delegates
// WITH_STDLIB
package testing
fun foo() {
val d = <caret>Delegates()
} | plugins/kotlin/idea/tests/testData/quickfix/autoImports/sameModuleImportPriority.before.Main.kt | 2340375756 |
package bj.vinylbrowser.release
import bj.vinylbrowser.model.listing.ScrapeListing
/**
* Created by Josh Laird on 19/05/2017.
*/
object ScrapeListFactory {
@JvmStatic fun buildOneEmptyScrapeListing(): List<ScrapeListing> {
return listOf(buildScrapeListing("", "", "", "", "", "", "", "", ""))
}
@JvmStatic fun buildFourEmptyScrapeListing(): List<ScrapeListing> {
return listOf(buildScrapeListing("scrapeListingPrice1", "", "", "", "", "", "", "", "marketplaceId1"),
buildScrapeListing("scrapeListingPrice2", "", "", "", "", "", "", "", "marketplaceId2"),
buildScrapeListing("scrapeListingPrice3", "", "", "", "", "", "", "", "marketplaceId3"),
buildScrapeListing("scrapeListingPrice4", "", "", "", "", "", "", "", "marketplaceId4"))
}
private fun buildScrapeListing(price: String, convertedPrice: String, mediaCondition: String,
sleeveCondition: String, sellerUrl: String, sellerName: String, sellerRating: String,
shipsFrom: String, marketPlaceId: String): ScrapeListing {
return ScrapeListing(price, convertedPrice, mediaCondition, sleeveCondition, sellerUrl,
sellerName, sellerRating, shipsFrom, marketPlaceId)
}
} | app/src/testShared/bj/vinylbrowser/release/ScrapeListFactory.kt | 3860986533 |
// GENERATE
package com.fkorotkov.kubernetes.certificates.v1
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequest as v1_CertificateSigningRequest
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestCondition as v1_CertificateSigningRequestCondition
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestList as v1_CertificateSigningRequestList
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestSpec as v1_CertificateSigningRequestSpec
import io.fabric8.kubernetes.api.model.certificates.v1.CertificateSigningRequestStatus as v1_CertificateSigningRequestStatus
fun newCertificateSigningRequest(block : v1_CertificateSigningRequest.() -> Unit = {}): v1_CertificateSigningRequest {
val instance = v1_CertificateSigningRequest()
instance.block()
return instance
}
fun newCertificateSigningRequestCondition(block : v1_CertificateSigningRequestCondition.() -> Unit = {}): v1_CertificateSigningRequestCondition {
val instance = v1_CertificateSigningRequestCondition()
instance.block()
return instance
}
fun newCertificateSigningRequestList(block : v1_CertificateSigningRequestList.() -> Unit = {}): v1_CertificateSigningRequestList {
val instance = v1_CertificateSigningRequestList()
instance.block()
return instance
}
fun newCertificateSigningRequestSpec(block : v1_CertificateSigningRequestSpec.() -> Unit = {}): v1_CertificateSigningRequestSpec {
val instance = v1_CertificateSigningRequestSpec()
instance.block()
return instance
}
fun newCertificateSigningRequestStatus(block : v1_CertificateSigningRequestStatus.() -> Unit = {}): v1_CertificateSigningRequestStatus {
val instance = v1_CertificateSigningRequestStatus()
instance.block()
return instance
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/kubernetes/certificates/v1/ClassBuilders.kt | 2819318379 |
package stan.androiddemo.project.petal.Module.ImageDetail
import android.Manifest
import android.animation.ObjectAnimator
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.drawable.Animatable
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.os.Environment
import android.support.design.widget.FloatingActionButton
import android.support.graphics.drawable.AnimatedVectorDrawableCompat
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.facebook.drawee.controller.BaseControllerListener
import com.facebook.imagepipeline.image.ImageInfo
import kotlinx.android.synthetic.main.activity_petal_image_detail.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import rx.Observable
import rx.Subscriber
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import stan.androiddemo.R
import stan.androiddemo.project.petal.API.OperateAPI
import stan.androiddemo.project.petal.Base.BasePetalActivity
import stan.androiddemo.project.petal.Config.Config
import stan.androiddemo.project.petal.Event.OnDialogInteractionListener
import stan.androiddemo.project.petal.Event.OnImageDetailFragmentInteractionListener
import stan.androiddemo.project.petal.HttpUtiles.RetrofitClient
import stan.androiddemo.project.petal.Model.PinsMainInfo
import stan.androiddemo.project.petal.Module.BoardDetail.BoardDetailActivity
import stan.androiddemo.project.petal.Module.UserInfo.PetalUserInfoActivity
import stan.androiddemo.project.petal.Observable.AnimatorOnSubscribe
import stan.androiddemo.project.petal.Widget.GatherDialogFragment
import stan.androiddemo.tool.AnimatorUtils
import stan.androiddemo.tool.CompatUtils
import stan.androiddemo.tool.ImageLoad.ImageLoadBuilder
import stan.androiddemo.tool.Logger
import stan.androiddemo.tool.SPUtils
import java.io.File
import java.util.*
import java.util.concurrent.TimeUnit
class PetalImageDetailActivity : BasePetalActivity(), OnDialogInteractionListener,OnImageDetailFragmentInteractionListener {
private val KEYPARCELABLE = "Parcelable"
private var mActionFrom: Int = 0
lateinit var mPinsBean:PinsMainInfo
lateinit var mImageUrl: String//图片地址
lateinit var mImageType: String//图片类型
lateinit var mPinsId: String
private var isLike = false//该图片是否被喜欢操作 默认false 没有被操作过
private var isGathered = false//该图片是否被采集过
var arrBoardId:List<String>? = null
lateinit var mDrawableCancel: Drawable
lateinit var mDrawableRefresh: Drawable
override fun getTag(): String {return this.toString() }
companion object {
val ACTION_KEY = "key"//key值
val ACTION_DEFAULT = -1//默认值
val ACTION_THIS = 0//来自自己的跳转
val ACTION_MAIN = 1//来自主界面的跳转
val ACTION_MODULE = 2//来自模块界面的跳转
val ACTION_BOARD = 3//来自画板界面的跳转
val ACTION_ATTENTION = 4//来自我的关注界面的跳转
val ACTION_SEARCH = 5//来自搜索界面的跳转
fun launch(activity:Activity){
val intent = Intent(activity,PetalImageDetailActivity::class.java)
activity.startActivity(intent)
}
fun launch(activity: Activity,action:Int){
val intent = Intent(activity,PetalImageDetailActivity::class.java)
intent.putExtra("action",action)
activity.startActivity(intent)
}
}
override fun getLayoutId(): Int {
return R.layout.activity_petal_image_detail
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//注册eventbus
setSupportActionBar(toolbar)
title = ""
toolbar.setNavigationOnClickListener { onBackPressed() }
EventBus.getDefault().register(this)
mActionFrom = intent.getIntExtra("action",ACTION_DEFAULT)
recoverData(savedInstanceState)
mDrawableCancel = CompatUtils.getTintDrawable(mContext,R.drawable.ic_cancel_black_24dp,Color.GRAY)
mDrawableRefresh = CompatUtils.getTintDrawable(mContext,R.drawable.ic_refresh_black_24dp,Color.GRAY)
mImageUrl = mPinsBean.file!!.key!!
mImageType = mPinsBean.file!!.type!!
mPinsId = mPinsBean.pin_id.toString()
isLike = mPinsBean.liked
img_image_detail_bg.aspectRatio = mPinsBean.imgRatio
supportFragmentManager.beginTransaction().replace(R.id.frame_layout_petal_with_refresh,
PetalImageDetailFragment.newInstance(mPinsId)).commit()
addSubscription(getGatherInfo())
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putParcelable(KEYPARCELABLE,mPinsBean)
}
fun recoverData(savedInstanceState:Bundle?){
if (savedInstanceState != null){
if (savedInstanceState!!.getParcelable<PinsMainInfo>(KEYPARCELABLE)!=null){
mPinsBean = savedInstanceState!!.getParcelable<PinsMainInfo>(KEYPARCELABLE)
}
}
}
override fun initResAndListener() {
super.initResAndListener()
fab_image_detail.setImageResource(R.drawable.ic_camera_white_24dp)
fab_image_detail.setOnClickListener {
showGatherDialog()
}
}
@Subscribe(sticky = true)
fun onEventReceiveBean(bean: PinsMainInfo) {
//接受EvenBus传过来的数据
Logger.d(TAG + " receive bean")
this.mPinsBean = bean
}
override fun onResume() {
super.onResume()
showImage()
}
fun showImage(){
var objectAnimator: ObjectAnimator? = null
if (mImageType.toLowerCase().contains("fig")){
objectAnimator = AnimatorUtils.getRotationFS(fab_image_detail)
objectAnimator?.start()
}
val url = String.format(mFormatImageUrlBig,mImageUrl)
val url_low = String.format(mFormatImageGeneral,mImageUrl)
ImageLoadBuilder.Start(mContext,img_image_detail_bg,url).setUrlLow(url_low)
.setRetryImage(mDrawableRefresh)
.setFailureImage(mDrawableCancel)
.setControllerListener(object:BaseControllerListener<ImageInfo>(){
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
super.onFinalImageSet(id, imageInfo, animatable)
Logger.d("onFinalImageSet"+Thread.currentThread().toString())
if (animatable != null){
animatable.start()
}
if (objectAnimator!= null && objectAnimator!!.isRunning){
img_image_detail_bg.postDelayed(Runnable {
objectAnimator?.cancel()
},600)
}
}
override fun onSubmit(id: String?, callerContext: Any?) {
super.onSubmit(id, callerContext)
Logger.d("onSubmit"+Thread.currentThread().toString())
}
override fun onFailure(id: String?, throwable: Throwable?) {
super.onFailure(id, throwable)
Logger.d(throwable.toString())
}
}).build()
}
override fun onClickPinsItemImage(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalImageDetailActivity,PetalImageDetailActivity.ACTION_THIS)
}
override fun onClickPinsItemText(bean: PinsMainInfo, view: View) {
PetalImageDetailActivity.launch(this@PetalImageDetailActivity,PetalImageDetailActivity.ACTION_THIS)
}
override fun onClickBoardField(key: String, title: String) {
BoardDetailActivity.launch(this, key, title)
}
override fun onClickUserField(key: String, title: String) {
PetalUserInfoActivity.launch(this, key, title)
}
override fun onClickImageLink(link: String) {
val uri = Uri.parse(link)
val int = Intent(Intent.ACTION_VIEW,uri)
if (int.resolveActivity([email protected]) != null){
startActivity(int)
}
else{
Logger.d("checkResolveIntent = null")
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.petal_image_detail_menu,menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu?): Boolean {
setMenuIconLikeDynamic(menu?.findItem(R.id.action_like),isLike)
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item!!.itemId){
android.R.id.home->{
//这里原代码有一个逻辑要处理
}
R.id.action_like->{
actionLike(item)
}
R.id.action_download->{
downloadItem()
}
R.id.action_gather->{
showGatherDialog()
}
}
return true
}
fun setMenuIconLikeDynamic(item:MenuItem?,like:Boolean){
val drawableCompat = if (like) AnimatedVectorDrawableCompat.create(mContext
,R.drawable.drawable_animation_petal_favorite_undo) else AnimatedVectorDrawableCompat.create(mContext
,R.drawable.drawable_animation_petal_favorite_do)
item?.icon = drawableCompat
}
fun downloadItem(){
if (ContextCompat.checkSelfPermission(this@PetalImageDetailActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this@PetalImageDetailActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),1)
return
}
object: AsyncTask<String, Int, File?>(){
override fun doInBackground(vararg p0: String?): File? {
var file: File? = null
try {
val url = String.format(mFormatImageUrlBig,mImageUrl)
val future = Glide.with(this@PetalImageDetailActivity).load(url).downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
file = future.get()
val pictureFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).absoluteFile
val fileDir = File(pictureFolder,"Petal")
if (!fileDir.exists()){
fileDir.mkdir()
}
val fileName = System.currentTimeMillis().toString() + ".jpg"
val destFile = File(fileDir,fileName)
file.copyTo(destFile)
sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(File(destFile.path))))
}
catch (e:Exception){
e.printStackTrace()
}
return file
}
override fun onPreExecute() {
Toast.makeText(this@PetalImageDetailActivity,"保存图片成功", Toast.LENGTH_LONG).show()
}
}.execute()
}
fun actionLike(menu: MenuItem){
if (!isLogin){
toast("请先登录再操作")
return
}
val operation = if (isLike) Config.OPERATEUNLIKE else Config.OPERATELIKE
RetrofitClient.createService(OperateAPI::class.java).httpsLikeOperate(mAuthorization,mPinsId,operation)
.subscribeOn(Schedulers.io())
.delay(600, TimeUnit.MILLISECONDS)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object:Subscriber<LikePinsOperateBean>(){
override fun onStart() {
super.onStart()
menu.isEnabled = false
(menu.icon as AnimatedVectorDrawableCompat)?.start()
}
override fun onCompleted() {
menu.isEnabled = true
}
override fun onNext(t: LikePinsOperateBean?) {
isLike = !isLike
setMenuIconLikeDynamic(menu,isLike)
}
override fun onError(e: Throwable?) {
menu.isEnabled = true
checkException(e!!,appBarLayout_image_detail)
}
})
}
fun showGatherDialog(){
if (!isLogin){
toast("请先登录再操作")
return
}
val arrayBoardTitle = SPUtils.get(mContext,Config.BOARDTILTARRAY,"") as String
val boardId = SPUtils.get(mContext,Config.BOARDIDARRAY,"") as String
val arr = arrayBoardTitle?.split(",")
arrBoardId = boardId?.split(",")
val fragment = GatherDialogFragment.create(mAuthorization,mPinsId,mPinsBean.raw_text!!, ArrayList(arr))
fragment.show(supportFragmentManager,null)
}
fun getGatherInfo(): Subscription {
return RetrofitClient.createService(OperateAPI::class.java).httpsGatherInfo(mAuthorization,mPinsId,true)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object:Subscriber<GatherInfoBean>(){
override fun onNext(t: GatherInfoBean?) {
if (t?.exist_pin != null){
setFabDrawableAnimator(R.drawable.ic_done_white_24dp,fab_image_detail)
isGathered = !isGathered
}
}
override fun onError(e: Throwable?) {
}
override fun onCompleted() {
}
})
}
override fun onDialogClick(option: Boolean, info: HashMap<String, Any>) {
if (option){
val desc = info["describe"] as String
val position = info["position"] as Int
val animation = AnimatorUtils.getRotationAD(fab_image_detail)
Observable.create(AnimatorOnSubscribe(animation)).observeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
.flatMap {
RetrofitClient.createService(OperateAPI::class.java).httpsGatherPins(mAuthorization,arrBoardId!![position],desc,mPinsId)
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe(object :Subscriber<GatherResultBean>(){
override fun onNext(t: GatherResultBean?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onError(e: Throwable?) {
checkException(e!!,appBarLayout_image_detail)
setFabDrawableAnimator(R.drawable.ic_done_white_24dp,fab_image_detail)
}
override fun onCompleted() {
setFabDrawableAnimator(R.drawable.ic_report_white_24dp,fab_image_detail)
isGathered = !isGathered
}
})
}
}
fun setFabDrawableAnimator(resId:Int,mFabActionBtn:FloatingActionButton){
mFabActionBtn.hide(object:FloatingActionButton.OnVisibilityChangedListener(){
override fun onHidden(fab: FloatingActionButton?) {
super.onHidden(fab)
fab?.setImageResource(resId)
fab?.show()
}
})
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
}
| app/src/main/java/stan/androiddemo/project/petal/Module/ImageDetail/PetalImageDetailActivity.kt | 2691671243 |
package ch.rmy.android.http_shortcuts.activities.editor.advancedsettings
import ch.rmy.android.framework.viewmodel.ViewModelEvent
import ch.rmy.android.http_shortcuts.data.dtos.VariablePlaceholder
abstract class AdvancedSettingsEvent : ViewModelEvent() {
data class InsertVariablePlaceholder(val variablePlaceholder: VariablePlaceholder) : AdvancedSettingsEvent()
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/advancedsettings/AdvancedSettingsEvent.kt | 3915722323 |
package cz.filipproch.reactor.ui
import cz.filipproch.reactor.base.view.ReactorUiEvent
import cz.filipproch.reactor.ui.events.TestEvent
import cz.filipproch.reactor.util.FakeReactorView
import cz.filipproch.reactor.util.TestTranslator
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
/**
* @author Filip Prochazka (@filipproch)
*/
class ReactorViewHelperTest {
private var reactorView: FakeReactorView? = null
private var viewHelper: ReactorViewHelper<TestTranslator>? = null
@Before
fun prepareViewHelper() {
reactorView = FakeReactorView()
viewHelper = ReactorViewHelper(checkNotNull(reactorView))
}
@Test
fun onReadyToRegisterEmittersTest() {
assertThat(reactorView?.onEmittersInitCalled).isFalse()
viewHelper?.onReadyToRegisterEmitters()
assertThat(reactorView?.onEmittersInitCalled).isTrue()
}
@Test
fun registerEmitterTest() {
var emitterSubscribed = false
val emitter = Observable.create<ReactorUiEvent> {
emitterSubscribed = true
it.onComplete()
}
reactorView?.setOnEmittersInitCallback {
viewHelper?.registerEmitter(emitter)
}
viewHelper?.onReadyToRegisterEmitters()
assertThat(emitterSubscribed).isTrue()
}
@Test(expected = ReactorViewHelper.IllegalLifecycleOperation::class)
fun registerEmitterAtInvalidTimeTest() {
val emitter = Observable.create<ReactorUiEvent> {
it.onComplete()
}
viewHelper?.registerEmitter(emitter)
}
@Test
fun translatorUnbindViewCalledInOnViewNotUsable() {
// prepare for the test
val emitter = PublishSubject.create<ReactorUiEvent>()
reactorView?.setOnEmittersInitCallback {
viewHelper?.registerEmitter(emitter)
}
viewHelper?.onReadyToRegisterEmitters()
val translator = TestTranslator()
translator.onCreated()
viewHelper?.bindTranslatorWithView(translator)
// the test
// emit an event
emitter.onNext(TestEvent)
// it should arrive, alone
assertThat(translator.receivedEvents).hasSize(1)
// clear all received events
translator.receivedEvents.clear()
viewHelper?.onViewNotUsable()
// emit an event
emitter.onNext(TestEvent)
assertThat(translator.receivedEvents).hasSize(0)
// rebind view
viewHelper?.bindTranslatorWithView(translator)
// emit an event
emitter.onNext(TestEvent)
// single event should arrive
assertThat(translator.receivedEvents).hasSize(2)
}
@Test
fun eventsAreDeliveredToTranslatorAfterUnbindAndRebind() {
// prepare for the test
val emitter = PublishSubject.create<ReactorUiEvent>()
reactorView?.setOnEmittersInitCallback {
viewHelper?.registerEmitter(emitter)
}
viewHelper?.onReadyToRegisterEmitters()
val translator = TestTranslator()
translator.onCreated()
viewHelper?.bindTranslatorWithView(translator)
// the test
viewHelper?.onViewNotUsable()
// emit an event
emitter.onNext(TestEvent)
viewHelper?.bindTranslatorWithView(translator)
// single event should arrive
assertThat(translator.receivedEvents).hasSize(1)
}
} | library/src/test/java/cz/filipproch/reactor/ui/ReactorViewHelperTest.kt | 2684713145 |
package com.dreampany.framework.api.receiver
import com.dreampany.framework.misc.AppExecutors
import dagger.android.AndroidInjector
import dagger.android.DaggerBroadcastReceiver
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import javax.inject.Inject
/**
* Created by Roman-372 on 2/8/2019
* Copyright (c) 2019 bjit. All rights reserved.
* [email protected]
* Last modified $file.lastModified
*/
abstract class BaseReceiver : DaggerBroadcastReceiver(), HasAndroidInjector {
@Inject
internal lateinit var receiverInjector: DispatchingAndroidInjector<Any>
@Inject
protected lateinit var ex: AppExecutors
override fun androidInjector(): AndroidInjector<Any> {
return receiverInjector
}
}
| frame/src/main/kotlin/com/dreampany/framework/api/receiver/BaseReceiver.kt | 852295043 |
/*
* MIT License
*
* Copyright (c) 2018 atlarge-research
*
* 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.atlarge.opendc.model.odc.platform
import com.atlarge.opendc.model.odc.integration.csv.Sc18CsvWriter
import com.atlarge.opendc.model.odc.integration.jpa.converter.SchedulerConverter
import com.atlarge.opendc.model.odc.integration.jpa.schema.Experiment
import com.atlarge.opendc.model.odc.integration.jpa.schema.ExperimentState
import com.atlarge.opendc.model.odc.integration.jpa.schema.Path
import com.atlarge.opendc.model.odc.integration.jpa.schema.Simulation
import com.atlarge.opendc.model.odc.integration.jpa.schema.Trace
import java.io.Closeable
import java.time.LocalDateTime
import javax.persistence.EntityManager
import javax.persistence.EntityManagerFactory
import kotlin.coroutines.experimental.buildSequence
/**
* This class manages the experiments that are run for the SC18 paper: A Reference Architecture for Datacenter
* Scheduling.
*
* The amount experiments generated is based on the schedulers to test, the amount of repeats per scheduler and the
* amount of warm-up passes.
*
* @property factory The [EntityManagerFactory] in which the data of the experiments is stored.
* @property schedulers The schedulers to simulate.
* @property writer The csv writer to use.
* @property trace The trace to use represented by its identifier.
* @property path The path to use represented by its identifier.
* @property repeat The amount of times to repeat a simulation for a scheduler.
* @property warmUp The amount of warm up passes.
*/
class Sc18ExperimentManager(
private val factory: EntityManagerFactory,
private val writer: Sc18CsvWriter,
private val schedulers: List<String>,
private val trace: Int,
private val path: Int,
private val repeat: Int,
private val warmUp: Int
) : Closeable {
/**
* The internal entity manager for persisting the experiments.
*/
private val manager: EntityManager = factory.createEntityManager()
/**
* The [SchedulerConverter] to use.
*/
private val schedulerConverter = SchedulerConverter()
/**
* A [Sequence] consisting of the generated experiments.
*/
val experiments: Sequence<Sc18Experiment> = buildSequence {
for (scheduler in schedulers) {
val range = 0 until repeat + warmUp
yieldAll(range.map { buildExperiment(scheduler, it) })
}
}
/**
* Build an [Sc18Experiment] for the given scheduler identified by string.
*
* @param schedulerName The scheduler to create an experiment for.
* @param i The index of the experiment.
*/
private fun buildExperiment(schedulerName: String, i: Int): Sc18Experiment {
val isWarmUp = i < warmUp
val name = if (isWarmUp) "WARM-UP" else "EXPERIMENT"
val scheduler = schedulerConverter.convertToEntityAttribute(schedulerName)
val internalManager = factory.createEntityManager()
val simulation = Simulation(null, "Simulation", LocalDateTime.now(), LocalDateTime.now())
val experiment = Experiment(null, name, scheduler, simulation, loadTrace(internalManager), loadPath(internalManager)).apply {
state = ExperimentState.CLAIMED
}
manager.transaction.begin()
manager.persist(simulation)
manager.persist(experiment)
manager.transaction.commit()
return Sc18Experiment(internalManager, writer, experiment, isWarmUp)
}
/**
* Load the [Trace] from the database.
*/
private fun loadTrace(entityManager: EntityManager): Trace = entityManager
.createQuery("SELECT t FROM com.atlarge.opendc.model.odc.integration.jpa.schema.Trace t WHERE t.id = :id", Trace::class.java)
.setParameter("id", trace)
.singleResult
/**
* Load the [Path] from the database.
*/
private fun loadPath(entityManager: EntityManager): Path = entityManager
.createQuery("SELECT p FROM com.atlarge.opendc.model.odc.integration.jpa.schema.Path p WHERE p.id = :id", Path::class.java)
.setParameter("id", path)
.singleResult
/**
* Close this resource, relinquishing any underlying resources.
* This method is invoked automatically on objects managed by the
* `try`-with-resources statement.*
*
* @throws Exception if this resource cannot be closed
*/
override fun close() = manager.close()
}
| opendc-model-odc/sc18/src/main/kotlin/com/atlarge/opendc/model/odc/platform/Sc18ExperimentManager.kt | 3615966299 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.vo.PojoMethod
import com.google.auto.common.MoreTypes
import javax.lang.model.element.ExecutableElement
import javax.lang.model.type.DeclaredType
/**
* processes an executable element as member of the owning class
*/
class PojoMethodProcessor(
private val context: Context,
private val element: ExecutableElement,
private val owner: DeclaredType) {
fun process(): PojoMethod {
val asMember = context.processingEnv.typeUtils.asMemberOf(owner, element)
val name = element.simpleName.toString()
return PojoMethod(
element = element,
resolvedType = MoreTypes.asExecutable(asMember),
name = name
)
}
} | room/compiler/src/main/kotlin/androidx/room/processor/PojoMethodProcessor.kt | 3121127375 |
/**
* BreadWallet
*
* Created by Pablo Budelli <[email protected]> on 11/14/19.
* Copyright (c) 2019 breadwallet LLC
*
* 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.breadwallet.ui.settings.nodeselector
import android.app.AlertDialog
import android.content.Context
import android.graphics.Typeface
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import com.breadwallet.R
import com.breadwallet.databinding.ControllerNodeSelectorBinding
import com.breadwallet.mobius.CompositeEffectHandler
import com.breadwallet.tools.util.TrustedNode
import com.breadwallet.tools.util.Utils
import com.breadwallet.ui.BaseMobiusController
import com.breadwallet.ui.ViewEffect
import com.breadwallet.ui.flowbind.clicks
import com.breadwallet.ui.settings.nodeselector.NodeSelector.E
import com.breadwallet.ui.settings.nodeselector.NodeSelector.F
import com.breadwallet.ui.settings.nodeselector.NodeSelector.M
import com.spotify.mobius.Connectable
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.launch
import org.kodein.di.direct
import org.kodein.di.erased.instance
private const val DIALOG_TITLE_PADDING = 16
private const val DIALOG_TITLE_TEXT_SIZE = 18f
private const val DIALOG_INPUT_PADDING = 24
private const val SHOW_KEYBOARD_DELAY = 200L
private const val RESTORE_DIALOG_TITLE_DELAY = 1_000L
class NodeSelectorController : BaseMobiusController<M, E, F>() {
override val defaultModel = M.createDefault()
override val update = NodeSelectorUpdate
override val init = NodeSelectorInit
override val effectHandler = CompositeEffectHandler.from<F, E>(
Connectable { output ->
NodeSelectorHandler(output, direct.instance())
})
private val binding by viewBinding(ControllerNodeSelectorBinding::inflate)
override fun bindView(modelFlow: Flow<M>): Flow<E> {
return merge(
binding.buttonSwitch.clicks().map { E.OnSwitchButtonClicked }
)
}
override fun M.render() {
val res = checkNotNull(resources)
with(binding) {
ifChanged(M::mode) {
buttonSwitch.text = when (mode) {
NodeSelector.Mode.AUTOMATIC -> res.getString(R.string.NodeSelector_manualButton)
NodeSelector.Mode.MANUAL -> res.getString(R.string.NodeSelector_automaticButton)
else -> ""
}
}
ifChanged(M::currentNode) {
nodeText.text = if (currentNode.isNotBlank()) {
currentNode
} else {
res.getString(R.string.NodeSelector_automatic)
}
}
ifChanged(M::connected) {
nodeStatus.text = if (connected) {
res.getString(R.string.NodeSelector_connected)
} else {
res.getString(R.string.NodeSelector_notConnected)
}
}
}
}
override fun handleViewEffect(effect: ViewEffect) {
when (effect) {
F.ShowNodeDialog -> showNodeDialog()
}
}
private fun showNodeDialog() {
val res = checkNotNull(resources)
val alertDialog = AlertDialog.Builder(activity)
val customTitle = TextView(activity)
customTitle.gravity = Gravity.CENTER
customTitle.textAlignment = View.TEXT_ALIGNMENT_CENTER
val pad16 = Utils.getPixelsFromDps(activity, DIALOG_TITLE_PADDING)
customTitle.setPadding(pad16, pad16, pad16, pad16)
customTitle.text = res.getString(R.string.NodeSelector_enterTitle)
customTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, DIALOG_TITLE_TEXT_SIZE)
customTitle.setTypeface(null, Typeface.BOLD)
alertDialog.setCustomTitle(customTitle)
alertDialog.setMessage(res.getString(R.string.NodeSelector_enterBody))
val input = EditText(activity)
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
val padding = Utils.getPixelsFromDps(activity, DIALOG_INPUT_PADDING)
input.setPadding(padding, 0, padding, padding)
input.layoutParams = lp
alertDialog.setView(input)
alertDialog.setNegativeButton(
res.getString(R.string.Button_cancel)
) { dialog, _ -> dialog.cancel() }
alertDialog.setPositiveButton(
res.getString(R.string.Button_ok)
) { _, _ ->
// this implementation will be overridden
}
val dialog = alertDialog.show()
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener {
val node = input.text.toString()
if (TrustedNode.isValid(node)) {
eventConsumer.accept(E.SetCustomNode(node))
dialog.dismiss()
} else {
viewAttachScope.launch(Dispatchers.Main) {
customTitle.setText(R.string.NodeSelector_invalid)
customTitle.setTextColor(res.getColor(R.color.warning_color))
delay(RESTORE_DIALOG_TITLE_DELAY)
customTitle.setText(R.string.NodeSelector_enterTitle)
customTitle.setTextColor(res.getColor(R.color.almost_black))
}
}
}
viewAttachScope.launch(Dispatchers.Main) {
delay(SHOW_KEYBOARD_DELAY)
input.requestFocus()
val keyboard =
activity!!.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
keyboard.showSoftInput(input, 0)
}
}
}
| app/src/main/java/com/breadwallet/ui/settings/nodeselector/NodeSelectorController.kt | 3485234534 |
@file:JvmName("ImageFileSelector")
package com.sw926.imagefileselector
import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import java.lang.ref.WeakReference
class ImageFileSelector {
private var resultListener: ImageFileResultListener? = null
private val mImagePickHelper: ImagePickHelper
private val mImageCaptureHelper: ImageCaptureHelper
private var compressParams: CompressParams
private val context: WeakReference<Context>
constructor(activity: AppCompatActivity) {
mImageCaptureHelper = ImageCaptureHelper(activity)
mImagePickHelper = ImagePickHelper(activity)
compressParams = CompressParams()
context = WeakReference(activity)
init()
}
constructor(fragment: Fragment) {
mImageCaptureHelper = ImageCaptureHelper(fragment)
mImagePickHelper = ImagePickHelper(fragment)
compressParams = CompressParams()
context = WeakReference(fragment.context)
init()
}
private fun init() {
val listener = object : ImageUriResultListener {
override fun onSuccess(uri: Uri) {
val context = [email protected]()
if (context == null) {
resultListener?.onError()
return
}
ImageUtils.compress(context, uri, compressParams) {
if (it != null) {
resultListener?.onSuccess(it)
} else {
resultListener?.onError()
}
}
}
override fun onCancel() {
}
override fun onError() {
}
}
mImagePickHelper.setListener(listener)
mImageCaptureHelper.setListener(listener)
}
@Suppress("unused")
fun setSelectFileType(type: String) {
mImagePickHelper.setType(type)
}
/**
* 设置压缩后的文件大小
*
* @param maxWidth 压缩后文件宽度
* *
* @param maxHeight 压缩后文件高度
*/
fun setOutPutImageSize(maxWidth: Int, maxHeight: Int) {
compressParams = compressParams.copy(maxWidth = maxWidth, maxHeight = maxHeight)
}
/**
* 设置压缩后保存图片的质量
*
* @param quality 图片质量 0 - 100
*/
@Suppress("unused")
fun setQuality(quality: Int) {
compressParams = compressParams.copy(saveQuality = quality)
}
/**
* set image compress format
*
* @param compressFormat compress format
*/
@Suppress("unused")
fun setCompressFormat(compressFormat: Bitmap.CompressFormat) {
compressParams = compressParams.copy(compressFormat = compressFormat)
}
fun setListener(listenerUri: ImageFileResultListener?) {
resultListener = listenerUri
}
fun selectImage() {
mImagePickHelper.pickImage()
}
fun takePhoto() {
mImageCaptureHelper.takePicture()
}
}
| library/src/main/java/com/sw926/imagefileselector/ImageFileSelector.kt | 1175162800 |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.processor
import androidx.room.ColumnInfo
import androidx.room.ext.getAsBoolean
import androidx.room.ext.getAsInt
import androidx.room.ext.getAsString
import androidx.room.parser.Collate
import androidx.room.parser.SQLTypeAffinity
import androidx.room.vo.EmbeddedField
import androidx.room.vo.Field
import com.google.auto.common.AnnotationMirrors
import com.google.auto.common.MoreElements
import com.squareup.javapoet.TypeName
import javax.lang.model.element.Element
import javax.lang.model.type.DeclaredType
class FieldProcessor(baseContext: Context, val containing: DeclaredType, val element: Element,
val bindingScope: BindingScope,
// pass only if this is processed as a child of Embedded field
val fieldParent: EmbeddedField?) {
val context = baseContext.fork(element)
fun process(): Field {
val member = context.processingEnv.typeUtils.asMemberOf(containing, element)
val type = TypeName.get(member)
val columnInfoAnnotation = MoreElements.getAnnotationMirror(element,
ColumnInfo::class.java)
val name = element.simpleName.toString()
val columnName: String
val affinity: SQLTypeAffinity?
val collate: Collate?
val fieldPrefix = fieldParent?.prefix ?: ""
val indexed: Boolean
if (columnInfoAnnotation.isPresent) {
val nameInAnnotation = AnnotationMirrors
.getAnnotationValue(columnInfoAnnotation.get(), "name")
.getAsString(ColumnInfo.INHERIT_FIELD_NAME)
columnName = fieldPrefix + if (nameInAnnotation == ColumnInfo.INHERIT_FIELD_NAME) {
name
} else {
nameInAnnotation
}
affinity = try {
val userDefinedAffinity = AnnotationMirrors
.getAnnotationValue(columnInfoAnnotation.get(), "typeAffinity")
.getAsInt(ColumnInfo.UNDEFINED)!!
SQLTypeAffinity.fromAnnotationValue(userDefinedAffinity)
} catch (ex: NumberFormatException) {
null
}
collate = Collate.fromAnnotationValue(AnnotationMirrors.getAnnotationValue(
columnInfoAnnotation.get(), "collate").getAsInt(ColumnInfo.UNSPECIFIED)!!)
indexed = AnnotationMirrors
.getAnnotationValue(columnInfoAnnotation.get(), "index")
.getAsBoolean(false)
} else {
columnName = fieldPrefix + name
affinity = null
collate = null
indexed = false
}
context.checker.notBlank(columnName, element,
ProcessorErrors.COLUMN_NAME_CANNOT_BE_EMPTY)
context.checker.notUnbound(type, element,
ProcessorErrors.CANNOT_USE_UNBOUND_GENERICS_IN_ENTITY_FIELDS)
val field = Field(name = name,
type = member,
element = element,
columnName = columnName,
affinity = affinity,
collate = collate,
parent = fieldParent,
indexed = indexed)
when (bindingScope) {
BindingScope.TWO_WAY -> {
val adapter = context.typeAdapterStore.findColumnTypeAdapter(field.type,
field.affinity)
field.statementBinder = adapter
field.cursorValueReader = adapter
field.affinity = adapter?.typeAffinity ?: field.affinity
context.checker.check(adapter != null, field.element,
ProcessorErrors.CANNOT_FIND_COLUMN_TYPE_ADAPTER)
}
BindingScope.BIND_TO_STMT -> {
field.statementBinder = context.typeAdapterStore
.findStatementValueBinder(field.type, field.affinity)
context.checker.check(field.statementBinder != null, field.element,
ProcessorErrors.CANNOT_FIND_STMT_BINDER)
}
BindingScope.READ_FROM_CURSOR -> {
field.cursorValueReader = context.typeAdapterStore
.findCursorValueReader(field.type, field.affinity)
context.checker.check(field.cursorValueReader != null, field.element,
ProcessorErrors.CANNOT_FIND_CURSOR_READER)
}
}
return field
}
/**
* Defines what we need to assign
*/
enum class BindingScope {
TWO_WAY, // both bind and read.
BIND_TO_STMT, // just value to statement
READ_FROM_CURSOR // just cursor to value
}
}
| room/compiler/src/main/kotlin/androidx/room/processor/FieldProcessor.kt | 2627859345 |
package com.orgzly.android.ui.main
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.FragmentActivity
import com.orgzly.R
import com.orgzly.android.db.entity.Book
import com.orgzly.android.query.Condition
import com.orgzly.android.query.Query
import com.orgzly.android.query.user.DottedQueryBuilder
import com.orgzly.android.ui.DisplayManager
import com.orgzly.android.ui.notes.book.BookFragment
/**
* SearchView setup and query text listeners.
* TODO: http://developer.android.com/training/search/setup.html
*/
fun FragmentActivity.setupSearchView(menu: Menu) {
fun getActiveFragmentBook(): Book? {
supportFragmentManager.findFragmentByTag(BookFragment.FRAGMENT_TAG)?.let { bookFragment ->
if (bookFragment is BookFragment && bookFragment.isVisible) {
return bookFragment.currentBook
}
}
return null
}
val activity = this
val searchItem = menu.findItem(R.id.search_view)
// Hide FAB while searching
searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(item: MenuItem): Boolean {
Fab.hide(activity)
return true
}
override fun onMenuItemActionCollapse(item: MenuItem): Boolean {
Fab.show(activity)
return true
}
})
val searchView = searchItem.actionView as SearchView
searchView.queryHint = getString(R.string.search_hint)
searchView.setOnSearchClickListener {
// Make search as wide as possible
searchView.layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT
/*
* When user starts the search, fill the search box with text
* depending on the current fragment.
*/
// For Query fragment, fill the box with full query
DisplayManager.getDisplayedQuery(supportFragmentManager)?.let { query ->
searchView.setQuery("$query ", false)
return@setOnSearchClickListener
}
// If searching from book, add book name to query
getActiveFragmentBook()?.let { book ->
val builder = DottedQueryBuilder()
val query = builder.build(Query(Condition.InBook(book.name)))
searchView.setQuery("$query ", false)
return@setOnSearchClickListener
}
}
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(str: String?): Boolean {
return false
}
override fun onQueryTextSubmit(str: String): Boolean {
// Close search
searchItem.collapseActionView()
DisplayManager.displayQuery(supportFragmentManager, str.trim { it <= ' ' })
return true
}
})
}
| app/src/main/java/com/orgzly/android/ui/main/SearchViewSetup.kt | 2866065259 |
/*
* Copyright (C) 2017-2021 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.utils.network
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.net.NetworkRequest
class ConnectionStateMonitor(private val listener: OnConnectionChangeListener) : ConnectivityManager.NetworkCallback() {
private val networkRequest = NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build()
var isAvailable = false
private set
fun enable(context: Context) {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
manager.registerNetworkCallback(networkRequest, this)
}
fun disable(context: Context) {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
manager.unregisterNetworkCallback(this)
}
override fun onAvailable(network: Network) {
if (!isAvailable) {
isAvailable = true
listener(true)
}
}
override fun onLost(network: Network) {
if (isAvailable) {
isAvailable = false
listener(false)
}
}
}
typealias OnConnectionChangeListener = (isAvailable: Boolean) -> Unit
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/network/ConnectionStateMonitor.kt | 2028118067 |
package com.smartsight.app.ui
import android.content.Context
import android.hardware.Camera
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import java.io.IOException
class CameraPreview(context: Context, private val camera: Camera) : SurfaceView(context), SurfaceHolder.Callback {
companion object {
private val TAG = CameraPreview::class.java.simpleName
}
private val surfaceHolder = holder
init {
surfaceHolder.addCallback(this)
}
override fun surfaceCreated(holder: SurfaceHolder) {
try {
camera.setDisplayOrientation(90)
camera.setPreviewDisplay(surfaceHolder)
camera.startPreview()
} catch (e: IOException) {
Log.e(TAG, "Cannot create surface preview $e")
}
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
try {
camera.stopPreview()
camera.setPreviewDisplay(surfaceHolder)
camera.startPreview()
} catch (e: IOException) {
Log.e(TAG, "Cannot change surface preview $e")
}
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
camera.stopPreview()
}
}
| app/src/main/java/com/smartsight/app/ui/CameraPreview.kt | 3928050937 |
/*
* Copyright 2019 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.event.chatgroup
import com.rpkit.chat.bukkit.chatgroup.RPKChatGroup
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitChatGroupDeleteEvent(
override val chatGroup: RPKChatGroup
): RPKBukkitEvent(), RPKChatGroupDeleteEvent, Cancellable {
companion object {
@JvmStatic val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/event/chatgroup/RPKBukkitChatGroupDeleteEvent.kt | 2286932326 |
package org.evomaster.core.search.algorithms.constant
import org.evomaster.core.search.EvaluatedIndividual
import org.evomaster.core.search.FitnessValue
import org.evomaster.core.search.service.FitnessFunction
/**
* Created by arcuri82 on 20-Feb-17.
*/
class ConstantFitness : FitnessFunction<ConstantIndividual>() {
override fun doCalculateCoverage(individual: ConstantIndividual, targets: Set<Int>): EvaluatedIndividual<ConstantIndividual>? {
val target = 123
val res = individual.getGene().value
val h = if (res == target) {
1.0
} else {
val distance = Math.abs(target - res)
1.0 - (distance / (1.0 + distance))
}
val fv = FitnessValue(individual.size().toDouble())
fv.updateTarget(0, h)
return EvaluatedIndividual(fv, individual.copy() as ConstantIndividual, listOf(), index = time.evaluatedIndividuals, config = config, trackOperator = individual.trackOperator)
}
} | core/src/test/kotlin/org/evomaster/core/search/algorithms/constant/ConstantFitness.kt | 977844690 |
package com.piticlistudio.playednext.ui.gamerelation.detail
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.lifecycle.Observer
import com.nhaarman.mockito_kotlin.*
import com.piticlistudio.playednext.domain.interactor.game.LoadGameUseCase
import com.piticlistudio.playednext.domain.interactor.relation.LoadRelationsForGameUseCase
import com.piticlistudio.playednext.domain.model.Game
import com.piticlistudio.playednext.domain.model.GameRelation
import com.piticlistudio.playednext.test.factory.DataFactory.Factory.randomInt
import com.piticlistudio.playednext.test.factory.DataFactory.Factory.randomListOf
import com.piticlistudio.playednext.test.factory.GameFactory.Factory.makeGame
import com.piticlistudio.playednext.test.factory.GameRelationFactory.Factory.makeGameRelation
import com.piticlistudio.playednext.util.RxSchedulersOverrideRule
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import kotlin.test.assertNull
import kotlin.test.assertTrue
internal class GameRelationDetailViewModelTest {
@JvmField
@Rule
val mOverrideSchedulersRule = RxSchedulersOverrideRule()
@JvmField
@Rule
val taskRule = InstantTaskExecutorRule()
private lateinit var vm: GameRelationDetailViewModel
@Mock lateinit var loadRelationsForGameUseCase: LoadRelationsForGameUseCase
@Mock lateinit var loadGameUseCase: LoadGameUseCase
@Mock private lateinit var observer: Observer<ViewState>
private val relations = randomListOf(5) { makeGameRelation() }
private val game = makeGame()
@Before
fun setUp() {
game.images = listOf()
MockitoAnnotations.initMocks(this)
vm = GameRelationDetailViewModel(loadRelationsForGameUseCase, loadGameUseCase)
vm.getCurrentState().observeForever(observer)
val flow = Flowable.create<List<GameRelation>>({ it.onNext(relations) }, BackpressureStrategy.MISSING)
whenever(loadRelationsForGameUseCase.execute(any())).thenReturn(flow)
val gameflow = Flowable.create<Game>({ it.onNext(game) }, BackpressureStrategy.MISSING)
whenever(loadGameUseCase.execute(any())).thenReturn(gameflow)
}
@Test
fun requestsUsecasesWithCorrectParameters() {
vm.loadRelationForGame(100)
verify(loadGameUseCase).execute(100)
verify(loadRelationsForGameUseCase).execute(game)
}
@Test
fun showsSuccessViewState() {
vm.loadRelationForGame(randomInt())
val captor = argumentCaptor<ViewState>()
verify(observer, times(3)).onChanged(captor.capture())
assertTrue {
captor.firstValue.isLoading && captor.firstValue.game == null && captor.firstValue.error == null
&& captor.firstValue.showImage == null && captor.firstValue.relations.isEmpty()
}
assertTrue {
!captor.lastValue.isLoading && captor.lastValue.game != null && captor.lastValue.game!!.equals(game)
&& captor.lastValue.relations.equals(relations)
&& captor.lastValue.error == null
}
captor.allValues.forEach {
assertNull(it.error)
}
}
@Test
fun showsErrorViewStateWhenLoadingAGame() {
val error = Throwable()
whenever(loadGameUseCase.execute(any())).thenReturn(Flowable.error(error))
vm.loadRelationForGame(randomInt())
val captor = argumentCaptor<ViewState>()
verify(observer, times(2)).onChanged(captor.capture())
assertTrue {
captor.firstValue.isLoading && captor.firstValue.game == null && captor.firstValue.error == null
&& captor.firstValue.showImage == null && captor.firstValue.relations.isEmpty()
}
assertTrue {
!captor.lastValue.isLoading && captor.lastValue.game == null && captor.lastValue.relations.isEmpty()
&& captor.lastValue.error == error
}
captor.allValues.forEach {
assertNull(it.game)
assertTrue { it.relations.isEmpty() }
assertNull(it.showImage)
}
}
@Test
fun showsErrorViewStateWhenLoadingRelations() {
val error = Throwable()
whenever(loadRelationsForGameUseCase.execute(any())).thenReturn(Flowable.error(error))
vm.loadRelationForGame(randomInt())
val captor = argumentCaptor<ViewState>()
verify(observer, times(3)).onChanged(captor.capture())
assertTrue {
captor.firstValue.isLoading && captor.firstValue.game == null && captor.firstValue.error == null
&& captor.firstValue.showImage == null && captor.firstValue.relations.isEmpty()
}
assertTrue {
!captor.lastValue.isLoading && captor.lastValue.game == game && captor.lastValue.relations.isEmpty()
&& captor.lastValue.error == error
}
captor.allValues.forEach {
assertTrue { it.relations.isEmpty() }
}
}
} | app/src/test/java/com/piticlistudio/playednext/ui/gamerelation/detail/GameRelationDetailViewModelTest.kt | 1116083605 |
package com.tekinarslan.kotlinrxjavasample.service
import com.tekinarslan.kotlinrxjavasample.model.PhotosDataModel
import io.reactivex.Observable
import retrofit2.http.GET
/**
* Created by selimtekinarslan on 6/29/2017.
*/
interface DataService {
@GET("photos")
fun getData(): Observable<ArrayList<PhotosDataModel>>
} | app/src/main/java/com/tekinarslan/kotlinrxjavasample/service/DataService.kt | 500527494 |
package com.soywiz.kpspemu
import com.soywiz.klogger.*
import com.soywiz.korau.format.util.*
import com.soywiz.korinject.*
import com.soywiz.korio.async.*
import com.soywiz.kpspemu.battery.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.cpu.dis.*
import com.soywiz.kpspemu.ctrl.*
import com.soywiz.kpspemu.display.*
import com.soywiz.kpspemu.ge.*
import com.soywiz.kpspemu.hle.manager.*
import com.soywiz.kpspemu.mem.*
import kotlin.coroutines.*
class Emulator constructor(
val coroutineContext: CoroutineContext,
val syscalls: SyscallManager = SyscallManager(),
val mem: Memory = Memory(),
var gpuRenderer: GpuRenderer = DummyGpuRenderer()
) : AsyncDependency {
//val INITIAL_INTERPRETED = false
val INITIAL_INTERPRETED = true
var interpreted = INITIAL_INTERPRETED
val onHomePress = Signal<Unit>()
val onLoadPress = Signal<Unit>()
val logger = Logger("Emulator")
val timeManager = TimeManager(this)
val nameProvider = AddressInfo()
val breakpoints = Breakpoints()
val globalCpuState = GlobalCpuState(mem)
var output = StringBuilder()
val ge: Ge = Ge(this)
val gpu: Gpu = Gpu(this)
val battery: PspBattery = PspBattery(this)
val interruptManager: InterruptManager = InterruptManager(this)
val display: PspDisplay = PspDisplay(this)
val deviceManager = DeviceManager(this)
val configManager = ConfigManager()
val memoryManager = MemoryManager(this)
val threadManager = ThreadManager(this)
val moduleManager = ModuleManager(this)
val callbackManager = CallbackManager(this)
val controller = PspController(this)
val fileManager = FileManager(this)
val imem = object : IMemory {
override fun read8(addr: Int): Int = mem.lbu(addr)
}
override suspend fun init() {
configManager.init()
deviceManager.init()
configManager.storage.subscribe {
deviceManager.setStorage(it)
}
}
val running: Boolean get() = threadManager.aliveThreadCount >= 1
var globalTrace: Boolean = false
var sdkVersion: Int = 150
init {
CpuBreakException.initialize(mem)
}
fun invalidateInstructionCache(ptr: Int = 0, size: Int = Int.MAX_VALUE) {
logger.trace { "invalidateInstructionCache($ptr, $size)" }
globalCpuState.mcache.invalidateInstructionCache(ptr, size)
}
fun dataCache(ptr: Int = 0, size: Int = Int.MAX_VALUE, writeback: Boolean, invalidate: Boolean) {
logger.trace { "writebackDataCache($ptr, $size, writeback=$writeback, invalidate=$invalidate)" }
}
suspend fun reset() {
globalTrace = false
sdkVersion = 150
syscalls.reset()
mem.reset()
CpuBreakException.initialize(mem)
gpuRenderer.reset()
timeManager.reset()
nameProvider.reset()
//breakpoints.reset() // Do not reset breakpoints?
globalCpuState.reset()
output = StringBuilder()
ge.reset()
gpu.reset()
battery.reset()
interruptManager.reset()
display.reset()
deviceManager.reset()
memoryManager.reset()
threadManager.reset()
moduleManager.reset()
callbackManager.reset()
controller.reset()
fileManager.reset()
}
}
interface WithEmulator {
val emulator: Emulator
}
class AddressInfo : NameProvider {
val names = hashMapOf<Int, String>()
override fun getName(addr: Int): String? = names[addr]
fun reset() {
names.clear()
}
}
val WithEmulator.mem: Memory get() = emulator.mem
val WithEmulator.imem: IMemory get() = emulator.imem
val WithEmulator.ge: Ge get() = emulator.ge
val WithEmulator.gpu: Gpu get() = emulator.gpu
val WithEmulator.controller: PspController get() = emulator.controller
val WithEmulator.coroutineContext: CoroutineContext get() = emulator.coroutineContext
val WithEmulator.display: PspDisplay get() = emulator.display
val WithEmulator.deviceManager: DeviceManager get() = emulator.deviceManager
val WithEmulator.memoryManager: MemoryManager get() = emulator.memoryManager
val WithEmulator.timeManager: TimeManager get() = emulator.timeManager
val WithEmulator.fileManager: FileManager get() = emulator.fileManager
val WithEmulator.rtc: TimeManager get() = emulator.timeManager
val WithEmulator.threadManager: ThreadManager get() = emulator.threadManager
val WithEmulator.callbackManager: CallbackManager get() = emulator.callbackManager
val WithEmulator.breakpoints: Breakpoints get() = emulator.breakpoints
| src/commonMain/kotlin/com/soywiz/kpspemu/Emulator.kt | 629322136 |
package asmble.run.jvm.interpret
import asmble.ast.Node
import asmble.compile.jvm.*
import asmble.run.jvm.RunErr
import asmble.util.Either
import asmble.util.Logger
import asmble.util.toUnsignedInt
import asmble.util.toUnsignedLong
import java.lang.invoke.MethodHandle
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.nio.ByteBuffer
import java.nio.ByteOrder
// This is not intended to be fast, rather clear and easy to read. Very little cached/memoized, lots of extra cycles.
open class Interpreter {
open fun execFunc(
ctx: Context,
funcIndex: Int = ctx.mod.startFuncIndex ?: error("No start func index"),
vararg funcArgs: Number
): Number? {
// Check params
val funcType = ctx.funcTypeAtIndex(funcIndex)
funcArgs.mapNotNull { it.valueType }.let {
if (it != funcType.params) throw InterpretErr.StartFuncParamMismatch(funcType.params, it)
}
// Import functions are executed inline and returned
ctx.importFuncs.getOrNull(funcIndex)?.also {
return ctx.imports.invokeFunction(it.module, it.field, funcType, funcArgs.toList())
}
// This is the call stack we need to stop at
val startingCallStackSize = ctx.callStack.size
// Make the call on the context
var lastStep: StepResult = StepResult.Call(funcIndex, funcArgs.toList(), funcType)
// Run until done
while (lastStep !is StepResult.Return || ctx.callStack.size > startingCallStackSize + 1) {
next(ctx, lastStep)
lastStep = step(ctx)
}
ctx.callStack.subList(startingCallStackSize, ctx.callStack.size).clear()
return lastStep.v
}
open fun step(ctx: Context): StepResult = ctx.currFuncCtx.run {
// If the insn is out of bounds, it's an implicit return, otherwise just execute the insn
if (insnIndex >= func.instructions.size) StepResult.Return(func.type.ret?.let { pop(it) })
else invokeSingle(ctx)
}
// Errors with InterpretErr.EndReached if there is no next step to be had
open fun next(ctx: Context, step: StepResult) {
ctx.logger.trace {
val fnName = ctx.maybeCurrFuncCtx?.funcIndex?.let { ctx.mod.names?.funcNames?.get(it) ?: it.toString() }
"NEXT ON $fnName(${ctx.maybeCurrFuncCtx?.funcIndex}:${ctx.maybeCurrFuncCtx?.insnIndex}): $step " +
"[VAL STACK: ${ctx.maybeCurrFuncCtx?.valueStack}] " +
"[CALL STACK DEPTH: ${ctx.callStack.size}]"
}
when (step) {
// Next just moves the counter
is StepResult.Next -> ctx.currFuncCtx.insnIndex++
// Branch updates the stack and moves the insn index
is StepResult.Branch -> ctx.currFuncCtx.run {
// A failed if just jumps to the else or end
if (step.failedIf) {
require(step.blockDepth == 0)
val block = blockStack.last()
if (block.elseIndex != null) insnIndex = block.elseIndex + 1
else {
insnIndex = block.endIndex + 1
blockStack.removeAt(blockStack.size - 1)
}
} else {
// Remove all blocks until the depth requested
blockStack.subList(blockStack.size - step.blockDepth, blockStack.size).clear()
// This can break out of the entire function
if (blockStack.isEmpty()) {
// Grab the stack item if present, blow away stack, put back, and move to end of func
val retVal = func.type.ret?.let { pop(it) }
valueStack.clear()
retVal?.also { push(it) }
insnIndex = func.instructions.size
} else if (blockStack.last().insn is Node.Instr.Loop && !step.forceEndOnLoop) {
// It's just a loop continuation, go back to top
insnIndex = blockStack.last().startIndex + 1
} else {
// Remove the one at the depth requested
val block = blockStack.removeAt(blockStack.size - 1)
// Pop value if applicable
val blockVal = block.insn.type?.let { pop(it) }
// Trim the stack down to required size
valueStack.subList(block.stackSizeAtStart, valueStack.size).clear()
// Put the value back on if applicable
blockVal?.also { push(it) }
// Jump past the end
insnIndex = block.endIndex + 1
}
}
}
// Call, if import, invokes it and puts result on stack. If not, just pushes a new func context.
is StepResult.Call -> ctx.funcAtIndex(step.funcIndex).let {
when (it) {
// If import, call and just put on stack and advance insn if came from insn
is Either.Left ->
ctx.imports.invokeFunction(it.v.module, it.v.field, step.type, step.args).also {
// Make sure result type is accurate
if (it.valueType != step.type.ret)
throw InterpretErr.InvalidCallResult(step.type.ret, it)
it?.also { ctx.currFuncCtx.push(it) }
ctx.currFuncCtx.insnIndex++
}
// If inside the module, create new context to continue
is Either.Right -> ctx.callStack += FuncContext(step.funcIndex, it.v).also { funcCtx ->
ctx.logger.debug {
">".repeat(ctx.callStack.size) + " " + ctx.mod.names?.funcNames?.get(funcCtx.funcIndex) +
":${funcCtx.funcIndex} - args: " + step.args
}
// Set the args
step.args.forEachIndexed { index, arg -> funcCtx.locals[index] = arg }
}
}
}
// Call indirect is just an MH invocation
is StepResult.CallIndirect -> {
val mh = ctx.table?.getOrNull(step.tableIndex) ?: error("Missing table entry")
val res = mh.invokeWithArguments(step.args) as? Number?
if (res.valueType != step.type.ret) throw InterpretErr.InvalidCallResult(step.type.ret, res)
res?.also { ctx.currFuncCtx.push(it) }
ctx.currFuncCtx.insnIndex++
}
// Unreachable throws
is StepResult.Unreachable -> throw UnsupportedOperationException("Unreachable")
// Return pops curr func from the call stack, push ret and move insn on prev one
is StepResult.Return -> ctx.callStack.removeAt(ctx.callStack.lastIndex).let { returnedFrom ->
if (ctx.callStack.isEmpty()) throw InterpretErr.EndReached(step.v)
if (returnedFrom.valueStack.isNotEmpty())
throw CompileErr.UnusedStackOnReturn(returnedFrom.valueStack.map { it::class.ref } )
step.v?.also { ctx.currFuncCtx.push(it) }
ctx.currFuncCtx.insnIndex++
}
}
}
open fun invokeSingle(ctx: Context): StepResult = ctx.currFuncCtx.run {
// TODO: validation?
func.instructions[insnIndex].let { insn ->
ctx.logger.trace { "INSN #$insnIndex: $insn [STACK: $valueStack]" }
when (insn) {
is Node.Instr.Unreachable -> StepResult.Unreachable
is Node.Instr.Nop -> next { }
is Node.Instr.Block, is Node.Instr.Loop -> next {
blockStack += Block(insnIndex, insn as Node.Instr.Args.Type, valueStack.size, currentBlockEnd()!!)
}
is Node.Instr.If -> {
blockStack += Block(insnIndex, insn, valueStack.size - 1, currentBlockEnd()!!, currentBlockElse())
if (popInt() == 0) StepResult.Branch(0, failedIf = true) else StepResult.Next
}
is Node.Instr.Else ->
// Jump over the whole thing and to the end, this can only be gotten here via if
StepResult.Branch(0)
is Node.Instr.End ->
// Since we reached the end by manually running through it, jump to end even on loop
StepResult.Branch(0, forceEndOnLoop = true)
is Node.Instr.Br -> StepResult.Branch(insn.relativeDepth)
is Node.Instr.BrIf -> if (popInt() != 0) StepResult.Branch(insn.relativeDepth) else StepResult.Next
is Node.Instr.BrTable -> StepResult.Branch(insn.targetTable.getOrNull(popInt())
?: insn.default)
is Node.Instr.Return ->
StepResult.Return(func.type.ret?.let { pop(it) })
is Node.Instr.Call -> ctx.funcTypeAtIndex(insn.index).let {
ctx.checkNextIsntStackOverflow()
StepResult.Call(insn.index, popCallArgs(it), it)
}
is Node.Instr.CallIndirect -> {
ctx.checkNextIsntStackOverflow()
val tableIndex = popInt()
val expectedType = ctx.typeAtIndex(insn.index).also {
val tableMh = ctx.table?.getOrNull(tableIndex) ?:
throw InterpretErr.UndefinedElement(tableIndex)
val actualType = Node.Type.Func(
params = tableMh.type().parameterList().map { it.valueType!! },
ret = tableMh.type().returnType().valueType
)
if (it != actualType) throw InterpretErr.IndirectCallTypeMismatch(it, actualType)
}
StepResult.CallIndirect(tableIndex, popCallArgs(expectedType), expectedType)
}
is Node.Instr.Drop -> next { pop() }
is Node.Instr.Select -> next {
popInt().also {
val v2 = pop()
val v1 = pop()
if (v1::class != v2::class)
throw CompileErr.SelectMismatch(v1.valueType!!.typeRef, v2.valueType!!.typeRef)
if (it != 0) push(v1) else push(v2)
}
}
is Node.Instr.GetLocal -> next { push(locals[insn.index]) }
is Node.Instr.SetLocal -> next { locals[insn.index] = pop()}
is Node.Instr.TeeLocal -> next { locals[insn.index] = peek() }
is Node.Instr.GetGlobal -> next { push(ctx.getGlobal(insn.index)) }
is Node.Instr.SetGlobal -> next { ctx.setGlobal(insn.index, pop()) }
is Node.Instr.I32Load -> next { push(ctx.mem.getInt(insn.popMemAddr())) }
is Node.Instr.I64Load -> next { push(ctx.mem.getLong(insn.popMemAddr())) }
is Node.Instr.F32Load -> next { push(ctx.mem.getFloat(insn.popMemAddr())) }
is Node.Instr.F64Load -> next { push(ctx.mem.getDouble(insn.popMemAddr())) }
is Node.Instr.I32Load8S -> next { push(ctx.mem.get(insn.popMemAddr()).toInt()) }
is Node.Instr.I32Load8U -> next { push(ctx.mem.get(insn.popMemAddr()).toUnsignedInt()) }
is Node.Instr.I32Load16S -> next { push(ctx.mem.getShort(insn.popMemAddr()).toInt()) }
is Node.Instr.I32Load16U -> next { push(ctx.mem.getShort(insn.popMemAddr()).toUnsignedInt()) }
is Node.Instr.I64Load8S -> next { push(ctx.mem.get(insn.popMemAddr()).toLong()) }
is Node.Instr.I64Load8U -> next { push(ctx.mem.get(insn.popMemAddr()).toUnsignedLong()) }
is Node.Instr.I64Load16S -> next { push(ctx.mem.getShort(insn.popMemAddr()).toLong()) }
is Node.Instr.I64Load16U -> next { push(ctx.mem.getShort(insn.popMemAddr()).toUnsignedLong()) }
is Node.Instr.I64Load32S -> next { push(ctx.mem.getInt(insn.popMemAddr()).toLong()) }
is Node.Instr.I64Load32U -> next { push(ctx.mem.getInt(insn.popMemAddr()).toUnsignedLong()) }
is Node.Instr.I32Store -> next { popInt().let { ctx.mem.putInt(insn.popMemAddr(), it) } }
is Node.Instr.I64Store -> next { popLong().let { ctx.mem.putLong(insn.popMemAddr(), it) } }
is Node.Instr.F32Store -> next { popFloat().let { ctx.mem.putFloat(insn.popMemAddr(), it) } }
is Node.Instr.F64Store -> next { popDouble().let { ctx.mem.putDouble(insn.popMemAddr(), it) } }
is Node.Instr.I32Store8 -> next { popInt().let { ctx.mem.put(insn.popMemAddr(), it.toByte()) } }
is Node.Instr.I32Store16 -> next { popInt().let { ctx.mem.putShort(insn.popMemAddr(), it.toShort()) } }
is Node.Instr.I64Store8 -> next { popLong().let { ctx.mem.put(insn.popMemAddr(), it.toByte()) } }
is Node.Instr.I64Store16 -> next { popLong().let { ctx.mem.putShort(insn.popMemAddr(), it.toShort()) } }
is Node.Instr.I64Store32 -> next { popLong().let { ctx.mem.putInt(insn.popMemAddr(), it.toInt()) } }
is Node.Instr.MemorySize -> next { push(ctx.mem.limit() / Mem.PAGE_SIZE) }
is Node.Instr.MemoryGrow -> next {
val newLim = ctx.mem.limit().toLong() + (popInt().toLong() * Mem.PAGE_SIZE)
if (newLim > ctx.mem.capacity()) push(-1)
else (ctx.mem.limit() / Mem.PAGE_SIZE).also {
push(it)
ctx.mem.limit(newLim.toInt())
}
}
is Node.Instr.I32Const -> next { push(insn.value) }
is Node.Instr.I64Const -> next { push(insn.value) }
is Node.Instr.F32Const -> next { push(insn.value) }
is Node.Instr.F64Const -> next { push(insn.value) }
is Node.Instr.I32Eqz -> next { push(popInt() == 0) }
is Node.Instr.I32Eq -> nextBinOp(popInt(), popInt()) { a, b -> a == b }
is Node.Instr.I32Ne -> nextBinOp(popInt(), popInt()) { a, b -> a != b }
is Node.Instr.I32LtS -> nextBinOp(popInt(), popInt()) { a, b -> a < b }
is Node.Instr.I32LtU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) < 0 }
is Node.Instr.I32GtS -> nextBinOp(popInt(), popInt()) { a, b -> a > b }
is Node.Instr.I32GtU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) > 0 }
is Node.Instr.I32LeS -> nextBinOp(popInt(), popInt()) { a, b -> a <= b }
is Node.Instr.I32LeU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) <= 0 }
is Node.Instr.I32GeS -> nextBinOp(popInt(), popInt()) { a, b -> a >= b }
is Node.Instr.I32GeU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.compareUnsigned(a, b) >= 0 }
is Node.Instr.I64Eqz -> next { push(popLong() == 0L) }
is Node.Instr.I64Eq -> nextBinOp(popLong(), popLong()) { a, b -> a == b }
is Node.Instr.I64Ne -> nextBinOp(popLong(), popLong()) { a, b -> a != b }
is Node.Instr.I64LtS -> nextBinOp(popLong(), popLong()) { a, b -> a < b }
is Node.Instr.I64LtU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) < 0 }
is Node.Instr.I64GtS -> nextBinOp(popLong(), popLong()) { a, b -> a > b }
is Node.Instr.I64GtU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) > 0 }
is Node.Instr.I64LeS -> nextBinOp(popLong(), popLong()) { a, b -> a <= b }
is Node.Instr.I64LeU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) <= 0 }
is Node.Instr.I64GeS -> nextBinOp(popLong(), popLong()) { a, b -> a >= b }
is Node.Instr.I64GeU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.compareUnsigned(a, b) >= 0 }
is Node.Instr.F32Eq -> nextBinOp(popFloat(), popFloat()) { a, b -> a == b }
is Node.Instr.F32Ne -> nextBinOp(popFloat(), popFloat()) { a, b -> a != b }
is Node.Instr.F32Lt -> nextBinOp(popFloat(), popFloat()) { a, b -> a < b }
is Node.Instr.F32Gt -> nextBinOp(popFloat(), popFloat()) { a, b -> a > b }
is Node.Instr.F32Le -> nextBinOp(popFloat(), popFloat()) { a, b -> a <= b }
is Node.Instr.F32Ge -> nextBinOp(popFloat(), popFloat()) { a, b -> a >= b }
is Node.Instr.F64Eq -> nextBinOp(popDouble(), popDouble()) { a, b -> a == b }
is Node.Instr.F64Ne -> nextBinOp(popDouble(), popDouble()) { a, b -> a != b }
is Node.Instr.F64Lt -> nextBinOp(popDouble(), popDouble()) { a, b -> a < b }
is Node.Instr.F64Gt -> nextBinOp(popDouble(), popDouble()) { a, b -> a > b }
is Node.Instr.F64Le -> nextBinOp(popDouble(), popDouble()) { a, b -> a <= b }
is Node.Instr.F64Ge -> nextBinOp(popDouble(), popDouble()) { a, b -> a >= b }
is Node.Instr.I32Clz -> next { push(Integer.numberOfLeadingZeros(popInt())) }
is Node.Instr.I32Ctz -> next { push(Integer.numberOfTrailingZeros(popInt())) }
is Node.Instr.I32Popcnt -> next { push(Integer.bitCount(popInt())) }
is Node.Instr.I32Add -> nextBinOp(popInt(), popInt()) { a, b -> a + b }
is Node.Instr.I32Sub -> nextBinOp(popInt(), popInt()) { a, b -> a - b }
is Node.Instr.I32Mul -> nextBinOp(popInt(), popInt()) { a, b -> a * b }
is Node.Instr.I32DivS -> nextBinOp(popInt(), popInt()) { a, b ->
ctx.checkedSignedDivInteger(a, b)
a / b
}
is Node.Instr.I32DivU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.divideUnsigned(a, b) }
is Node.Instr.I32RemS -> nextBinOp(popInt(), popInt()) { a, b -> a % b }
is Node.Instr.I32RemU -> nextBinOp(popInt(), popInt()) { a, b -> Integer.remainderUnsigned(a, b) }
is Node.Instr.I32And -> nextBinOp(popInt(), popInt()) { a, b -> a and b }
is Node.Instr.I32Or -> nextBinOp(popInt(), popInt()) { a, b -> a or b }
is Node.Instr.I32Xor -> nextBinOp(popInt(), popInt()) { a, b -> a xor b }
is Node.Instr.I32Shl -> nextBinOp(popInt(), popInt()) { a, b -> a shl b }
is Node.Instr.I32ShrS -> nextBinOp(popInt(), popInt()) { a, b -> a shr b }
is Node.Instr.I32ShrU -> nextBinOp(popInt(), popInt()) { a, b -> a ushr b }
is Node.Instr.I32Rotl -> nextBinOp(popInt(), popInt()) { a, b -> Integer.rotateLeft(a, b) }
is Node.Instr.I32Rotr -> nextBinOp(popInt(), popInt()) { a, b -> Integer.rotateRight(a, b) }
is Node.Instr.I64Clz -> next { push(java.lang.Long.numberOfLeadingZeros(popLong()).toLong()) }
is Node.Instr.I64Ctz -> next { push(java.lang.Long.numberOfTrailingZeros(popLong()).toLong()) }
is Node.Instr.I64Popcnt -> next { push(java.lang.Long.bitCount(popLong()).toLong()) }
is Node.Instr.I64Add -> nextBinOp(popLong(), popLong()) { a, b -> a + b }
is Node.Instr.I64Sub -> nextBinOp(popLong(), popLong()) { a, b -> a - b }
is Node.Instr.I64Mul -> nextBinOp(popLong(), popLong()) { a, b -> a * b }
is Node.Instr.I64DivS -> nextBinOp(popLong(), popLong()) { a, b ->
ctx.checkedSignedDivInteger(a, b)
a / b
}
is Node.Instr.I64DivU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.divideUnsigned(a, b) }
is Node.Instr.I64RemS -> nextBinOp(popLong(), popLong()) { a, b -> a % b }
is Node.Instr.I64RemU -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.remainderUnsigned(a, b) }
is Node.Instr.I64And -> nextBinOp(popLong(), popLong()) { a, b -> a and b }
is Node.Instr.I64Or -> nextBinOp(popLong(), popLong()) { a, b -> a or b }
is Node.Instr.I64Xor -> nextBinOp(popLong(), popLong()) { a, b -> a xor b }
is Node.Instr.I64Shl -> nextBinOp(popLong(), popLong()) { a, b -> a shl b.toInt() }
is Node.Instr.I64ShrS -> nextBinOp(popLong(), popLong()) { a, b -> a shr b.toInt() }
is Node.Instr.I64ShrU -> nextBinOp(popLong(), popLong()) { a, b -> a ushr b.toInt() }
is Node.Instr.I64Rotl -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.rotateLeft(a, b.toInt()) }
is Node.Instr.I64Rotr -> nextBinOp(popLong(), popLong()) { a, b -> java.lang.Long.rotateRight(a, b.toInt()) }
is Node.Instr.F32Abs -> next { push(Math.abs(popFloat())) }
is Node.Instr.F32Neg -> next { push(-popFloat()) }
is Node.Instr.F32Ceil -> next { push(Math.ceil(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Floor -> next { push(Math.floor(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Trunc -> next {
popFloat().toDouble().let { push((if (it >= 0.0) Math.floor(it) else Math.ceil(it)).toFloat()) }
}
is Node.Instr.F32Nearest -> next { push(Math.rint(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Sqrt -> next { push(Math.sqrt(popFloat().toDouble()).toFloat()) }
is Node.Instr.F32Add -> nextBinOp(popFloat(), popFloat()) { a, b -> a + b }
is Node.Instr.F32Sub -> nextBinOp(popFloat(), popFloat()) { a, b -> a - b }
is Node.Instr.F32Mul -> nextBinOp(popFloat(), popFloat()) { a, b -> a * b }
is Node.Instr.F32Div -> nextBinOp(popFloat(), popFloat()) { a, b -> a / b }
is Node.Instr.F32Min -> nextBinOp(popFloat(), popFloat()) { a, b -> Math.min(a, b) }
is Node.Instr.F32Max -> nextBinOp(popFloat(), popFloat()) { a, b -> Math.max(a, b) }
is Node.Instr.F32CopySign -> nextBinOp(popFloat(), popFloat()) { a, b -> Math.copySign(a, b) }
is Node.Instr.F64Abs -> next { push(Math.abs(popDouble())) }
is Node.Instr.F64Neg -> next { push(-popDouble()) }
is Node.Instr.F64Ceil -> next { push(Math.ceil(popDouble())) }
is Node.Instr.F64Floor -> next { push(Math.floor(popDouble())) }
is Node.Instr.F64Trunc -> next {
popDouble().let { push((if (it >= 0.0) Math.floor(it) else Math.ceil(it))) }
}
is Node.Instr.F64Nearest -> next { push(Math.rint(popDouble())) }
is Node.Instr.F64Sqrt -> next { push(Math.sqrt(popDouble())) }
is Node.Instr.F64Add -> nextBinOp(popDouble(), popDouble()) { a, b -> a + b }
is Node.Instr.F64Sub -> nextBinOp(popDouble(), popDouble()) { a, b -> a - b }
is Node.Instr.F64Mul -> nextBinOp(popDouble(), popDouble()) { a, b -> a * b }
is Node.Instr.F64Div -> nextBinOp(popDouble(), popDouble()) { a, b -> a / b }
is Node.Instr.F64Min -> nextBinOp(popDouble(), popDouble()) { a, b -> Math.min(a, b) }
is Node.Instr.F64Max -> nextBinOp(popDouble(), popDouble()) { a, b -> Math.max(a, b) }
is Node.Instr.F64CopySign -> nextBinOp(popDouble(), popDouble()) { a, b -> Math.copySign(a, b) }
is Node.Instr.I32WrapI64 -> next { push(popLong().toInt()) }
// TODO: trunc traps on overflow!
is Node.Instr.I32TruncSF32 -> next {
push(ctx.checkedTrunc(popFloat(), true) { it.toInt() })
}
is Node.Instr.I32TruncUF32 -> next {
push(ctx.checkedTrunc(popFloat(), false) { it.toLong().toInt() })
}
is Node.Instr.I32TruncSF64 -> next {
push(ctx.checkedTrunc(popDouble(), true) { it.toInt() })
}
is Node.Instr.I32TruncUF64 -> next {
push(ctx.checkedTrunc(popDouble(), false) { it.toLong().toInt() })
}
is Node.Instr.I64ExtendSI32 -> next { push(popInt().toLong()) }
is Node.Instr.I64ExtendUI32 -> next { push(popInt().toUnsignedLong()) }
is Node.Instr.I64TruncSF32 -> next {
push(ctx.checkedTrunc(popFloat(), true) { it.toLong() })
}
is Node.Instr.I64TruncUF32 -> next {
push(ctx.checkedTrunc(popFloat(), false) {
// If over max long, subtract and negate
if (it < 9223372036854775807f) it.toLong()
else (-9223372036854775808f + (it - 9223372036854775807f)).toLong()
})
}
is Node.Instr.I64TruncSF64 -> next {
push(ctx.checkedTrunc(popDouble(), true) { it.toLong() })
}
is Node.Instr.I64TruncUF64 -> next {
push(ctx.checkedTrunc(popDouble(), false) {
// If over max long, subtract and negate
if (it < 9223372036854775807.0) it.toLong()
else (-9223372036854775808.0 + (it - 9223372036854775807.0)).toLong()
})
}
is Node.Instr.F32ConvertSI32 -> next { push(popInt().toFloat()) }
is Node.Instr.F32ConvertUI32 -> next { push(popInt().toUnsignedLong().toFloat()) }
is Node.Instr.F32ConvertSI64 -> next { push(popLong().toFloat()) }
is Node.Instr.F32ConvertUI64 -> next {
push(popLong().let { if (it >= 0) it.toFloat() else (it ushr 1).toFloat() * 2f })
}
is Node.Instr.F32DemoteF64 -> next { push(popDouble().toFloat()) }
is Node.Instr.F64ConvertSI32 -> next { push(popInt().toDouble()) }
is Node.Instr.F64ConvertUI32 -> next { push(popInt().toUnsignedLong().toDouble()) }
is Node.Instr.F64ConvertSI64 -> next { push(popLong().toDouble()) }
is Node.Instr.F64ConvertUI64 -> next {
push(popLong().let { if (it >= 0) it.toDouble() else ((it ushr 1) or (it and 1)) * 2.0 })
}
is Node.Instr.F64PromoteF32 -> next { push(popFloat().toDouble()) }
is Node.Instr.I32ReinterpretF32 -> next { push(java.lang.Float.floatToRawIntBits(popFloat())) }
is Node.Instr.I64ReinterpretF64 -> next { push(java.lang.Double.doubleToRawLongBits(popDouble())) }
is Node.Instr.F32ReinterpretI32 -> next { push(java.lang.Float.intBitsToFloat(popInt())) }
is Node.Instr.F64ReinterpretI64 -> next { push(java.lang.Double.longBitsToDouble(popLong())) }
}
}
}
companion object : Interpreter()
// Creating this does all the initialization except execute the start function
data class Context(
val mod: Node.Module,
val logger: Logger = Logger.Print(Logger.Level.OFF),
val interpreter: Interpreter = Interpreter.Companion,
val imports: Imports = Imports.None,
val defaultMaxMemPages: Int = 1,
val memByteBufferDirect: Boolean = true,
val checkTruncOverflow: Boolean = true,
val checkSignedDivIntegerOverflow: Boolean = true,
val maximumCallStackDepth: Int = 3000
) {
val callStack = mutableListOf<FuncContext>()
val currFuncCtx get() = callStack.last()
val maybeCurrFuncCtx get() = callStack.lastOrNull()
val exportsByName = mod.exports.map { it.field to it }.toMap()
fun exportIndex(field: String, kind: Node.ExternalKind) =
exportsByName[field]?.takeIf { it.kind == kind }?.index
val importGlobals = mod.imports.filter { it.kind is Node.Import.Kind.Global }
fun singleConstant(instrs: List<Node.Instr>): Number? = instrs.singleOrNull().let { instr ->
when (instr) {
is Node.Instr.Args.Const<*> -> instr.value
is Node.Instr.GetGlobal -> importGlobals.getOrNull(instr.index).let {
it ?: throw CompileErr.UnknownGlobal(instr.index)
imports.getGlobal(it.module, it.field, (it.kind as Node.Import.Kind.Global).type)
}
else -> null
}
}
val maybeMem = run {
// Import it if we can, otherwise make it
val memImport = mod.imports.singleOrNull { it.kind is Node.Import.Kind.Memory }
// TODO: validate imported memory
val mem =
if (memImport != null) imports.getMemory(
memImport.module,
memImport.field,
(memImport.kind as Node.Import.Kind.Memory).type
) else mod.memories.singleOrNull()?.let { memType ->
val max = (memType.limits.maximum ?: defaultMaxMemPages) * Mem.PAGE_SIZE
val mem = if (memByteBufferDirect) ByteBuffer.allocateDirect(max) else ByteBuffer.allocate(max)
mem.apply {
order(ByteOrder.LITTLE_ENDIAN)
limit(memType.limits.initial * Mem.PAGE_SIZE)
}
}
mem?.also { mem ->
// Load all data
mod.data.forEach { data ->
val pos = singleConstant(data.offset) as? Int ?: throw CompileErr.OffsetNotConstant()
if (pos < 0 || pos + data.data.size > mem.limit())
throw RunErr.InvalidDataIndex(pos, data.data.size, mem.limit())
mem.duplicate().apply { position(pos) }.put(data.data)
}
}
}
val mem get() = maybeMem ?: throw CompileErr.UnknownMemory(0)
// TODO: some of this shares with the compiler's context, so how about some code reuse?
val importFuncs = mod.imports.filter { it.kind is Node.Import.Kind.Func }
fun typeAtIndex(index: Int) = mod.types.getOrNull(index) ?: throw CompileErr.UnknownType(index)
fun funcAtIndex(index: Int) = importFuncs.getOrNull(index).let {
when (it) {
null -> Either.Right(mod.funcs.getOrNull(index - importFuncs.size) ?: throw CompileErr.UnknownFunc(index))
else -> Either.Left(it)
}
}
fun funcTypeAtIndex(index: Int) = funcAtIndex(index).let {
when (it) {
is Either.Left -> typeAtIndex((it.v.kind as Node.Import.Kind.Func).typeIndex)
is Either.Right -> it.v.type
}
}
fun boundFuncMethodHandleAtIndex(index: Int): MethodHandle {
val type = funcTypeAtIndex(index).let {
MethodType.methodType(it.ret?.jclass ?: Void.TYPE, it.params.map { it.jclass })
}
val origMh = MethodHandles.lookup().bind(interpreter, "execFunc", MethodType.methodType(
Number::class.java, Context::class.java, Int::class.java, Array<Number>::class.java))
return MethodHandles.insertArguments(origMh, 0, this, index).
asVarargsCollector(Array<Number>::class.java).asType(type)
}
val moduleGlobals = mod.globals.mapIndexed { index, global ->
// In MVP all globals have an init, it's either a const or an import read
val initVal = singleConstant(global.init) ?: throw CompileErr.GlobalInitNotConstant(index)
if (initVal.valueType != global.type.contentType)
throw CompileErr.GlobalConstantMismatch(index, global.type.contentType.typeRef, initVal::class.ref)
initVal
}.toMutableList()
fun globalTypeAtIndex(index: Int) =
(importGlobals.getOrNull(index)?.kind as? Node.Import.Kind.Global)?.type ?:
mod.globals[index - importGlobals.size].type
fun getGlobal(index: Int): Number = importGlobals.getOrNull(index).let { importGlobal ->
if (importGlobal != null) imports.getGlobal(
importGlobal.module,
importGlobal.field,
(importGlobal.kind as Node.Import.Kind.Global).type
) else moduleGlobals.getOrNull(index - importGlobals.size) ?: error("No global")
}
fun setGlobal(index: Int, v: Number) {
val importGlobal = importGlobals.getOrNull(index)
if (importGlobal != null) imports.setGlobal(
importGlobal.module,
importGlobal.field,
(importGlobal.kind as Node.Import.Kind.Global).type,
v
) else (index - importGlobals.size).also { index ->
require(index < moduleGlobals.size)
moduleGlobals[index] = v
}
}
val table = run {
val importTable = mod.imports.singleOrNull { it.kind is Node.Import.Kind.Table }
val table = (importTable?.kind as? Node.Import.Kind.Table)?.type ?: mod.tables.singleOrNull()
if (table == null && mod.elems.isNotEmpty()) throw CompileErr.UnknownTable(0)
table?.let { table ->
// Create array either cloned from import or fresh
val arr = importTable?.let { imports.getTable(it.module, it.field, table) } ?:
arrayOfNulls(table.limits.initial)
// Now put all the elements in there
mod.elems.forEach { elem ->
require(elem.index == 0)
// Offset index always a constant or import
val offsetVal = singleConstant(elem.offset) as? Int ?: throw CompileErr.OffsetNotConstant()
// Still have to validate offset even if no func indexes
if (offsetVal < 0 || offsetVal + elem.funcIndices.size > arr.size)
throw RunErr.InvalidElemIndex(offsetVal, elem.funcIndices.size, arr.size)
elem.funcIndices.forEachIndexed { index, funcIndex ->
arr[offsetVal + index] = boundFuncMethodHandleAtIndex(funcIndex)
}
}
arr
}
}
fun <T : Number> checkedTrunc(orig: Float, signed: Boolean, to: (Float) -> T) = to(orig).also {
if (checkTruncOverflow) {
if (orig.isNaN()) throw InterpretErr.TruncIntegerNaN(orig, it.valueType!!, signed)
val invalid =
(it is Int && signed && (orig < -2147483648f || orig >= 2147483648f)) ||
(it is Int && !signed && (orig.toInt() < 0 || orig >= 4294967296f)) ||
(it is Long && signed && (orig < -9223372036854775807f || orig >= 9223372036854775807f)) ||
(it is Long && !signed && (orig.toInt() < 0 || orig >= 18446744073709551616f))
if (invalid) throw InterpretErr.TruncIntegerOverflow(orig, it.valueType!!, signed)
}
}
fun <T : Number> checkedTrunc(orig: Double, signed: Boolean, to: (Double) -> T) = to(orig).also {
if (checkTruncOverflow) {
if (orig.isNaN()) throw InterpretErr.TruncIntegerNaN(orig, it.valueType!!, signed)
val invalid =
(it is Int && signed && (orig < -2147483648.0 || orig >= 2147483648.0)) ||
(it is Int && !signed && (orig.toInt() < 0 || orig >= 4294967296.0)) ||
(it is Long && signed && (orig < -9223372036854775807.0 || orig >= 9223372036854775807.0)) ||
(it is Long && !signed && (orig.toInt() < 0 || orig >= 18446744073709551616.0))
if (invalid) throw InterpretErr.TruncIntegerOverflow(orig, it.valueType!!, signed)
}
}
fun checkedSignedDivInteger(a: Int, b: Int) {
if (checkSignedDivIntegerOverflow && (a == Int.MIN_VALUE && b == -1))
throw InterpretErr.SignedDivOverflow(a, b)
}
fun checkedSignedDivInteger(a: Long, b: Long) {
if (checkSignedDivIntegerOverflow && (a == Long.MIN_VALUE && b == -1L))
throw InterpretErr.SignedDivOverflow(a, b)
}
fun checkNextIsntStackOverflow() {
// TODO: note this doesn't keep count of imports and their call stack
if (callStack.size + 1 >= maximumCallStackDepth) {
// We blow away the entire stack here so code can continue...could provide stack to
// exception if we wanted
callStack.clear()
throw InterpretErr.StackOverflow(maximumCallStackDepth)
}
}
}
data class FuncContext(
val funcIndex: Int,
val func: Node.Func,
val valueStack: MutableList<Number> = mutableListOf(),
val blockStack: MutableList<Block> = mutableListOf(),
var insnIndex: Int = 0
) {
val locals = (func.type.params + func.locals).map {
when (it) {
is Node.Type.Value.I32 -> 0 as Number
is Node.Type.Value.I64 -> 0L as Number
is Node.Type.Value.F32 -> 0f as Number
is Node.Type.Value.F64 -> 0.0 as Number
}
}.toMutableList()
fun peek() = valueStack.last()
fun pop() = valueStack.removeAt(valueStack.size - 1)
fun popInt() = pop() as Int
fun popLong() = pop() as Long
fun popFloat() = pop() as Float
fun popDouble() = pop() as Double
fun Node.Instr.Args.AlignOffset.popMemAddr(): Int {
val v = popInt()
if (offset > Int.MAX_VALUE || offset + v > Int.MAX_VALUE) throw InterpretErr.OutOfBoundsMemory(v, offset)
return v + offset.toInt()
}
fun pop(type: Node.Type.Value): Number = when (type) {
is Node.Type.Value.I32 -> popInt()
is Node.Type.Value.I64 -> popLong()
is Node.Type.Value.F32 -> popFloat()
is Node.Type.Value.F64 -> popDouble()
}
fun popCallArgs(type: Node.Type.Func) = type.params.reversed().map(::pop).reversed()
fun push(v: Number) { valueStack += v }
fun push(v: Boolean) { valueStack += if (v) 1 else 0 }
fun currentBlockEndOrElse(end: Boolean): Int? {
// Find the next end/else
var blockDepth = 0
val index = func.instructions.drop(insnIndex + 1).indexOfFirst { insn ->
// Increase block depth if necessary
when (insn) { is Node.Instr.Block, is Node.Instr.Loop, is Node.Instr.If -> blockDepth++ }
// If we're at the end of ourself but not looking for end, short-circuit a failure
if (blockDepth == 0 && !end && insn is Node.Instr.End) return null
// Did we find an end or an else on ourself?
val found = blockDepth == 0 && ((end && insn is Node.Instr.End) || (!end && insn is Node.Instr.Else))
if (blockDepth > 0 && insn is Node.Instr.End) blockDepth--
found
}
return if (index == -1) null else index + insnIndex + 1
}
fun currentBlockEnd() = currentBlockEndOrElse(true)
fun currentBlockElse(): Int? = currentBlockEndOrElse(false)
inline fun next(crossinline f: () -> Unit) = StepResult.Next.also { f() }
inline fun <T, U> nextBinOp(second: T, first: U, crossinline f: (U, T) -> Any) = StepResult.Next.also {
val v = f(first, second)
if (v is Boolean) push(v) else push(v as Number)
}
}
data class Block(
val startIndex: Int,
val insn: Node.Instr.Args.Type,
val stackSizeAtStart: Int,
val endIndex: Int,
val elseIndex: Int? = null
)
sealed class StepResult {
object Next : StepResult()
data class Branch(
val blockDepth: Int,
val failedIf: Boolean = false,
val forceEndOnLoop: Boolean = false
) : StepResult()
data class Call(
val funcIndex: Int,
val args: List<Number>,
val type: Node.Type.Func
) : StepResult()
data class CallIndirect(
val tableIndex: Int,
val args: List<Number>,
val type: Node.Type.Func
) : StepResult()
object Unreachable : StepResult()
data class Return(val v: Number?) : StepResult()
}
} | compiler/src/main/kotlin/asmble/run/jvm/interpret/Interpreter.kt | 1595350673 |
package tonnysunm.com.acornote.ui.label
import android.app.Activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_labels.*
import tonnysunm.com.acornote.R
class LabelListActivity : AppCompatActivity(R.layout.activity_labels) {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.title = null
}
override fun onSupportNavigateUp(): Boolean {
setResult(Activity.RESULT_CANCELED)
finish()
return true
}
}
| Acornote_Kotlin/app/src/main/java/tonnysunm/com/acornote/ui/label/LabelListActivity.kt | 3193566572 |
package asmble.run.jvm.interpret
import asmble.ast.Node
import asmble.compile.jvm.jclass
import asmble.run.jvm.Module
import asmble.run.jvm.ModuleBuilder
import asmble.util.Logger
import java.lang.invoke.MethodHandles
import java.lang.invoke.MethodType
import java.nio.ByteBuffer
class RunModule(
override val name: String?,
val ctx: Interpreter.Context
) : Module {
override fun exportedFunc(field: String) =
ctx.exportIndex(field, Node.ExternalKind.FUNCTION)?.let { ctx.boundFuncMethodHandleAtIndex(it) }
override fun exportedGlobal(field: String) = ctx.exportIndex(field, Node.ExternalKind.GLOBAL)?.let { index ->
val type = ctx.globalTypeAtIndex(index)
val lookup = MethodHandles.lookup()
var getter = lookup.bind(ctx, "getGlobal",
MethodType.methodType(Number::class.java, Int::class.javaPrimitiveType))
var setter = if (!type.mutable) null else lookup.bind(ctx, "setGlobal", MethodType.methodType(
Void::class.javaPrimitiveType, Int::class.javaPrimitiveType, Number::class.java))
// Cast number to specific type
getter = MethodHandles.explicitCastArguments(getter,
MethodType.methodType(type.contentType.jclass, Int::class.javaPrimitiveType))
if (setter != null)
setter = MethodHandles.explicitCastArguments(setter, MethodType.methodType(
Void::class.javaPrimitiveType, Int::class.javaPrimitiveType, type.contentType.jclass))
// Insert the index argument up front
getter = MethodHandles.insertArguments(getter, 0, index)
if (setter != null) setter = MethodHandles.insertArguments(setter, 0, index)
getter to setter
}
@SuppressWarnings("UNCHECKED_CAST")
override fun <T> exportedMemory(field: String, memClass: Class<T>) =
ctx.exportIndex(field, Node.ExternalKind.MEMORY)?.let { index ->
require(index == 0 && memClass == ByteBuffer::class.java)
ctx.maybeMem as? T?
}
override fun exportedTable(field: String) =
ctx.exportIndex(field, Node.ExternalKind.TABLE)?.let { index ->
require(index == 0)
ctx.table
}
class Builder(
val logger: Logger = Logger.Print(Logger.Level.OFF),
val defaultMaxMemPages: Int = 1,
val memByteBufferDirect: Boolean = true
) : ModuleBuilder<RunModule> {
override fun build(
imports: Module.ImportResolver,
mod: Node.Module,
className: String,
name: String?
) = RunModule(
name = name,
ctx = Interpreter.Context(
mod = mod,
logger = logger,
imports = ResolverImports(imports),
defaultMaxMemPages = defaultMaxMemPages,
memByteBufferDirect = memByteBufferDirect
).also { ctx ->
// Run start function if present
mod.startFuncIndex?.also { Interpreter.execFunc(ctx, it) }
}
)
}
class ResolverImports(val res: Module.ImportResolver) : Imports {
override fun invokeFunction(module: String, field: String, type: Node.Type.Func, args: List<Number>) =
res.resolveImportFunc(module, field, type).invokeWithArguments(args) as Number?
override fun getGlobal(module: String, field: String, type: Node.Type.Global) =
res.resolveImportGlobal(module, field, type).first.invokeWithArguments() as Number
override fun setGlobal(module: String, field: String, type: Node.Type.Global, value: Number) {
res.resolveImportGlobal(module, field, type).second!!.invokeWithArguments(value)
}
override fun getMemory(module: String, field: String, type: Node.Type.Memory) =
res.resolveImportMemory(module, field, type, ByteBuffer::class.java)
override fun getTable(module: String, field: String, type: Node.Type.Table) =
res.resolveImportTable(module, field, type)
}
} | compiler/src/main/kotlin/asmble/run/jvm/interpret/RunModule.kt | 1094143375 |
package com.theostanton.lfgss.conversation
import android.os.Bundle
import com.theostanton.lfgss.listitem.ListItemActivity
import kotlinx.android.synthetic.main.activity_listitem.*
/**
* Created by theostanton on 22/02/16.
*/
class ConActivity : ListItemActivity() {
override val fromBottom = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
recyclerView.setupMoreListener(
{
numberOfItems,numberBefore,currPos->
recyclerView.removeMoreListener()
(presenter as ConversationPresenter).more(numberOfItems)
},10)
}
override fun createPresenter() = ConversationPresenter(intent.getIntExtra("id",0),intent.getIntExtra("totalComments",-1))
} | app/src/main/java/com/theostanton/lfgss/conversation/ConActivity.kt | 2147928993 |
/*
* Copyright 2022 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.
*/
@file:Incubating
@file:Suppress("EXTENSION_SHADOWED_BY_MEMBER")
package org.gradle.kotlin.dsl
import org.gradle.api.Action
import org.gradle.api.Incubating
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.FileCollectionDependency
import org.gradle.api.artifacts.MinimalExternalModuleDependency
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.Dependencies
import org.gradle.api.artifacts.dsl.DependencyAdder
import org.gradle.api.artifacts.dsl.DependencyFactory
import org.gradle.api.artifacts.dsl.DependencyModifier
import org.gradle.api.artifacts.dsl.GradleDependencies
import org.gradle.api.file.FileCollection
import org.gradle.api.provider.Provider
import org.gradle.api.provider.ProviderConvertible
/**
* This file is used to add [Kotlin extension functions](https://kotlinlang.org/docs/extensions.html) to [Dependencies], [DependencyAdder] and [DependencyModifier] to make the Kotlin DSL more idiomatic.
*
* These extension functions allow an interface to implement a dependencies block in the Kotlin DSL by
* - exposing an instance of [DependencyAdder] to add dependencies without explicitly calling [DependencyAdder.add]
* - exposing an instance of [DependencyModifier] to modify dependencies without explicitly calling [DependencyModifier.modify]
*
* There are `invoke(...)` equivalents for all the `add(...)` methods in [DependencyAdder].
*
* There are `invoke(...)` equivalents for all the `modify(...)` methods in [DependencyModifier].
*
* @since 8.0
*
* @see org.gradle.api.internal.artifacts.dsl.dependencies.DependenciesExtensionModule
* @see Dependencies
* @see DependencyAdder
* @see DependencyModifier
* @see DependencyFactory
*
* @sample DependenciesExtensions.sample
*/
@Suppress("unused")
private
class DependenciesExtensions {
interface MyDependencies : GradleDependencies {
val implementation: DependencyAdder
val testFixtures: DependencyModifier
operator fun invoke(action: Action<in MyDependencies>)
}
fun sample(dependencies: MyDependencies) {
// In a Kotlin DSL build script
dependencies {
// Add a dependency by String
implementation("org:foo:1.0") // is getImplementation().add("org:foo:1.0")
// Add a dependency with explicit coordinate parameters
implementation(module(group = "org", name = "foo", version = "1.0")) // is getImplementation().add(module("org", "foo", "1.0"))
// Add dependencies on projects
implementation(project(":path")) // is getImplementation().add(project(":path"))
implementation(project()) // is getImplementation().add(project())
// Add a dependency on the Gradle API
implementation(gradleApi()) // is getImplementation().add(gradleApi())
// Modify a dependency to select test fixtures
implementation(testFixtures("org:foo:1.0")) // is getImplementation().add(getTestFixtures().modify("org:foo:1.0"))
}
}
}
/**
* Creates a dependency based on the group, name and version (GAV) coordinates.
*
* @since 8.0
*/
fun Dependencies.module(group: String?, name: String, version: String?): ExternalModuleDependency = module(group, name, version)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun <D : ModuleDependency> DependencyModifier.invoke(dependency: D): D = modify(dependency)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun DependencyModifier.invoke(dependencyNotation: CharSequence): ExternalModuleDependency = modify(dependencyNotation)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun DependencyModifier.invoke(dependency: ProviderConvertible<out MinimalExternalModuleDependency>): Provider<out MinimalExternalModuleDependency> = modify(dependency)
/**
* Modifies a dependency to select the variant of the given module.
*
* @see DependencyModifier
* @since 8.0
*/
operator fun DependencyModifier.invoke(dependency: Provider<out ModuleDependency>): Provider<out ModuleDependency> = modify(dependency)
/**
* Add a dependency.
*
* @param dependencyNotation dependency to add
* @see DependencyFactory.create
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependencyNotation: CharSequence) = add(dependencyNotation)
/**
* Add a dependency.
*
* @param dependencyNotation dependency to add
* @param configuration an action to configure the dependency
* @see DependencyFactory.create
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependencyNotation: CharSequence, configuration: Action<in ExternalModuleDependency>) = add(dependencyNotation, configuration)
/**
* Add a dependency.
*
* @param files files to add as a dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(files: FileCollection) = add(files)
/**
* Add a dependency.
*
* @param files files to add as a dependency
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(files: FileCollection, configuration: Action<in FileCollectionDependency>) = add(files, configuration)
/**
* Add a dependency.
*
* @param externalModule external module to add as a dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(externalModule: ProviderConvertible<out MinimalExternalModuleDependency>) = add(externalModule)
/**
* Add a dependency.
*
* @param externalModule external module to add as a dependency
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun DependencyAdder.invoke(externalModule: ProviderConvertible<out MinimalExternalModuleDependency>, configuration: Action<in ExternalModuleDependency>) = add(externalModule, configuration)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependency: Dependency) = add(dependency)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun <D : Dependency> DependencyAdder.invoke(dependency: D, configuration: Action<in D>) = add(dependency, configuration)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @since 8.0
*/
operator fun DependencyAdder.invoke(dependency: Provider<out Dependency>) = add(dependency)
/**
* Add a dependency.
*
* @param dependency dependency to add
* @param configuration an action to configure the dependency
* @since 8.0
*/
operator fun <D : Dependency> DependencyAdder.invoke(dependency: Provider<out D>, configuration: Action<in D>) = add(dependency, configuration)
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/DependenciesExtensions.kt | 1459070321 |
/*
* 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.execution
/**
* The result of partially evaluating a Kotlin DSL [program][Program] of a certain [kind][ProgramKind]
* against a given [target][ProgramTarget].
*
* @see PartialEvaluator.reduce
*/
internal
sealed class ResidualProgram {
/**
* A static residue, can be compiled ahead of time.
*/
data class Static(val instructions: List<Instruction>) : ResidualProgram() {
constructor(vararg instructions: Instruction) :
this(instructions.toList())
}
/**
* A dynamic script [source] residue, can only be compiled after the execution of the static [prelude] at runtime.
*/
data class Dynamic(val prelude: Static, val source: ProgramSource) : ResidualProgram()
sealed class Instruction {
/**
* Causes the configuration of the embedded Kotlin libraries
* on the host's ScriptHandler.
*/
object SetupEmbeddedKotlin : Instruction()
/**
* Causes the target scope to be closed without applying any plugins.
*/
object CloseTargetScope : StageTransition, Instruction()
/**
* Causes the target scope to be closed by applying a default set of plugin requests that includes
* the set of [auto-applied plugins][org.gradle.plugin.management.internal.autoapply.AutoAppliedPluginHandler].
*/
object ApplyDefaultPluginRequests : StageTransition, Instruction()
/**
* Causes the target scope to be closed by applying the plugin requests collected during the execution
* of the given [program] plus the set of [auto-applied plugins][org.gradle.plugin.management.internal.autoapply.AutoAppliedPluginHandler].
*/
data class ApplyPluginRequestsOf(val program: Program.Stage1) : StageTransition, Instruction()
/**
* An instruction that marks the transition from stage 1 to stage 2 by causing the
* target scope to be closed thus making the resolved classpath available to stage 2.
*
* A valid [Static] program must contain one and only one [StageTransition] instruction.
*/
interface StageTransition
/**
* Causes the Kotlin DSL base plugins to be applied.
*/
object ApplyBasePlugins : Instruction()
/**
* Causes the evaluation of the precompiled [script] against the script host.
*/
data class Eval(val script: ProgramSource) : Instruction()
override fun toString(): String = javaClass.simpleName
}
}
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/execution/ResidualProgram.kt | 4155342209 |
package org.nield.kotlinstatistics.range
class InvalidRangeException(msg: String): Exception(msg) | src/main/kotlin/org/nield/kotlinstatistics/range/InvalidRangeException.kt | 2943335774 |
/*
* 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.integration
import org.gradle.kotlin.dsl.fixtures.AbstractPluginTest
/**
* Base class for tests that require plugins from `:plugins`.
*/
open class AbstractPluginIntegrationTest : AbstractPluginTest()
| subprojects/kotlin-dsl-integ-tests/src/integTest/kotlin/org/gradle/kotlin/dsl/integration/AbstractPluginIntegrationTest.kt | 2682928807 |
package guideme.volunteers.ui.fragments.genericlist
interface GenericItem <out T>{
val title : String
val subTitle : String
val imageUrl : String
val data : T
}
class GenericItemImpl<T>(override val title: String, override val subTitle: String, override val imageUrl: String, override val data: T) : GenericItem<T>
| app/src/main/java/guideme/volunteers/ui/fragments/genericlist/GenericItem.kt | 527330439 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.listener
import android.os.SystemClock
import android.util.Pair
import com.facebook.common.logging.FLog
import com.facebook.imagepipeline.request.ImageRequest
import java.util.HashMap
import javax.annotation.concurrent.GuardedBy
/** Logging for [ImageRequest]s. */
class RequestLoggingListener : RequestListener {
@GuardedBy("this")
private val producerStartTimeMap: MutableMap<Pair<String, String>, Long> = HashMap()
@GuardedBy("this") private val requestStartTimeMap: MutableMap<String, Long> = HashMap()
@Synchronized
override fun onRequestStart(
request: ImageRequest,
callerContextObject: Any,
requestId: String,
isPrefetch: Boolean
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
FLog.v(
TAG,
"time %d: onRequestSubmit: {requestId: %s, callerContext: %s, isPrefetch: %b}",
time,
requestId,
callerContextObject,
isPrefetch)
requestStartTimeMap[requestId] = time
}
}
@Synchronized
override fun onProducerStart(requestId: String, producerName: String) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = time
producerStartTimeMap[mapKey] = startTime
FLog.v(
TAG,
"time %d: onProducerStart: {requestId: %s, producer: %s}",
startTime,
requestId,
producerName)
}
}
@Synchronized
override fun onProducerFinishWithSuccess(
requestId: String,
producerName: String,
extraMap: Map<String, String>?
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.v(
TAG,
"time %d: onProducerFinishWithSuccess: {requestId: %s, producer: %s, elapsedTime: %d ms, extraMap: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap)
}
}
@Synchronized
override fun onProducerFinishWithFailure(
requestId: String,
producerName: String,
throwable: Throwable,
extraMap: Map<String, String>?
) {
if (FLog.isLoggable(FLog.WARN)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.w(
TAG,
throwable,
"time %d: onProducerFinishWithFailure: {requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s, throwable: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap,
throwable.toString())
}
}
@Synchronized
override fun onProducerFinishWithCancellation(
requestId: String,
producerName: String,
extraMap: Map<String, String>?
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.v(
TAG,
"time %d: onProducerFinishWithCancellation: {requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
extraMap)
}
}
@Synchronized
override fun onProducerEvent(requestId: String, producerName: String, producerEventName: String) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap[mapKey]
val currentTime = time
FLog.v(
TAG,
"time %d: onProducerEvent: {requestId: %s, stage: %s, eventName: %s; elapsedTime: %d ms}",
time,
requestId,
producerName,
producerEventName,
getElapsedTime(startTime, currentTime))
}
}
@Synchronized
override fun onUltimateProducerReached(
requestId: String,
producerName: String,
successful: Boolean
) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val mapKey = Pair.create(requestId, producerName)
val startTime = producerStartTimeMap.remove(mapKey)
val currentTime = time
FLog.v(
TAG,
"time %d: onUltimateProducerReached: {requestId: %s, producer: %s, elapsedTime: %d ms, success: %b}",
currentTime,
requestId,
producerName,
getElapsedTime(startTime, currentTime),
successful)
}
}
@Synchronized
override fun onRequestSuccess(request: ImageRequest, requestId: String, isPrefetch: Boolean) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val startTime = requestStartTimeMap.remove(requestId)
val currentTime = time
FLog.v(
TAG,
"time %d: onRequestSuccess: {requestId: %s, elapsedTime: %d ms}",
currentTime,
requestId,
getElapsedTime(startTime, currentTime))
}
}
@Synchronized
override fun onRequestFailure(
request: ImageRequest,
requestId: String,
throwable: Throwable,
isPrefetch: Boolean
) {
if (FLog.isLoggable(FLog.WARN)) {
val startTime = requestStartTimeMap.remove(requestId)
val currentTime = time
FLog.w(
TAG,
"time %d: onRequestFailure: {requestId: %s, elapsedTime: %d ms, throwable: %s}",
currentTime,
requestId,
getElapsedTime(startTime, currentTime),
throwable.toString())
}
}
@Synchronized
override fun onRequestCancellation(requestId: String) {
if (FLog.isLoggable(FLog.VERBOSE)) {
val startTime = requestStartTimeMap.remove(requestId)
val currentTime = time
FLog.v(
TAG,
"time %d: onRequestCancellation: {requestId: %s, elapsedTime: %d ms}",
currentTime,
requestId,
getElapsedTime(startTime, currentTime))
}
}
override fun requiresExtraMap(id: String): Boolean = FLog.isLoggable(FLog.VERBOSE)
companion object {
private const val TAG = "RequestLoggingListener"
private fun getElapsedTime(startTime: Long?, endTime: Long): Long =
if (startTime != null) {
endTime - startTime
} else {
-1
}
private val time: Long
get() = SystemClock.uptimeMillis()
}
}
| imagepipeline/src/main/java/com/facebook/imagepipeline/listener/RequestLoggingListener.kt | 2554323201 |
package vip.frendy.news.activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AppCompatActivity
import vip.frendy.news.R
/**
* Created by iimedia on 2017/3/23.
*/
open class BaseFragmentActivity : AppCompatActivity() {
protected var currentFragment: Fragment ?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fragment_base)
}
protected fun setDefaultFragment(fragment: Fragment) {
// 开启Fragment事务
val fragmentTransaction = supportFragmentManager.beginTransaction()
// 使用fragment的布局替代frame_layout的控件并提交事务
fragmentTransaction.replace(R.id.frame_layout, fragment).commit()
currentFragment = fragment
}
protected fun switchFragment(fragment: Fragment) {
if (fragment !== currentFragment) {
if (!fragment.isAdded) {
supportFragmentManager.beginTransaction().hide(currentFragment)
.add(R.id.frame_layout, fragment).commit()
} else {
supportFragmentManager.beginTransaction().hide(currentFragment)
.show(fragment).commit()
}
currentFragment = fragment
}
}
override fun onResume() {
super.onResume()
currentFragment?.userVisibleHint = true
}
override fun onPause() {
super.onPause()
currentFragment?.userVisibleHint = false
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
currentFragment?.onActivityResult(requestCode, resultCode, data)
}
override fun onDestroy() {
super.onDestroy()
}
}
| app/src/main/java/vip/frendy/news/activity/BaseFragmentActivity.kt | 146931716 |
package jp.bglb.bonboru.fluxutility.dtos.markers
import jp.bglb.bonboru.fluxutility.types.RequestStatus
/**
* Created by Tetsuya Masuda on 2016/07/01.
*/
interface AsyncLoadable {
fun updateRequestStatus(status: RequestStatus)
}
| flux-utility-kotlin/src/main/kotlin/jp/bglb/bonboru/fluxutility/dtos/markers/AsyncLoadable.kt | 458024219 |
package com.fastaccess.ui.modules.repos.extras.branches.pager
import com.fastaccess.data.dao.BranchesModel
/**
* Created by kosh on 15/07/2017.
*/
interface BranchesPagerListener {
fun onItemSelect(branch: BranchesModel)
} | app/src/main/java/com/fastaccess/ui/modules/repos/extras/branches/pager/BranchesPagerListener.kt | 1337149262 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.physics.box2d.dynamics
import com.almasb.fxgl.core.math.Vec2
import com.almasb.fxgl.physics.box2d.collision.shapes.Shape
/**
*
*
* @author Almas Baimagambetov ([email protected])
*/
enum class BodyType {
/**
* Zero mass, zero velocity, may be manually moved.
*/
STATIC,
/**
* Zero mass, non-zero velocity set by user, moved by solver.
*/
KINEMATIC,
/**
* Positive mass, non-zero velocity determined by forces, moved by solver.
*/
DYNAMIC
}
/**
* A body definition holds all the data needed to construct a rigid body.
* You can safely re-use body definitions.
* Shapes are added to a body after construction.
*/
class BodyDef {
/**
* The body type: static, kinematic, or dynamic.
* Note: if a dynamic body would have zero mass, the mass is set to one.
*/
var type = BodyType.STATIC
/**
* The world position of the body.
* Avoid creating bodies at the origin since this can lead to many overlapping shapes.
*/
var position = Vec2()
/**
* The world angle of the body in radians.
*/
var angle = 0f
/**
* The linear velocity of the body in world co-ordinates.
*/
var linearVelocity = Vec2()
/**
* The angular velocity of the body.
*/
var angularVelocity = 0f
/**
* Linear damping is used to reduce the linear velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
var linearDamping = 0f
/**
* Angular damping is use to reduce the angular velocity. The damping parameter can be larger than
* 1.0f but the damping effect becomes sensitive to the time step when the damping parameter is
* large.
*/
var angularDamping = 0f
/**
* Set this flag to false if this body should never fall asleep. Note that this increases CPU
* usage.
*/
var isAllowSleep = true
/**
* Is this body initially sleeping?
*/
var isAwake = true
/**
* Should this body be prevented from rotating? Useful for characters.
*/
var isFixedRotation = false
/**
* Is this a fast moving body that should be prevented from tunneling through other moving bodies?
* Note that all bodies are prevented from tunneling through kinematic and static bodies. This
* setting is only considered on dynamic bodies.
* You should use this flag sparingly since it increases processing time.
*/
var isBullet = false
/**
* Does this body start out active?
*/
var isActive = true
/**
* Experimental: scales the inertia tensor.
*/
var gravityScale = 1f
var userData: Any? = null
}
/**
* A fixture definition is used to create a fixture.
* This class defines an abstract fixture definition.
* You can reuse fixture definitions safely.
*/
class FixtureDef {
/**
* The friction coefficient, usually in the range [0,1].
*/
var friction = 0.2f
/**
* The restitution (elasticity) usually in the range [0,1].
*/
var restitution = 0.0f
/**
* The density, usually in kg/m^2
*/
var density = 0.0f
/**
* A sensor shape collects contact information but never generates a collision response.
*/
var isSensor = false
/**
* Contact filtering data
*/
var filter = Filter()
/**
* The shape, this must be set. The shape will be cloned, so you can create the shape on the
* stack.
*/
var shape: Shape? = null
var userData: Any? = null
fun copy(): FixtureDef {
val def = FixtureDef()
def.friction = friction
def.restitution = restitution
def.density = density
def.isSensor = isSensor
def.filter.set(filter)
def.shape = shape!!.clone()
def.userData = userData
return def
}
/* FLUENT API */
fun friction(friction: Float): FixtureDef {
this.friction = friction
return this
}
fun restitution(restitution: Float): FixtureDef {
this.restitution = restitution
return this
}
fun density(density: Float): FixtureDef {
this.density = density
return this
}
fun filter(filter: Filter): FixtureDef {
this.filter = filter
return this
}
fun shape(shape: Shape): FixtureDef {
this.shape = shape
return this
}
fun sensor(isSensor: Boolean): FixtureDef {
this.isSensor = isSensor
return this
}
fun userData(userData: Any): FixtureDef {
this.userData = userData
return this
}
} | fxgl-entity/src/main/kotlin/com/almasb/fxgl/physics/box2d/dynamics/Definitions.kt | 1372195299 |
package org.worshipsongs.service
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context.PRINT_SERVICE
import android.content.Intent
import android.graphics.Paint
import android.graphics.pdf.PdfDocument
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.print.PrintAttributes
import android.print.pdf.PrintedPdfDocument
import androidx.core.content.FileProvider
import android.util.Log
import android.view.ContextThemeWrapper
import android.view.Gravity
import android.view.View
import android.widget.PopupMenu
import androidx.appcompat.app.AppCompatActivity
import org.apache.commons.lang3.StringUtils
import org.worshipsongs.BuildConfig
import org.worshipsongs.CommonConstants
import org.worshipsongs.R
import org.worshipsongs.WorshipSongApplication
import org.worshipsongs.WorshipSongApplication.Companion.context
import org.worshipsongs.activity.CustomYoutubeBoxActivity
import org.worshipsongs.activity.PresentSongActivity
import org.worshipsongs.dialog.FavouritesDialogFragment
import org.worshipsongs.domain.Song
import org.worshipsongs.utils.PermissionUtils
import java.io.File
import java.io.FileOutputStream
import java.util.*
/**
* author: Madasamy,Seenivasan, Vignesh Palanisamy
* version: 1.0.0
*/
class PopupMenuService
{
private val customTagColorService = CustomTagColorService()
private val preferenceSettingService = UserPreferenceSettingService()
private val favouriteService = FavouriteService()
private val songService = SongService(context!!)
fun showPopupmenu(activity: AppCompatActivity, view: View, songName: String, hidePlay: Boolean)
{
val wrapper = ContextThemeWrapper(context, R.style.PopupMenu_Theme)
val popupMenu: PopupMenu
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
popupMenu = PopupMenu(wrapper, view, Gravity.RIGHT)
} else
{
popupMenu = PopupMenu(wrapper, view)
}
popupMenu.menuInflater.inflate(R.menu.favourite_share_option_menu, popupMenu.menu)
val song = songService.findContentsByTitle(songName)
val urlKey = song!!.urlKey
val menuItem = popupMenu.menu.findItem(R.id.play_song)
menuItem.isVisible = urlKey != null && urlKey.length > 0 && preferenceSettingService.isPlayVideo && hidePlay
val exportMenuItem = popupMenu.menu.findItem(R.id.export_pdf)
exportMenuItem.isVisible = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT
val presentSongMenuItem = popupMenu.menu.findItem(R.id.present_song)
presentSongMenuItem.isVisible = false
popupMenu.setOnMenuItemClickListener { item ->
when (item.itemId)
{
R.id.addToList ->
{
val bundle = Bundle()
bundle.putString(CommonConstants.TITLE_KEY, songName)
bundle.putString(CommonConstants.LOCALISED_TITLE_KEY, song.tamilTitle)
bundle.putInt(CommonConstants.ID, song.id)
val favouritesDialogFragment = FavouritesDialogFragment.newInstance(bundle)
favouritesDialogFragment.show(activity.supportFragmentManager, "FavouritesDialogFragment")
true
}
R.id.share_whatsapp ->
{
shareSongInSocialMedia(songName, song)
true
}
R.id.play_song ->
{
showYouTube(urlKey, songName)
true
}
R.id.present_song ->
{
startPresentActivity(songName)
true
}
R.id.export_pdf ->
{
if (PermissionUtils.isStoragePermissionGranted(activity))
{
exportSongToPDF(songName, Arrays.asList(song))
}
true
}
else -> false
}
}
popupMenu.show()
}
private fun shareSongInSocialMedia(songName: String, song: Song)
{
val builder = StringBuilder()
builder.append(songName).append("\n").append("\n")
for (content in song.contents!!)
{
builder.append(customTagColorService.getFormattedLines(content))
builder.append("\n")
}
builder.append(context!!.getString(R.string.share_info))
Log.i([email protected], builder.toString())
val textShareIntent = Intent(Intent.ACTION_SEND)
textShareIntent.putExtra(Intent.EXTRA_TEXT, builder.toString())
textShareIntent.type = "text/plain"
val intent = Intent.createChooser(textShareIntent, "Share $songName with...")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private fun exportSongToPDF(songName: String, songs: List<Song>)
{
val file = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "$songName.pdf")
val printAttrs = PrintAttributes.Builder().setColorMode(PrintAttributes.COLOR_MODE_COLOR).setMediaSize(PrintAttributes.MediaSize.ISO_A4).setResolution(PrintAttributes.Resolution("zooey", PRINT_SERVICE, 450, 700)).setMinMargins(PrintAttributes.Margins.NO_MARGINS).build()
val document = PrintedPdfDocument(WorshipSongApplication.context, printAttrs)
for (i in songs.indices)
{
val song = songs[i]
val pageInfo = PdfDocument.PageInfo.Builder(450, 700, i).create()
var page: PdfDocument.Page? = document.startPage(pageInfo)
if (page != null)
{
val titleDesign = Paint()
titleDesign.textAlign = Paint.Align.LEFT
titleDesign.textSize = 18f
val title = getTamilTitle(song) + song.title!!
val titleLength = titleDesign.measureText(title)
var yPos = 50f
if (page.canvas.width > titleLength)
{
val xPos = page.canvas.width / 2 - titleLength.toInt() / 2
page.canvas.drawText(title, xPos.toFloat(), 20f, titleDesign)
} else
{
var xPos = page.canvas.width / 2 - titleDesign.measureText(song.tamilTitle).toInt() / 2
page.canvas.drawText(song.tamilTitle!! + "/", xPos.toFloat(), 20f, titleDesign)
xPos = page.canvas.width / 2 - titleDesign.measureText(song.title).toInt() / 2
page.canvas.drawText(song.title!!, xPos.toFloat(), 45f, titleDesign)
yPos = 75f
}
for (content in song.contents!!)
{
if (yPos > 620)
{
document.finishPage(page)
page = document.startPage(pageInfo)
yPos = 40f
}
yPos = customTagColorService.getFormattedPage(content, page!!, 10f, yPos)
yPos = yPos + 20
}
}
document.finishPage(page)
}
try
{
val os = FileOutputStream(file)
document.writeTo(os)
document.close()
os.close()
val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.type = "application/pdf"
val uriForFile = FileProvider.getUriForFile(context!!, BuildConfig.APPLICATION_ID + ".provider", file)
shareIntent.putExtra(Intent.EXTRA_STREAM, uriForFile)
val intent = Intent.createChooser(shareIntent, "Share $songName with...")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
Log.i("done", file.absolutePath.toString())
} catch (ex: Exception)
{
Log.e(PopupMenuService::class.java.simpleName, "Error occurred while exporting to PDF", ex)
}
}
private fun getTamilTitle(song: Song): String
{
return if (StringUtils.isNotBlank(song.tamilTitle)) song.tamilTitle!! + "/" else ""
}
private fun showYouTube(urlKey: String?, songName: String)
{
Log.i(this.javaClass.simpleName, "Url key: " + urlKey!!)
val youTubeIntent = Intent(context, CustomYoutubeBoxActivity::class.java)
youTubeIntent.putExtra(CustomYoutubeBoxActivity.KEY_VIDEO_ID, urlKey)
youTubeIntent.putExtra(CommonConstants.TITLE_KEY, songName)
youTubeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(youTubeIntent)
}
private fun startPresentActivity(title: String)
{
val intent = Intent(context, PresentSongActivity::class.java)
intent.putExtra(CommonConstants.TITLE_KEY, title)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
}
fun shareFavouritesInSocialMedia(activity: Activity, view: View, favouriteName: String)
{
val wrapper = ContextThemeWrapper(context, R.style.PopupMenu_Theme)
val popupMenu: PopupMenu
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT)
{
popupMenu = PopupMenu(wrapper, view, Gravity.RIGHT)
} else
{
popupMenu = PopupMenu(wrapper, view)
}
popupMenu.menuInflater.inflate(R.menu.favourite_share_option_menu, popupMenu.menu)
popupMenu.menu.findItem(R.id.play_song).isVisible = false
popupMenu.menu.findItem(R.id.present_song).isVisible = false
popupMenu.menu.findItem(R.id.addToList).isVisible = false
popupMenu.setOnMenuItemClickListener(getPopupMenuItemListener(activity, favouriteName))
popupMenu.show()
}
private fun getPopupMenuItemListener(activity: Activity, text: String): PopupMenu.OnMenuItemClickListener
{
return PopupMenu.OnMenuItemClickListener { item ->
when (item.itemId)
{
R.id.share_whatsapp ->
{
shareFavouritesInSocialMedia(text)
true
}
R.id.export_pdf ->
{
if (PermissionUtils.isStoragePermissionGranted(activity))
{
exportSongToPDF(text, favouriteService.findSongsByFavouriteName(text))
}
false
}
else -> false
}
}
}
private fun shareFavouritesInSocialMedia(text: String)
{
val textShareIntent = Intent(Intent.ACTION_SEND)
textShareIntent.putExtra(Intent.EXTRA_TEXT, favouriteService.buildShareFavouriteFormat(text))
textShareIntent.type = "text/plain"
val intent = Intent.createChooser(textShareIntent, "Share with...")
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
context!!.startActivity(intent)
}
}
| app/src/main/java/org/worshipsongs/service/PopupMenuService.kt | 2477028249 |
package glNext.tut03
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import main.framework.Framework
import uno.buffer.destroyBuffers
import uno.buffer.floatBufferOf
import uno.buffer.intBufferBig
import uno.glsl.programOf
/**
* Created by elect on 21/02/17.
*/
fun main(args: Array<String>) {
VertCalcOffset_Next().setup("Tutorial 03 - Shader Calc Offset")
}
class VertCalcOffset_Next : Framework() {
var theProgram = 0
var elapsedTimeUniform = 0
val positionBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
val vertexPositions = floatBufferOf(
+0.25f, +0.25f, 0.0f, 1.0f,
+0.25f, -0.25f, 0.0f, 1.0f,
-0.25f, -0.25f, 0.0f, 1.0f)
var startingTime = 0L
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
startingTime = System.currentTimeMillis()
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut03", "calc-offset.vert", "standard.frag")
withProgram(theProgram) {
elapsedTimeUniform = "time".location
use { "loopDuration".location.float = 5f }
}
}
fun initializeVertexBuffer(gl: GL3) =
gl.initArrayBuffer(positionBufferObject) { data(vertexPositions, GL_STATIC_DRAW) }
override fun display(gl: GL3) = with(gl) {
clear { color(0) }
usingProgram(theProgram) {
elapsedTimeUniform.float = (System.currentTimeMillis() - startingTime) / 1_000.0f
withVertexLayout(positionBufferObject, glf.pos4) { glDrawArrays(3) }
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(positionBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(positionBufferObject, vao)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
}
| src/main/kotlin/glNext/tut03/vertCalcOffset.kt | 3036331270 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.chatchannel.matchpattern
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannel
class RPKChatChannelMatchPatternImpl(
override val regex: String,
override val groups: Map<Int, RPKChatChannel>
) : RPKChatChannelMatchPattern | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/chatchannel/matchpattern/RPKChatChannelMatchPatternImpl.kt | 4191801915 |
package actor.proto.router.fixture
import actor.proto.PID
import actor.proto.RestartStatistics
import actor.proto.Supervisor
import actor.proto.SupervisorStrategy
class DoNothingSupervisorStrategy : SupervisorStrategy {
override fun handleFailure(supervisor: Supervisor, child: PID, rs: RestartStatistics, reason: Exception) {
}
}
| proto-router/src/test/kotlin/actor/proto/router/fixture/DoNothingSupervisorStrategy.kt | 893891552 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react.common.mapbuffer
/**
* MapBuffer is an optimized sparse array format for transferring props-like data between C++ and
* JNI. It is designed to:
* - be compact to optimize space when sparse (sparse is the common case).
* - be accessible through JNI with zero/minimal copying.
* - work recursively for nested maps/arrays.
* - support dynamic types that map to JSON.
* - have minimal APK size and build time impact.
*
* See <react/renderer/mapbuffer/MapBuffer.h> for more information and native implementation.
*
* Limitations:
* - Keys are usually sized as 2 bytes, with each buffer supporting up to 65536 entries as a result.
* - O(log(N)) random key access for native buffers due to selected structure. Faster access can be
* achieved by retrieving [MapBuffer.Entry] with [entryAt] on known offsets.
*/
interface MapBuffer : Iterable<MapBuffer.Entry> {
companion object {
/**
* Key are represented as 2 byte values, and typed as Int for ease of access. The serialization
* format only allows to store [UShort] values.
*/
internal val KEY_RANGE = IntRange(UShort.MIN_VALUE.toInt(), UShort.MAX_VALUE.toInt())
}
/**
* Data types supported by [MapBuffer]. Keep in sync with definition in
* `<react/renderer/mapbuffer/MapBuffer.h>`, as enum serialization relies on correct order.
*/
enum class DataType {
BOOL,
INT,
DOUBLE,
STRING,
MAP
}
/**
* Number of elements inserted into current MapBuffer.
* @return number of elements in the [MapBuffer]
*/
val count: Int
/**
* Checks whether entry for given key exists in MapBuffer.
* @param key key to lookup the entry
* @return whether entry for the given key exists in the MapBuffer.
*/
fun contains(key: Int): Boolean
/**
* Provides offset of the key to use for [entryAt], for cases when offset is not statically known
* but can be cached.
* @param key key to lookup offset for
* @return offset for the given key to be used for entry access, -1 if key wasn't found.
*/
fun getKeyOffset(key: Int): Int
/**
* Provides parsed access to a MapBuffer without additional lookups for provided offset.
* @param offset offset of entry in the MapBuffer structure. Can be looked up for known keys with
* [getKeyOffset].
* @return parsed entry for structured access for given offset
*/
fun entryAt(offset: Int): MapBuffer.Entry
/**
* Provides parsed [DataType] annotation associated with the given key.
* @param key key to lookup type for
* @return data type of the given key.
* @throws IllegalArgumentException if the key doesn't exist
*/
fun getType(key: Int): DataType
/**
* Provides parsed [Boolean] value if the entry for given key exists with [DataType.BOOL] type
* @param key key to lookup [Boolean] value for
* @return value associated with the requested key
* @throws IllegalArgumentException if the key doesn't exist
* @throws IllegalStateException if the data type doesn't match
*/
fun getBoolean(key: Int): Boolean
/**
* Provides parsed [Int] value if the entry for given key exists with [DataType.INT] type
* @param key key to lookup [Int] value for
* @return value associated with the requested key
* @throws IllegalArgumentException if the key doesn't exist
* @throws IllegalStateException if the data type doesn't match
*/
fun getInt(key: Int): Int
/**
* Provides parsed [Double] value if the entry for given key exists with [DataType.DOUBLE] type
* @param key key to lookup [Double] value for
* @return value associated with the requested key
* @throws IllegalArgumentException if the key doesn't exist
* @throws IllegalStateException if the data type doesn't match
*/
fun getDouble(key: Int): Double
/**
* Provides parsed [String] value if the entry for given key exists with [DataType.STRING] type
* @param key key to lookup [String] value for
* @return value associated with the requested key
* @throws IllegalArgumentException if the key doesn't exist
* @throws IllegalStateException if the data type doesn't match
*/
fun getString(key: Int): String
/**
* Provides parsed [MapBuffer] value if the entry for given key exists with [DataType.MAP] type
* @param key key to lookup [MapBuffer] value for
* @return value associated with the requested key
* @throws IllegalArgumentException if the key doesn't exist
* @throws IllegalStateException if the data type doesn't match
*/
fun getMapBuffer(key: Int): MapBuffer
/**
* Provides parsed [List<MapBuffer>] value if the entry for given key exists with [DataType.MAP]
* type
* @param key key to lookup [List<MapBuffer>] value for
* @return value associated with the requested key
* @throws IllegalArgumentException if the key doesn't exist
* @throws IllegalStateException if the data type doesn't match
*/
fun getMapBufferList(key: Int): List<MapBuffer>
/** Iterable entry representing parsed MapBuffer values */
interface Entry {
/**
* Key of the given entry. Usually represented as 2 byte unsigned integer with the value range
* of [0,65536)
*/
val key: Int
/** Parsed [DataType] of the entry */
val type: DataType
/**
* Entry value represented as [Boolean]
* @throws IllegalStateException if the data type doesn't match [DataType.BOOL]
*/
val booleanValue: Boolean
/**
* Entry value represented as [Int]
* @throws IllegalStateException if the data type doesn't match [DataType.INT]
*/
val intValue: Int
/**
* Entry value represented as [Double]
* @throws IllegalStateException if the data type doesn't match [DataType.DOUBLE]
*/
val doubleValue: Double
/**
* Entry value represented as [String]
* @throws IllegalStateException if the data type doesn't match [DataType.STRING]
*/
val stringValue: String
/**
* Entry value represented as [MapBuffer]
* @throws IllegalStateException if the data type doesn't match [DataType.MAP]
*/
val mapBufferValue: MapBuffer
}
}
| ReactAndroid/src/main/java/com/facebook/react/common/mapbuffer/MapBuffer.kt | 3195559551 |
/*
* Copyright 2017 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.itachi1706.cheesecakeutilities.modules.cameraViewer
import android.content.Context
import android.util.AttributeSet
import android.view.TextureView
/**
* A [TextureView] that can be adjusted to a specified aspect ratio.
*/
class AutoFitTextureView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) : TextureView(context, attrs, defStyle) {
private var ratioWidth = 0
private var ratioHeight = 0
/**
* Sets the aspect ratio for this view. The size of the view will be measured based on the ratio
* calculated from the parameters. Note that the actual sizes of parameters don't matter, that
* is, calling setAspectRatio(2, 3) and setAspectRatio(4, 6) make the same result.
*
* @param width Relative horizontal size
* @param height Relative vertical size
*/
fun setAspectRatio(width: Int, height: Int) {
if (width < 0 || height < 0) throw IllegalArgumentException("Size cannot be negative.")
ratioWidth = width
ratioHeight = height
requestLayout()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
if (ratioWidth == 0 || ratioHeight == 0) setMeasuredDimension(width, height)
else {
if (width < height * ratioWidth / ratioHeight) setMeasuredDimension(width, width * ratioHeight / ratioWidth)
else setMeasuredDimension(height * ratioWidth / ratioHeight, height)
}
}
}
| app/src/main/java/com/itachi1706/cheesecakeutilities/modules/cameraViewer/AutoFitTextureView.kt | 4227359477 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.dessertrelease.data
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
/*
* Concrete class implementation to access data store
*/
class UserPreferencesRepository(
private val dataStore: DataStore<Preferences>
) {
private companion object {
val IS_LINEAR_LAYOUT = booleanPreferencesKey("is_linear_layout")
const val TAG = "UserPreferencesRepo"
}
val isLinearLayout: Flow<Boolean> = dataStore.data
.catch {
if (it is IOException) {
Log.e(TAG, "Error reading preferences.", it)
emit(emptyPreferences())
} else {
throw it
}
}
.map { preferences ->
preferences[IS_LINEAR_LAYOUT] ?: true
}
suspend fun saveLayoutPreference(isLinearLayout: Boolean) {
dataStore.edit { preferences ->
preferences[IS_LINEAR_LAYOUT] = isLinearLayout
}
}
}
| app/src/main/java/com/example/dessertrelease/data/UserPreferencesRepository.kt | 1821899230 |
package fr.geobert.efficio.adapter
import android.view.View
import android.widget.TextView
import fr.geobert.efficio.R
class StoreViewHolder(val view: View) {
var name: TextView = view.findViewById(R.id.store_name_lbl)
} | app/src/main/kotlin/fr/geobert/efficio/adapter/StoreViewHolder.kt | 4202878996 |
package net.codetojoy
class Utils() {
fun add(x: Int, y:Int): Int {
val result = x + y
return result
}
}
| kotlin/kotlin_sandbox/src/main/kotlin/net/codetojoy/Utils.kt | 728635431 |
package org.toml.ide.annotator
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.toml.lang.core.psi.TomlInlineTable
class TomlAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
if (element is TomlInlineTable) {
val whiteSpaces = PsiTreeUtil.findChildrenOfType(element, PsiWhiteSpace::class.java)
if (whiteSpaces.any { '\n' in it.text }) {
holder.createErrorAnnotation(element, "Inline tables are intended to appear on a single line")
}
}
}
}
| toml/src/main/kotlin/org/toml/ide/annotator/TomlAnnotator.kt | 3996883877 |
// DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2016 Konrad Jamrozik
//
// 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/>.
//
// email: [email protected]
// web: www.droidmate.org
package org.droidmate.report
import com.konradjamrozik.Resource
import com.konradjamrozik.uniqueItemsWithFirstOccurrenceIndex
import org.droidmate.android_sdk.DeviceException
import org.droidmate.apis.IApiLogcatMessage
import org.droidmate.exploration.actions.DeviceExceptionMissing
import org.droidmate.exploration.actions.RunnableExplorationActionWithResult
import org.droidmate.exploration.data_aggregators.IApkExplorationOutput2
import org.droidmate.logging.LogbackConstants
import java.time.Duration
class ApkSummary() {
companion object {
fun build(data: IApkExplorationOutput2): String {
return build(Payload(data))
}
fun build(payload: Payload): String {
return with(payload) {
// @formatter:off
StringBuilder(template)
.replaceVariable("exploration_title" , "droidmate-run:" + appPackageName)
.replaceVariable("total_run_time" , totalRunTime.minutesAndSeconds)
.replaceVariable("total_actions_count" , totalActionsCount.toString().padStart(4, ' '))
.replaceVariable("total_resets_count" , totalResetsCount.toString().padStart(4, ' '))
.replaceVariable("exception" , exception.messageIfAny())
.replaceVariable("unique_apis_count" , uniqueApisCount.toString())
.replaceVariable("api_entries" , apiEntries.joinToString(separator = "\n"))
.replaceVariable("unique_api_event_pairs_count" , uniqueEventApiPairsCount.toString())
.replaceVariable("api_event_entries" , apiEventEntries.joinToString(separator = "\n"))
.toString()
}
// @formatter:on
}
val template: String by lazy {
Resource("apk_exploration_summary_template.txt").text
}
private fun DeviceException.messageIfAny(): String {
return if (this is DeviceExceptionMissing)
""
else {
"\n* * * * * * * * * *\n" +
"WARNING! This exploration threw an exception.\n\n" +
"Exception message: '${this.message}'.\n\n" +
LogbackConstants.err_log_msg + "\n" +
"* * * * * * * * * *\n"
}
}
}
@Suppress("unused") // Kotlin BUG on private constructor(data: IApkExplorationOutput2, uniqueApiLogsWithFirstTriggeringActionIndex: Map<IApiLogcatMessage, Int>)
data class Payload(
val appPackageName: String,
val totalRunTime: Duration,
val totalActionsCount: Int,
val totalResetsCount: Int,
val exception: DeviceException,
val uniqueApisCount: Int,
val apiEntries: List<ApiEntry>,
val uniqueEventApiPairsCount: Int,
val apiEventEntries: List<ApiEventEntry>
) {
constructor(data: IApkExplorationOutput2) : this(
data,
data.uniqueApiLogsWithFirstTriggeringActionIndex,
data.uniqueEventApiPairsWithFirstTriggeringActionIndex
)
private constructor(
data: IApkExplorationOutput2,
uniqueApiLogsWithFirstTriggeringActionIndex: Map<IApiLogcatMessage, Int>,
uniqueEventApiPairsWithFirstTriggeringActionIndex: Map<EventApiPair, Int>
) : this(
appPackageName = data.packageName,
totalRunTime = data.explorationDuration,
totalActionsCount = data.actRess.size,
totalResetsCount = data.resetActionsCount,
exception = data.exception,
uniqueApisCount = uniqueApiLogsWithFirstTriggeringActionIndex.keys.size,
apiEntries = uniqueApiLogsWithFirstTriggeringActionIndex.map {
val (apiLog: IApiLogcatMessage, firstIndex: Int) = it
ApiEntry(
time = Duration.between(data.explorationStartTime, apiLog.time),
actionIndex = firstIndex,
threadId = apiLog.threadId.toInt(),
apiSignature = apiLog.uniqueString
)
},
uniqueEventApiPairsCount = uniqueEventApiPairsWithFirstTriggeringActionIndex.keys.size,
apiEventEntries = uniqueEventApiPairsWithFirstTriggeringActionIndex.map {
val (eventApiPair, firstIndex: Int) = it
val (event: String, apiLog: IApiLogcatMessage) = eventApiPair
ApiEventEntry(
ApiEntry(
time = Duration.between(data.explorationStartTime, apiLog.time),
actionIndex = firstIndex,
threadId = apiLog.threadId.toInt(),
apiSignature = apiLog.uniqueString
),
event = event
)
}
)
companion object {
val IApkExplorationOutput2.uniqueApiLogsWithFirstTriggeringActionIndex: Map<IApiLogcatMessage, Int> get() {
return this.actRess.uniqueItemsWithFirstOccurrenceIndex(
extractItems = { it.result.deviceLogs.apiLogsOrEmpty },
extractUniqueString = { it.uniqueString }
)
}
val IApkExplorationOutput2.uniqueEventApiPairsWithFirstTriggeringActionIndex: Map<EventApiPair, Int> get() {
return this.actRess.uniqueItemsWithFirstOccurrenceIndex(
extractItems = RunnableExplorationActionWithResult::extractEventApiPairs,
extractUniqueString = EventApiPair::uniqueString
)
}
}
}
data class ApiEntry(val time: Duration, val actionIndex: Int, val threadId: Int, val apiSignature: String) {
companion object {
private val actionIndexPad: Int = 7
private val threadIdPad: Int = 7
}
override fun toString(): String {
val actionIndexFormatted = "$actionIndex".padStart(actionIndexPad)
val threadIdFormatted = "$threadId".padStart(threadIdPad)
return "${time.minutesAndSeconds} $actionIndexFormatted $threadIdFormatted $apiSignature"
}
}
data class ApiEventEntry(val apiEntry: ApiEntry, val event: String) {
companion object {
private val actionIndexPad: Int = 7
private val threadIdPad: Int = 7
private val eventPadEnd: Int = 69
}
override fun toString(): String {
val actionIndexFormatted = "${apiEntry.actionIndex}".padStart(actionIndexPad)
val eventFormatted = event.padEnd(eventPadEnd)
val threadIdFormatted = "${apiEntry.threadId}".padStart(threadIdPad)
return "${apiEntry.time.minutesAndSeconds} $actionIndexFormatted $eventFormatted $threadIdFormatted ${apiEntry.apiSignature}"
}
}
} | dev/droidmate/projects/reporter/src/main/kotlin/org/droidmate/report/ApkSummary.kt | 3566576229 |
package org.owntracks.android.ui.map
import android.content.Context
import android.location.Location
import android.os.Looper
import androidx.lifecycle.LiveData
import com.google.android.gms.location.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Semaphore
import org.owntracks.android.gms.location.toGMSLocationRequest
import org.owntracks.android.location.LocationRequest
import timber.log.Timber
import java.util.concurrent.TimeUnit
class LocationLiveData(
private val locationProviderClient: FusedLocationProviderClient,
private val coroutineScope: CoroutineScope,
) :
LiveData<Location>() {
constructor(
context: Context,
coroutineScope: CoroutineScope,
) : this(LocationServices.getFusedLocationProviderClient(context), coroutineScope)
private val locationCallback = Callback()
private val lock = Semaphore(1)
suspend fun requestLocationUpdates() {
// We don't want to kick off another request while we're doing this one
lock.acquire()
locationProviderClient.removeLocationUpdates(locationCallback).continueWith { task ->
Timber.d("Removing previous locationupdate task complete. Success=${task.isSuccessful} Cancelled=${task.isCanceled}")
locationProviderClient.requestLocationUpdates(
LocationRequest(
smallestDisplacement = 1f,
priority = LocationRequest.PRIORITY_HIGH_ACCURACY,
interval = TimeUnit.SECONDS.toMillis(2),
waitForAccurateLocation = false
).toGMSLocationRequest(),
locationCallback, Looper.getMainLooper()
).addOnCompleteListener {
Timber.d("LocationLiveData location update request completed: Success=${it.isSuccessful} Cancelled=${it.isCanceled}")
lock.release()
}
}
}
private suspend fun removeLocationUpdates() {
lock.acquire()
locationProviderClient.removeLocationUpdates(locationCallback).addOnCompleteListener {
Timber.d("LocationLiveData removing location updates completed: Success=${it.isSuccessful} Cancelled=${it.isCanceled}")
lock.release()
}
}
override fun onActive() {
super.onActive()
coroutineScope.launch { requestLocationUpdates() }
}
override fun onInactive() {
coroutineScope.launch { removeLocationUpdates() }
super.onInactive()
}
inner class Callback : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
value = locationResult.lastLocation
}
override fun onLocationAvailability(locationAvailability: LocationAvailability) {
Timber.d("LocationLiveData location availability: $locationAvailability")
super.onLocationAvailability(locationAvailability)
}
}
}
| project/app/src/gms/java/org/owntracks/android/ui/map/LocationLiveData.kt | 1407907381 |
package us.jimschubert.kopper.typed
class ExampleDefaultStringArgs(args: Array<String>) : TypedArgumentParser(args) {
val first: String by StringArgument(self, "f", default = "first")
val second by StringArgument(self, "s", default = "")
val third by StringArgument(self, "t")
} | kopper-typed/src/test/kotlin/us/jimschubert/kopper/typed/ExampleDefaultStringArgs.kt | 1354586229 |
package mogul.demo
import mogul.generated.button
import mogul.generated.fourBoxes
import mogul.generated.globalKobxCounter
import mogul.generated.kobxCounter
import mogul.kobx.DemoStore
import mogul.kobx.KobX
import mogul.microdom.MicroDom
import mogul.microdom.primitives.VerticalDirection
import mogul.platform.MouseEvent
import mogul.react.ElementType
import mogul.react.StatefulComponent
import mogul.react.dom.appGui
import mogul.react.dom.layoutBox
import mogul.react.dom.runApp
import mogul.react.gui
import mogul.react.injection.container
data class MyAppState(
val windowCount: Int,
val globalCounter: Int
)
@Suppress("UNUSED_PARAMETER")
class MyApp : StatefulComponent<Nothing, MyAppState>() {
override val initialState = MyAppState(windowCount = 1, globalCounter = 0)
override fun render() = appGui {
(1..state.windowCount).map {
window(title = "mogul-$platformName #$it", width = 800, height = 600, root = gui {
layoutBox(direction = VerticalDirection, spacing = 15) {
fourBoxes(
title = "Window #$it. Click on the small boxes.",
onMoreWindows = this@MyApp::onMoreWindows,
onFewerWindows = this@MyApp::onFewerWindows
)
-"Global counter: ${state.globalCounter}"
button(text = "Increment", onClick = this@MyApp::incrementGlobalCounter)
kobxCounter()
globalKobxCounter()
}
})
}
}
fun onMoreWindows(event: MouseEvent) {
// This is called separately to test the batching of updates.
setState(state.copy(windowCount = state.windowCount + 1))
setState(state.copy(globalCounter = state.globalCounter + 1))
}
fun onFewerWindows(event: MouseEvent) {
setState(state.copy(windowCount = state.windowCount - 1))
}
fun incrementGlobalCounter(event: MouseEvent) {
setState(state.copy(globalCounter = state.globalCounter + 1))
}
}
val myAppType = ElementType("MyApp", { MyApp() })
fun main(args: Array<String>) {
val (engine, events) = platformInit()
val microDom = MicroDom(engine, events)
runApp(microDom, myAppType, container = container {
// The string tags are only required because the current preview of Kotlin Native doesn't have `T::class`
register("KobX") { KobX() }
register("DemoStore") { DemoStore(get("KobX")) }
})
// runApp(microDom, liveReloadType, LiveReloadProps(engine))
}
| native/src/mogul/demo/main.kt | 389911780 |
package com.pinterest.ktlint.ruleset.experimental
import com.pinterest.ktlint.core.Rule
import com.pinterest.ktlint.core.ast.ElementType
import com.pinterest.ktlint.core.ast.isPartOf
import com.pinterest.ktlint.core.ast.isPartOfComment
import com.pinterest.ktlint.core.ast.isWhiteSpace
import com.pinterest.ktlint.core.ast.isWhiteSpaceWithNewline
import com.pinterest.ktlint.core.ast.nextCodeSibling
import com.pinterest.ktlint.core.ast.nextLeaf
import com.pinterest.ktlint.core.ast.nextSibling
import org.jetbrains.kotlin.com.intellij.lang.ASTNode
import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl
import org.jetbrains.kotlin.psi.KtAnnotationEntry
import org.jetbrains.kotlin.psi.psiUtil.children
import org.jetbrains.kotlin.psi.psiUtil.endOffset
/**
* Ensures annotations occur immediately prior to the annotated construct
*
* https://kotlinlang.org/docs/reference/coding-conventions.html#annotation-formatting
*/
class AnnotationSpacingRule : Rule("annotation-spacing") {
companion object {
const val ERROR_MESSAGE = "Annotations should occur immediately before the annotated construct"
}
override fun visit(
node: ASTNode,
autoCorrect: Boolean,
emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit
) {
if (node.elementType != ElementType.MODIFIER_LIST && node.elementType != ElementType.FILE_ANNOTATION_LIST) {
return
}
val annotations =
node.children()
.mapNotNull { it.psi as? KtAnnotationEntry }
.toList()
if (annotations.isEmpty()) {
return
}
// Join the nodes that immediately follow the annotations (whitespace), then add the final whitespace
// if it's not a child of root. This happens when a new line separates the annotations from the annotated
// construct. In the following example, there are no whitespace children of root, but root's next sibling is the
// new line whitespace.
//
// @JvmField
// val s: Any
//
val whiteSpaces = (annotations.asSequence().map { it.nextSibling } + node.treeNext)
.filterIsInstance<PsiWhiteSpace>()
.take(annotations.size)
.toList()
val next = node.nextSiblingWithAtLeastOneOf(
{
!it.isWhiteSpace() &&
it.textLength > 0 &&
!it.isPartOf(ElementType.FILE_ANNOTATION_LIST)
},
{
// Disallow multiple white spaces as well as comments
if (it.psi is PsiWhiteSpace) {
val s = it.text
// Ensure at least one occurrence of two line breaks
s.indexOf("\n") != s.lastIndexOf("\n")
} else it.isPartOfComment()
}
)
if (next != null) {
if (node.elementType != ElementType.FILE_ANNOTATION_LIST) {
val psi = node.psi
emit(psi.endOffset - 1, ERROR_MESSAGE, true)
if (autoCorrect) {
// Special-case autocorrection when the annotation is separated from the annotated construct
// by a comment: we need to swap the order of the comment and the annotation
if (next.isPartOfComment()) {
// Remove the annotation and the following whitespace
val nextSibling = node.nextSibling { it.isWhiteSpace() }
node.treeParent.removeChild(node)
nextSibling?.treeParent?.removeChild(nextSibling)
// Insert the annotation prior to the annotated construct
val space = PsiWhiteSpaceImpl("\n")
next.treeParent.addChild(space, next.nextCodeSibling())
next.treeParent.addChild(node, space)
} else {
removeExtraLineBreaks(node)
}
}
}
}
if (whiteSpaces.isNotEmpty() && annotations.size > 1 && node.elementType != ElementType.FILE_ANNOTATION_LIST) {
// Check to make sure there are multi breaks between annotations
if (whiteSpaces.any { psi -> psi.textToCharArray().filter { it == '\n' }.count() > 1 }) {
val psi = node.psi
emit(psi.endOffset - 1, ERROR_MESSAGE, true)
if (autoCorrect) {
removeIntraLineBreaks(node, annotations.last())
}
}
}
}
private inline fun ASTNode.nextSiblingWithAtLeastOneOf(
p: (ASTNode) -> Boolean,
needsToOccur: (ASTNode) -> Boolean
): ASTNode? {
var n = this.treeNext
var occurrenceCount = 0
while (n != null) {
if (needsToOccur(n)) {
occurrenceCount++
}
if (p(n)) {
return if (occurrenceCount > 0) {
n
} else {
null
}
}
n = n.treeNext
}
return null
}
private fun removeExtraLineBreaks(node: ASTNode) {
val next = node.nextSibling {
it.isWhiteSpaceWithNewline()
} as? LeafPsiElement
if (next != null) {
rawReplaceExtraLineBreaks(next)
}
}
private fun rawReplaceExtraLineBreaks(leaf: LeafPsiElement) {
// Replace the extra white space with a single break
val text = leaf.text
val firstIndex = text.indexOf("\n") + 1
val replacementText = text.substring(0, firstIndex) +
text.substringAfter("\n").replace("\n", "")
leaf.rawReplaceWithText(replacementText)
}
private fun removeIntraLineBreaks(
node: ASTNode,
last: KtAnnotationEntry
) {
val txt = node.text
// Pull the next before raw replace or it will blow up
val lNext = node.nextLeaf()
if (node is PsiWhiteSpaceImpl) {
if (txt.toCharArray().count { it == '\n' } > 1) {
rawReplaceExtraLineBreaks(node)
}
}
if (lNext != null && !last.text.endsWith(lNext.text)) {
removeIntraLineBreaks(lNext, last)
}
}
}
| ktlint-ruleset-experimental/src/main/kotlin/com/pinterest/ktlint/ruleset/experimental/AnnotationSpacingRule.kt | 4071609723 |
package de.tutorials.springboot.repo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository
import de.tutorials.springboot.model.Customer;
// This will be AUTO IMPLEMENTED by Spring into a Bean called userRepository
// CRUD refers Create, Read, Update, Delete
@Repository
interface CustomerRepository : CrudRepository<Customer, Long> | src/main/kotlin/de/tutorials/springboot/repo/CustomerRepository.kt | 2170310470 |
package team.morale.core
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class CoreApplicationTests {
@Test
fun contextLoads() {
}
}
| src/test/kotlin/team/morale/core/CoreApplicationTests.kt | 3653699974 |
/*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and 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.vanniktech.emoji.internal
import android.content.Context
import android.util.AttributeSet
import com.vanniktech.emoji.EmojiCategory
import com.vanniktech.emoji.EmojiTheming
import com.vanniktech.emoji.listeners.OnEmojiClickListener
import com.vanniktech.emoji.variant.VariantEmoji
internal open class CategoryGridView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
) : EmojiGridView(context, attrs) {
fun init(
onEmojiClickListener: OnEmojiClickListener?,
onEmojiLongClickListener: OnEmojiLongClickListener?,
theming: EmojiTheming,
category: EmojiCategory,
variantManager: VariantEmoji,
): CategoryGridView {
adapter = EmojiArrayAdapter(
context,
category.emojis,
variantManager,
onEmojiClickListener,
onEmojiLongClickListener,
theming,
)
return this
}
}
| emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/CategoryGridView.kt | 2440934712 |
package redux.api
class VanillaStoreSpecsTest : StoreTest() {
override fun <S : Any> createStore(reducer: Reducer<S>, state: S): Store<S> {
return redux.createStore(reducer, state, Store.Enhancer { it })
}
}
| lib/src/test/kotlin/redux/api/VanillaStoreSpecsTest.kt | 1017202271 |
package cn.luo.yuan.maze.model.goods.types
import cn.luo.yuan.maze.model.Parameter
import cn.luo.yuan.maze.model.goods.GoodsProperties
import cn.luo.yuan.maze.model.goods.UsableGoods
import cn.luo.yuan.maze.service.InfoControlInterface
import cn.luo.yuan.maze.utils.Field
import cn.luo.yuan.maze.utils.StringUtils
/**
* Created by luoyuan on 2017/9/4.
*/
class RandomPortal: UsableGoods() {
companion object {
private const val serialVersionUID: Long = Field.SERVER_VERSION
}
override fun perform(properties: GoodsProperties): Boolean {
val context:InfoControlInterface? = properties[Parameter.CONTEXT] as InfoControlInterface
if(context!=null){
val maze = context.maze
val level = context.random.randomRange((maze.level * 0.4f).toLong(), (maze.maxLevel * 0.8f).toLong()) + 1
maze.level = level
context.showPopup("传送到了第 ${StringUtils.formatNumber(level)} 层")
return true
}
return false
}
override var desc: String = "使用后随机传送。传送范围为(当前层数40%)至(最高层数80%)之间"
override var name: String = "随机传送"
override var price: Long = 300000L
} | dataModel/src/cn/luo/yuan/maze/model/goods/types/RandomPortal.kt | 3397166024 |
package com.gitlab.daring.fms.zabbix.metric
import com.gitlab.daring.fms.zabbix.model.ItemValue
/**
* Supplier of metric values
*/
interface MetricSupplier {
/**
* Returns current value of specified metric
*/
fun getCurrentValue(metric: Metric): ItemValue
/**
* Returns values for specified metrics
*/
fun getValues(metris: List<Metric>): List<ItemValue> {
return metris.map(this::getCurrentValue)
}
} | zabbix/core/src/main/kotlin/com/gitlab/daring/fms/zabbix/metric/MetricSupplier.kt | 2912670506 |
/*
* Copyright (C) 2016 skydoves
*
* 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.skydoves.waterdays.persistence.preference
import android.content.Context
/**
* Created by skydoves on 2016-10-15.
* Updated by skydoves on 2017-08-17.
* Copyright (c) 2017 skydoves rights reserved.
*/
class PreferenceManager(private val mContext: Context) {
fun getBoolean(key: String, default_value: Boolean): Boolean {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
return pref.getBoolean(key, default_value)
}
fun getInt(key: String, default_value: Int): Int {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
return pref.getInt(key, default_value)
}
fun getString(key: String, default_value: String): String {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
return pref.getString(key, default_value)
}
fun putBoolean(key: String, default_value: Boolean) {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
val editor = pref.edit()
editor.putBoolean(key, default_value).apply()
}
fun putInt(key: String, default_value: Int) {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
val editor = pref.edit()
editor.putInt(key, default_value).apply()
}
fun putString(key: String, default_value: String) {
val pref = mContext.getSharedPreferences(preferenceKey, 0)
val editor = pref.edit()
editor.putString(key, default_value).apply()
}
companion object {
private val preferenceKey = "waterdays"
}
}
| app/src/main/java/com/skydoves/waterdays/persistence/preference/PreferenceManager.kt | 247980489 |
package me.giacoppo.examples.kotlin.mvp.bean
data class Show(val id: Int,val title: String = "", val description: String = "", val originCountry: String = "", val coverUrl: String = "", val posterUrl: String = "") | core/src/main/java/me/giacoppo/examples/kotlin/mvp/bean/Show.kt | 4075640146 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.trace
class TraceIteratorTest : TraceIteratorTestBase() {
override val trace = TraceStubs.TraceStub3()
override val event1 = trace.events[0]
override val event2 = trace.events[1]
override val event3 = trace.events[2]
override val timestampBetween1and2 = 101L
override val lastEvent = trace.events.last()
override val timestampAfterEnd = 210L
override val middleEvent = trace.events[25]
override val middleEventPosition = 25
}
| jabberwocky-core-test-base/src/test/kotlin/com/efficios/jabberwocky/trace/TraceIteratorTest.kt | 3261006231 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.import
class AutoImportFixTest : AutoImportFixTestBase() {
fun `test import struct`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo;
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
pub struct Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test import enum variant 1`() = checkAutoImportFixByText("""
mod foo {
pub enum Foo { A }
}
fn main() {
<error descr="Unresolved reference: `Foo`">Foo::A/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
pub enum Foo { A }
}
fn main() {
Foo::A/*caret*/;
}
""")
fun `test import enum variant 2`() = checkAutoImportFixByText("""
mod foo {
pub enum Foo { A }
}
fn main() {
let a = <error descr="Unresolved reference: `A`">A/*caret*/</error>;
}
""", """
use foo::Foo::A;
mod foo {
pub enum Foo { A }
}
fn main() {
let a = A/*caret*/;
}
""")
fun `test import function`() = checkAutoImportFixByText("""
mod foo {
pub fn bar() -> i32 { unimplemented!() }
}
fn main() {
let f = <error descr="Unresolved reference: `bar`">bar/*caret*/</error>();
}
""", """
use foo::bar;
mod foo {
pub fn bar() -> i32 { unimplemented!() }
}
fn main() {
let f = bar/*caret*/();
}
""")
fun `test import function method`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo;
impl Foo {
pub fn foo() {}
}
}
fn main() {
<error descr="Unresolved reference: `Foo`">Foo::foo/*caret*/</error>();
}
""", """
use foo::Foo;
mod foo {
pub struct Foo;
impl Foo {
pub fn foo() {}
}
}
fn main() {
Foo::foo/*caret*/();
}
""")
fun `test import generic item`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo<T>(T);
}
fn f<T>(foo: <error descr="Unresolved reference: `Foo`">Foo/*caret*/<T></error>) {}
""", """
use foo::Foo;
mod foo {
pub struct Foo<T>(T);
}
fn f<T>(foo: Foo/*caret*/<T>) {}
""")
fun `test import module`() = checkAutoImportFixByText("""
mod foo {
pub mod bar {
pub fn foo_bar() -> i32 { unimplemented!() }
}
}
fn main() {
let f = <error descr="Unresolved reference: `bar`">bar/*caret*/::foo_bar</error>();
}
""", """
use foo::bar;
mod foo {
pub mod bar {
pub fn foo_bar() -> i32 { unimplemented!() }
}
}
fn main() {
let f = bar/*caret*/::foo_bar();
}
""")
fun `test insert use item after existing use items`() = checkAutoImportFixByText("""
mod foo {
pub struct Foo;
pub struct Bar;
}
use foo::Bar;
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
mod foo {
pub struct Foo;
pub struct Bar;
}
use foo::Bar;
use foo::Foo;
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test insert use item after inner attributes`() = checkAutoImportFixByText("""
#![allow(non_snake_case)]
mod foo {
pub struct Foo;
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
#![allow(non_snake_case)]
use foo::Foo;
mod foo {
pub struct Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test import item from nested module`() = checkAutoImportFixByText("""
mod foo {
pub mod bar {
pub struct Foo;
}
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::bar::Foo;
mod foo {
pub mod bar {
pub struct Foo;
}
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test don't try to import private item`() = checkAutoImportFixIsUnavailable("""
mod foo {
struct Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test don't try to import from private mod`() = checkAutoImportFixIsUnavailable("""
mod foo {
mod bar {
pub struct Foo;
}
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test complex module structure`() = checkAutoImportFixByText("""
mod aaa {
mod bbb {
fn foo() {
let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
}
}
mod ccc {
pub mod ddd {
pub struct Foo;
}
mod eee {
struct Foo;
}
}
""", """
mod aaa {
mod bbb {
use ccc::ddd::Foo;
fn foo() {
let x = Foo/*caret*/;
}
}
}
mod ccc {
pub mod ddd {
pub struct Foo;
}
mod eee {
struct Foo;
}
}
""")
fun `test complex module structure with file modules`() = checkAutoImportFixByFileTree("""
//- aaa/mod.rs
mod bbb;
//- aaa/bbb/mod.rs
fn foo() {
let x = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
//- ccc/mod.rs
pub mod ddd;
mod eee;
//- ccc/ddd/mod.rs
pub struct Foo;
//- ccc/eee/mod.rs
struct Foo;
//- main.rs
mod aaa;
mod ccc;
""", """
use ccc::ddd::Foo;
fn foo() {
let x = Foo/*caret*/;
}
""")
fun `test import module declared via module declaration`() = checkAutoImportFixByFileTree("""
//- foo/bar.rs
fn foo_bar() {}
//- main.rs
mod foo {
pub mod bar;
}
fn main() {
<error descr="Unresolved reference: `bar`">bar::foo_bar/*caret*/</error>();
}
""", """
use foo::bar;
mod foo {
pub mod bar;
}
fn main() {
bar::foo_bar/*caret*/();
}
""")
fun `test filter import candidates 1`() = checkAutoImportFixByText("""
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
<error descr="Unresolved reference: `bar`">bar/*caret*/</error>();
}
""", """
use foo1::bar;
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
bar/*caret*/();
}
""")
fun `test filter import candidates 2`() = checkAutoImportFixByText("""
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
<error descr="Unresolved reference: `bar`">bar::foo_bar/*caret*/</error>();
}
""", """
use foo2::bar;
mod foo1 {
pub fn bar() {}
}
mod foo2 {
pub mod bar {
pub fn foo_bar() {}
}
}
fn main() {
bar::foo_bar/*caret*/();
}
""")
fun `test filter members without owner prefix`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub struct Foo;
impl Foo {
pub fn foo() {}
}
}
fn main() {
foo/*caret*/();
}
""")
fun `test don't try to import item if it can't be resolved`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub mod bar {
}
}
fn main() {
bar::foo_bar/*caret*/();
}
""")
fun `test don't import trait method`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub trait Bar {
fn bar();
}
}
fn main() {
Bar::bar/*caret*/();
}
""")
fun `test don't import trait const`() = checkAutoImportFixIsUnavailable("""
mod foo {
pub trait Bar {
const BAR: i32;
}
}
fn main() {
Bar::BAR/*caret*/();
}
""")
fun `test import reexported item`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar;
}
fn main() {
<error descr="Unresolved reference: `Bar`">Bar/*caret*/</error>;
}
""", """
use foo::Bar;
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar;
}
fn main() {
Bar/*caret*/;
}
""")
fun `test import reexported item with alias`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar as Foo;
}
fn main() {
<error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
mod bar {
pub struct Bar;
}
pub use self::bar::Bar as Foo;
}
fn main() {
Foo/*caret*/;
}
""")
fun `test import reexported item via use group`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz, Qwe};
}
fn main() {
let a = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>;
}
""", """
use foo::Baz;
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz, Qwe};
}
fn main() {
let a = Baz/*caret*/;
}
""")
fun `test import reexported item via 'self'`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Baz;
}
pub use self::bar::Baz::{self};
}
fn main() {
let a = <error descr="Unresolved reference: `Baz`">Baz/*caret*/</error>;
}
""", """
use foo::Baz;
mod foo {
mod bar {
pub struct Baz;
}
pub use self::bar::Baz::{self};
}
fn main() {
let a = Baz/*caret*/;
}
""")
fun `test import reexported item with complex reexport`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz as Foo, Qwe};
}
fn main() {
let a = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", """
use foo::Foo;
mod foo {
mod bar {
pub struct Baz;
pub struct Qwe;
}
pub use self::bar::{Baz as Foo, Qwe};
}
fn main() {
let a = Foo/*caret*/;
}
""")
fun `test module reexport`() = checkAutoImportFixByText("""
mod foo {
mod bar {
pub mod baz {
pub struct FooBar;
}
}
pub use self::bar::baz;
}
fn main() {
let x = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>;
}
""", """
use foo::baz::FooBar;
mod foo {
mod bar {
pub mod baz {
pub struct FooBar;
}
}
pub use self::bar::baz;
}
fn main() {
let x = FooBar/*caret*/;
}
""")
fun `test multiple import`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub struct Foo;
pub mod bar {
pub struct Foo;
}
}
mod baz {
pub struct Foo;
mod qwe {
pub struct Foo;
}
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", setOf("foo::Foo", "foo::bar::Foo", "baz::Foo"), "foo::bar::Foo", """
use foo::bar::Foo;
mod foo {
pub struct Foo;
pub mod bar {
pub struct Foo;
}
}
mod baz {
pub struct Foo;
mod qwe {
pub struct Foo;
}
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test multiple import with reexports`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub struct Foo;
}
mod bar {
mod baz {
pub struct Foo;
}
pub use self::baz::Foo;
}
mod qwe {
mod xyz {
pub struct Bar;
}
pub use self::xyz::Bar as Foo;
}
fn main() {
let f = <error descr="Unresolved reference: `Foo`">Foo/*caret*/</error>;
}
""", setOf("foo::Foo", "bar::Foo", "qwe::Foo"), "qwe::Foo", """
use qwe::Foo;
mod foo {
pub struct Foo;
}
mod bar {
mod baz {
pub struct Foo;
}
pub use self::baz::Foo;
}
mod qwe {
mod xyz {
pub struct Bar;
}
pub use self::xyz::Bar as Foo;
}
fn main() {
let f = Foo/*caret*/;
}
""")
fun `test double module reexport`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub mod bar {
pub struct FooBar;
}
}
mod baz {
pub mod qqq {
pub use foo::bar;
}
}
mod xxx {
pub use baz::qqq;
}
fn main() {
let a = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>;
}
""", setOf("foo::bar::FooBar", "baz::qqq::bar::FooBar", "xxx::qqq::bar::FooBar"), "baz::qqq::bar::FooBar", """
use baz::qqq::bar::FooBar;
mod foo {
pub mod bar {
pub struct FooBar;
}
}
mod baz {
pub mod qqq {
pub use foo::bar;
}
}
mod xxx {
pub use baz::qqq;
}
fn main() {
let a = FooBar/*caret*/;
}
""")
fun `test cyclic module reexports`() = checkAutoImportFixByTextWithMultipleChoice("""
pub mod x {
pub struct Z;
pub use y;
}
pub mod y {
pub use x;
}
fn main() {
let x = <error descr="Unresolved reference: `Z`">Z/*caret*/</error>;
}
""", setOf("x::Z", "y::x::Z", "x::y::x::Z"), "x::Z", """
use x::Z;
pub mod x {
pub struct Z;
pub use y;
}
pub mod y {
pub use x;
}
fn main() {
let x = Z/*caret*/;
}
""")
fun `test crazy cyclic module reexports`() = checkAutoImportFixByTextWithMultipleChoice("""
pub mod x {
pub use u;
pub mod y {
pub use u::v;
pub struct Z;
}
}
pub mod u {
pub use x::y;
pub mod v {
pub use x;
}
}
fn main() {
let z = <error descr="Unresolved reference: `Z`">Z/*caret*/</error>;
}
""", setOf(
"x::y::Z",
"x::u::y::Z",
"x::u::v::x::y::Z",
"x::u::y::v::x::y::Z",
"x::y::v::x::u::y::Z",
"x::y::v::x::y::Z",
"u::y::Z",
"u::v::x::y::Z",
"u::y::v::x::y::Z",
"u::v::x::u::y::Z"
), "u::y::Z", """
use u::y::Z;
pub mod x {
pub use u;
pub mod y {
pub use u::v;
pub struct Z;
}
}
pub mod u {
pub use x::y;
pub mod v {
pub use x;
}
}
fn main() {
let z = Z/*caret*/;
}
""")
fun `test filter imports`() = checkAutoImportFixByTextWithMultipleChoice("""
mod foo {
pub mod bar {
pub struct FooBar;
}
pub use self::bar::FooBar;
}
mod baz {
pub use foo::bar::FooBar;
}
mod quuz {
pub use foo::bar;
}
fn main() {
let x = <error descr="Unresolved reference: `FooBar`">FooBar/*caret*/</error>;
}
""", setOf("foo::FooBar", "baz::FooBar", "quuz::bar::FooBar"), "baz::FooBar", """
use baz::FooBar;
mod foo {
pub mod bar {
pub struct FooBar;
}
pub use self::bar::FooBar;
}
mod baz {
pub use foo::bar::FooBar;
}
mod quuz {
pub use foo::bar;
}
fn main() {
let x = FooBar/*caret*/;
}
""")
}
| src/test/kotlin/org/rust/ide/inspections/import/AutoImportFixTest.kt | 2731733017 |
/*
* MIT License
*
* Copyright (c) 2017 Jeff Banks
*
* 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.jjbanks.lotto.service
import com.jjbanks.lotto.model.Drawing
import com.jjbanks.lotto.model.PowerDrawing
import org.springframework.stereotype.Component
import java.time.LocalDate
import java.util.*
@Component
class LottoData {
fun getPowerDrawing(): Drawing {
// Simulation of drawing retrieval from some source.
val date: LocalDate = LocalDate.of(2017, 10, 1)
val powerPick: Int = (1..PowerDrawing.MAX_POWER_PICK).random()
val corePicks: HashSet<Int> = HashSet()
for (n in 1..5) {
while (true) {
val pick: Int = (1..PowerDrawing.MAX_CORE_PICK).random()
if (!corePicks.contains(pick)) {
corePicks.add(pick)
break
}
}
}
val powerDrawing = PowerDrawing(date, corePicks, powerPick)
powerDrawing.validate()
return powerDrawing
}
private fun ClosedRange<Int>.random() = Random().nextInt(endInclusive - start) + start
} | lotto-session-3/src/main/kotlin/com/jjbanks/lotto/service/LottoData.kt | 3461378412 |
package screenswitchersample.espressotestingbootstrap.activity
import android.content.Intent
import screenswitchersample.core.activity.ActivityComponentFactory
import screenswitchersample.core.activity.ActivityModule
import screenswitchersample.core.components.ActivityComponent
import screenswitchersample.core.components.PassthroughComponent
const val TEST_SCREEN_FACTORY = "testScreenFactory"
internal object TestActivityComponentFactory : ActivityComponentFactory {
override fun create(component: PassthroughComponent, intent: Intent?): ActivityComponent {
return DaggerTestActivityComponent.builder()
.activityModule(ActivityModule(intent))
.passthroughComponent(component)
.build()
}
}
| espresso-testing-bootstrap/src/main/java/screenswitchersample/espressotestingbootstrap/activity/TestActivityComponentFactory.kt | 3023550381 |
package com.simplemobiletools.gallery.extensions
import com.bumptech.glide.signature.ObjectKey
import java.io.File
fun String.getFileSignature(): ObjectKey {
val file = File(this)
return ObjectKey("${file.absolutePath}${file.lastModified()}")
}
fun String.isThisOrParentIncluded(includedPaths: MutableSet<String>) = includedPaths.any { startsWith(it, true) }
fun String.isThisOrParentExcluded(excludedPaths: MutableSet<String>) = excludedPaths.any { startsWith(it, true) }
| app/src/main/kotlin/com/simplemobiletools/gallery/extensions/String.kt | 1774332579 |
package info.papdt.express.helper.model
import android.content.Context
import androidx.annotation.ColorInt
import info.papdt.express.helper.R
data class MaterialPalette(
val colorName: String,
private val colorMap: Map<String, Int>
) {
companion object {
fun make(colorName: String, vararg colors: Pair<String, Int>): MaterialPalette {
return MaterialPalette(colorName, mapOf(*colors))
}
fun makeFromResources(
context: Context,
colorName: String,
vararg colorsRes: Pair<String, Int>
): MaterialPalette {
return MaterialPalette(colorName, mapOf(*colorsRes.map {
it.first to context.resources.getColor(it.second)
}.toTypedArray()))
}
}
@ColorInt
operator fun get(key: String): Int {
return colorMap.getValue(key)
}
@ColorInt
fun getPackageIconBackground(context: Context): Int {
return get(context.getString(R.string.packageIconBackgroundColorKey))
}
@ColorInt
fun getPackageIconForeground(context: Context): Int {
return get(context.getString(R.string.packageIconForegroundColorKey))
}
@ColorInt
fun getStatusIconTint(context: Context): Int {
return get(context.getString(R.string.packageStatusIconColorKey))
}
} | mobile/src/main/kotlin/info/papdt/express/helper/model/MaterialPalette.kt | 186156095 |
package karballo
import karballo.pgn.PgnFile
import karballo.pgn.PgnImportExport
import org.junit.Assert.*
import org.junit.Test
class DrawDetectionTest {
@Test
fun test3FoldDraw() {
val b = Board()
val `is` = this.javaClass.getResourceAsStream("/draw.pgn")
val pgnGame = PgnFile.getGameNumber(`is`, 0)
PgnImportExport.setBoard(b, pgnGame!!)
System.out.println(b.toString())
System.out.println("draw = " + b.isDraw)
assertTrue(b.isDraw)
}
@Test
fun test3FoldDrawNo() {
val b = Board()
val `is` = this.javaClass.getResourceAsStream("/draw.pgn")
val pgnGame = PgnFile.getGameNumber(`is`, 0)
PgnImportExport.setBoard(b, pgnGame!!)
b.undoMove()
System.out.println(b.toString())
System.out.println("draw = " + b.isDraw)
assertFalse(b.isDraw)
}
@Test
fun testDrawDetection() {
val b = Board()
b.fen = "7k/8/8/8/8/8/8/7K w - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/8/8/8/8/8/6BK b - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/8/8/8/8/8/6NK b - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/nn6/8/8/8/8/8K b - - 0 0"
assertEquals(b.isDraw, true)
b.fen = "7k/8/Nn6/8/8/8/8/8K b - - 0 0"
assertEquals(b.isDraw, false)
b.fen = "7k/7p/8/8/8/8/8/6NK b - - 0 0"
assertEquals(b.isDraw, false)
}
@Test
fun testKBbkDraw() {
val b = Board()
// Different bishop color is NOT draw
b.fen = "6bk/8/8/8/8/8/8/6BK b - - 0 0"
assertEquals(b.isDraw, false)
// Both bishops in the same color is draw
b.fen = "6bk/8/8/8/8/8/8/5B1K b - - 0 0"
assertEquals(b.isDraw, true)
}
} | karballo-jvm/src/test/kotlin/karballo/DrawDetectionTest.kt | 941408390 |
package com.supercilex.robotscouter.feature.templates
import android.animation.FloatEvaluator
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.Guideline
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.LayoutParams
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.tabs.TabLayout
import com.supercilex.robotscouter.Bridge
import com.supercilex.robotscouter.Refreshable
import com.supercilex.robotscouter.SignInResolver
import com.supercilex.robotscouter.TemplateListFragmentCompanion
import com.supercilex.robotscouter.TemplateListFragmentCompanion.Companion.TAG
import com.supercilex.robotscouter.core.data.TAB_KEY
import com.supercilex.robotscouter.core.data.defaultTemplateId
import com.supercilex.robotscouter.core.data.getTabId
import com.supercilex.robotscouter.core.data.getTabIdBundle
import com.supercilex.robotscouter.core.data.isSignedIn
import com.supercilex.robotscouter.core.data.model.addTemplate
import com.supercilex.robotscouter.core.model.TemplateType
import com.supercilex.robotscouter.core.ui.FragmentBase
import com.supercilex.robotscouter.core.ui.LifecycleAwareLazy
import com.supercilex.robotscouter.core.ui.RecyclerPoolHolder
import com.supercilex.robotscouter.core.ui.animateChange
import com.supercilex.robotscouter.core.ui.isInTabletMode
import com.supercilex.robotscouter.core.ui.longSnackbar
import com.supercilex.robotscouter.core.ui.onDestroy
import com.supercilex.robotscouter.core.unsafeLazy
import com.supercilex.robotscouter.shared.SharedLifecycleResource
import kotlinx.android.synthetic.main.fragment_template_list.*
import com.supercilex.robotscouter.R as RC
@Bridge
internal class TemplateListFragment : FragmentBase(R.layout.fragment_template_list), Refreshable,
View.OnClickListener, RecyclerPoolHolder {
override val recyclerPool by LifecycleAwareLazy { RecyclerView.RecycledViewPool() }
val pagerAdapter by unsafeLazy {
object : TemplatePagerAdapter(this@TemplateListFragment) {
override fun onDataChanged() {
super.onDataChanged()
if (currentScouts.isEmpty()) {
fab.hide()
} else {
fab.show()
}
}
}
}
private val sharedResources by activityViewModels<SharedLifecycleResource>()
val fab: FloatingActionButton by unsafeLazy {
requireActivity().findViewById(RC.id.fab)
}
private val appBar: AppBarLayout by unsafeLazy {
requireActivity().findViewById(RC.id.appBar)
}
private val tabs by LifecycleAwareLazy {
val tabs = TabLayout(ContextThemeWrapper(
requireContext(),
RC.style.ThemeOverlay_AppCompat_Dark_ActionBar
)).apply {
id = R.id.tabs
tabMode = TabLayout.MODE_SCROLLABLE
}
appBar.addView(
tabs, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT).apply {
scrollFlags = LayoutParams.SCROLL_FLAG_ENTER_ALWAYS_COLLAPSED
})
tabs
} onDestroy {
appBar.removeView(it)
}
private val homeDivider: Guideline? by unsafeLazy {
val activity = requireActivity()
if (activity.isInTabletMode()) activity.findViewById<Guideline>(RC.id.guideline) else null
}
private var savedState: Bundle? = null
init {
setHasOptionsMenu(true)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedState = savedInstanceState
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
sharedResources.onCreate(fab)
animateContainerMorph(2f / 3)
tabs // Force init
viewPager.adapter = pagerAdapter
tabs.setupWithViewPager(viewPager)
fab.setOnClickListener(this)
handleArgs(arguments, savedInstanceState)
}
override fun refresh() {
childFragmentManager.fragments
.filterIsInstance<TemplateFragment>()
.singleOrNull { pagerAdapter.currentTabId == it.dataId }
?.refresh()
}
override fun onStop() {
super.onStop()
// This has to be done in onStop so fragment transactions from the view pager can be
// committed. Only reset the adapter if the user is switching destinations.
if (isDetached) pagerAdapter.reset()
}
override fun onDestroyView() {
super.onDestroyView()
viewPager.adapter = null
animateContainerMorph(1f / 3)
sharedResources.onDestroy(fab) {
setOnClickListener(null)
hide()
}
}
fun handleArgs(args: Bundle) {
if (view == null) {
arguments = (arguments ?: Bundle()).apply { putAll(args) }
} else {
handleArgs(args, null)
}
}
private fun handleArgs(args: Bundle?, savedInstanceState: Bundle?) {
val templateId = getTabId(args)
if (templateId == null) {
getTabId(savedInstanceState)?.let { pagerAdapter.currentTabId = it }
} else {
pagerAdapter.currentTabId = TemplateType.coerce(templateId)?.let {
viewPager.longSnackbar(R.string.template_added_message)
addTemplate(it).also { defaultTemplateId = it }
} ?: templateId
args?.remove(TAB_KEY)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) =
inflater.inflate(R.menu.template_list_menu, menu)
override fun onSaveInstanceState(outState: Bundle) =
outState.putAll(getTabIdBundle(pagerAdapter.currentTabId ?: getTabId(savedState)))
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (!isSignedIn) {
(activity as SignInResolver).showSignInResolution()
return false
}
when (item.itemId) {
R.id.action_new_template -> NewTemplateDialog.show(childFragmentManager)
R.id.action_share -> TemplateSharer.shareTemplate(
this,
checkNotNull(pagerAdapter.currentTabId),
checkNotNull(pagerAdapter.currentTab?.text?.toString())
)
else -> return false
}
return true
}
override fun onClick(v: View) {
if (v.id == RC.id.fab) {
AddMetricDialog.show(childFragmentManager)
} else {
childFragmentManager.fragments
.filterIsInstance<TemplateFragment>()
.singleOrNull { pagerAdapter.currentTabId == it.dataId }
?.onClick(v)
}
}
fun onTemplateCreated(id: String) {
pagerAdapter.currentTabId = id
viewPager.longSnackbar(
R.string.template_added_title,
RC.string.template_set_default_title
) { defaultTemplateId = id }
}
private fun animateContainerMorph(new: Float) {
val div = homeDivider ?: return
val current = (div.layoutParams as ConstraintLayout.LayoutParams).guidePercent
animateChange(FloatEvaluator(), current, new) {
div.setGuidelinePercent(it.animatedValue as Float)
}
}
companion object : TemplateListFragmentCompanion {
override fun getInstance(
manager: FragmentManager,
args: Bundle?
): TemplateListFragment {
val instance = manager.findFragmentByTag(TAG) as TemplateListFragment?
?: TemplateListFragment()
args?.let { instance.handleArgs(args) }
return instance
}
}
}
| feature/templates/src/main/java/com/supercilex/robotscouter/feature/templates/TemplateListFragment.kt | 1126600491 |
package com.dragbone.pizzabot
import java.text.ParseException
class PizzaVoteParser {
companion object {
private val dayMap: Map<String, DayOfWeek> = mapOf(
"mo" to DayOfWeek.MONDAY,
"di" to DayOfWeek.TUESDAY,
"tu" to DayOfWeek.TUESDAY,
"mi" to DayOfWeek.WEDNESDAY,
"we" to DayOfWeek.WEDNESDAY,
"do" to DayOfWeek.THURSDAY,
"th" to DayOfWeek.THURSDAY,
"fr" to DayOfWeek.FRIDAY,
"sa" to DayOfWeek.SATURDAY,
"so" to DayOfWeek.SUNDAY,
"su" to DayOfWeek.SUNDAY
)
val noneList: Set<String> = setOf("none", "null", "{}", "()", "[]", "nada", "never", "nope", ":-(", ":'-(")
}
fun mapToDay(day: String): DayOfWeek = dayMap[day.toLowerCase().substring(0, 2)]!!
fun parsePizzaVote(input: String): Set<Vote> {
if (noneList.contains(input.trim()))
return emptySet()
//remove all superfluous whitespace
val cleanInput = input.replace(Regex("\\s*-\\s*"), "-").replace(Regex("\\(\\s*"), "(").replace(Regex("\\s*\\)"), ")")
// Split on whitespaces and comma and remove all empty sections
val sections = cleanInput.split(Regex("[\\s,]")).filter { it.length > 0 }
// Map sections to votes
val votes = sections.flatMap { parsePizzaVoteSection(it) }
if (votes.groupBy { it.day }.any { it.value.count() > 1 })
throw IllegalArgumentException("You can't fool me with your double votes!")
return votes.toSet()
}
private fun parsePizzaVoteSection(input: String): Iterable<Vote> {
val strength = if (input.matches(Regex("\\(.+\\)"))) 0.5f else 1f
val trimmed = input.trim('(', ')')
if (trimmed.contains('-')) {
val startEnd = trimmed.split('-')
val start = mapToDay(startEnd[0])
val end = mapToDay(startEnd[1])
if (start >= end)
throw ParseException("End before start in '$input'", 0)
return (start.ordinal..end.ordinal).map { Vote(DayOfWeek.of(it), strength) }
}
return listOf(Vote(mapToDay(trimmed), strength))
}
}
| src/main/kotlin/com/dragbone/pizzabot/PizzaVoteParser.kt | 1714473015 |
package org.elder.sourcerer.eventstore.tests
import org.elder.sourcerer.EventType
/**
* Event type used for integration tests.
*/
@EventType(repositoryName = "testrepo")
data class TestEventType(
val value: String
)
| sourcerer-eventstore-test-utils/src/main/kotlin/org/elder/sourcerer/eventstore/tests/TestEventType.kt | 423819735 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.launcher
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.testGuiFramework.impl.GuiTestStarter
import com.intellij.testGuiFramework.launcher.classpath.ClassPathBuilder
import com.intellij.testGuiFramework.launcher.classpath.PathUtils
import com.intellij.testGuiFramework.launcher.ide.CommunityIde
import com.intellij.testGuiFramework.launcher.ide.Ide
import com.intellij.testGuiFramework.launcher.system.SystemInfo
import org.jetbrains.jps.model.JpsElementFactory
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JpsJavaExtensionService
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService
import org.jetbrains.jps.model.serialization.JpsProjectLoader
import org.junit.Assert.fail
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.lang.management.ManagementFactory
import java.net.URL
import java.nio.file.Paths
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.jar.JarInputStream
import java.util.stream.Collectors
import kotlin.concurrent.thread
/**
* @author Sergey Karashevich
*/
object GuiTestLocalLauncher {
private val LOG = Logger.getInstance("#com.intellij.testGuiFramework.launcher.GuiTestLocalLauncher")
var process: Process? = null
private val TEST_GUI_FRAMEWORK_MODULE_NAME = "intellij.platform.testGuiFramework"
val project: JpsProject by lazy {
val home = PathManager.getHomePath()
val model = JpsElementFactory.getInstance().createModel()
val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global)
val jpsProject = model.project
JpsProjectLoader.loadProject(jpsProject, pathVariables, home)
jpsProject.changeOutputIfNeeded()
jpsProject
}
private val modulesList: List<JpsModule> by lazy {
project.modules
}
private val testGuiFrameworkModule: JpsModule by lazy {
modulesList.module(TEST_GUI_FRAMEWORK_MODULE_NAME) ?: throw Exception("Unable to find module '$TEST_GUI_FRAMEWORK_MODULE_NAME'")
}
private fun killProcessIfPossible() {
try {
if (process?.isAlive == true) process!!.destroyForcibly()
}
catch (e: KotlinNullPointerException) {
LOG.error("Seems that process has already destroyed, right after condition")
}
}
fun runIdeLocally(ide: Ide = Ide(CommunityIde(), 0, 0), port: Int = 0, testClassNames: List<String> = emptyList()) {
//todo: check that we are going to run test locally
val args = createArgs(ide = ide, port = port, testClassNames = testClassNames)
return startIde(ide = ide, args = args)
}
fun runIdeByPath(path: String, ide: Ide = Ide(CommunityIde(), 0, 0), port: Int = 0) {
//todo: check that we are going to run test locally
val args = createArgsByPath(path, port)
return startIde(ide = ide, args = args)
}
fun firstStartIdeLocally(ide: Ide = Ide(CommunityIde(), 0, 0), firstStartClassName: String = "undefined") {
val args = createArgsForFirstStart(ide = ide, firstStartClassName = firstStartClassName)
return startIdeAndWait(ide = ide, args = args)
}
private fun startIde(ide: Ide,
needToWait: Boolean = false,
timeOut: Long = 0,
timeOutUnit: TimeUnit = TimeUnit.SECONDS,
args: List<String>) {
LOG.info("Running $ide locally \n with args: $args")
//do not limit IDE starting if we are using debug mode to not miss the debug listening period
val conditionalTimeout = if (GuiTestOptions.isDebug()) 0 else timeOut
val startLatch = CountDownLatch(1)
thread(start = true, name = "IdeaTestThread") {
val ideaStartTest = ProcessBuilder().inheritIO().command(args)
process = ideaStartTest.start()
startLatch.countDown()
}
if (needToWait) {
startLatch.await()
if (conditionalTimeout != 0L)
process!!.waitFor(conditionalTimeout, timeOutUnit)
else
process!!.waitFor()
try {
if (process!!.exitValue() == 0) {
println("${ide.ideType} process completed successfully")
LOG.info("${ide.ideType} process completed successfully")
}
else {
System.err.println("${ide.ideType} process execution error:")
val collectedError = BufferedReader(InputStreamReader(process!!.errorStream)).lines().collect(Collectors.joining("\n"))
System.err.println(collectedError)
LOG.error("${ide.ideType} process execution error:")
LOG.error(collectedError)
fail("Starting ${ide.ideType} failed.")
}
}
catch (e: IllegalThreadStateException) {
killProcessIfPossible()
throw e
}
}
}
private fun startIdeAndWait(ide: Ide, args: List<String>)
= startIde(ide = ide, needToWait = true, timeOut = 180, args = args)
private fun createArgs(ide: Ide, mainClass: String = "com.intellij.idea.Main", port: Int = 0, testClassNames: List<String>): List<String>
= createArgsBase(ide = ide,
mainClass = mainClass,
commandName = GuiTestStarter.COMMAND_NAME,
port = port,
testClassNames = testClassNames)
private fun createArgsForFirstStart(ide: Ide, firstStartClassName: String = "undefined", port: Int = 0): List<String>
= createArgsBase(ide = ide,
mainClass = "com.intellij.testGuiFramework.impl.FirstStarterKt",
firstStartClassName = firstStartClassName,
commandName = null,
port = port,
testClassNames = emptyList())
/**
* customVmOptions should contain a full VM options formatted items like: customVmOptions = listOf("-Dapple.laf.useScreenMenuBar=true", "-Dide.mac.file.chooser.native=false").
* GuiTestLocalLauncher passed all VM options from test, that starts with "-Dpass."
*/
private fun createArgsBase(ide: Ide,
mainClass: String,
commandName: String?,
firstStartClassName: String = "undefined",
port: Int,
testClassNames: List<String>): List<String> {
val customVmOptions = getCustomPassedOptions()
var resultingArgs = listOf<String>()
.plus(getCurrentJavaExec())
.plus(getDefaultAndCustomVmOptions(ide, customVmOptions))
.plus("-Didea.gui.test.first.start.class=$firstStartClassName")
.plus("-classpath")
.plus(getOsSpecificClasspath(ide.ideType.mainModule, testClassNames))
.plus(mainClass)
if (commandName != null) resultingArgs = resultingArgs.plus(commandName)
if (port != 0) resultingArgs = resultingArgs.plus("port=$port")
LOG.info("Running with args: ${resultingArgs.joinToString(" ")}")
return resultingArgs
}
private fun createArgsByPath(path: String, port: Int = 0): List<String> {
val resultingArgs = mutableListOf(
path,
"--args",
GuiTestStarter.COMMAND_NAME
)
if (SystemInfo.isMac()) resultingArgs.add(0, "open")
if (port != 0) resultingArgs.add("port=$port")
LOG.info("Running with args: ${resultingArgs.joinToString(" ")}")
return resultingArgs
}
private fun getCurrentProcessVmOptions(): List<String> {
val runtimeMxBean = ManagementFactory.getRuntimeMXBean()
return runtimeMxBean.inputArguments
}
private fun getPassedVmOptions(): List<String> {
return getCurrentProcessVmOptions().filter { it.startsWith("-Dpass.") }
}
private fun getCustomPassedOptions(): List<String> {
return getPassedVmOptions().map { it.replace("-Dpass.", "-D") }
}
/**
* Default VM options to start IntelliJ IDEA (or IDEA-based IDE). To customize options use com.intellij.testGuiFramework.launcher.GuiTestOptions
*/
private fun getDefaultAndCustomVmOptions(ide: Ide, customVmOptions: List<String> = emptyList()): List<String> {
return listOf<String>()
.plus("-Xmx${GuiTestOptions.getXmxSize()}m")
.plus("-XX:ReservedCodeCacheSize=240m")
.plus("-XX:+UseConcMarkSweepGC")
.plus("-XX:SoftRefLRUPolicyMSPerMB=50")
.plus("-XX:MaxJavaStackTraceDepth=10000")
.plus("-ea")
.plus("-Xbootclasspath/p:${GuiTestOptions.getBootClasspath()}")
.plus("-Dsun.awt.disablegrab=true")
.plus("-Dsun.io.useCanonCaches=false")
.plus("-Djava.net.preferIPv4Stack=true")
.plus("-Dapple.laf.useScreenMenuBar=${GuiTestOptions.useAppleScreenMenuBar()}")
.plus("-Didea.is.internal=${GuiTestOptions.isInternal()}")
.plus("-Didea.debug.mode=true")
.plus("-Dnative.mac.file.chooser.enabled=false")
.plus("-Didea.config.path=${GuiTestOptions.getConfigPath()}")
.plus("-Didea.system.path=${GuiTestOptions.getSystemPath()}")
.plus("-Dfile.encoding=${GuiTestOptions.getEncoding()}")
.plus("-Didea.platform.prefix=${ide.ideType.platformPrefix}")
.plus(customVmOptions)
.plus("-Xdebug")
.plus("-Xrunjdwp:transport=dt_socket,server=y,suspend=${GuiTestOptions.suspendDebug()},address=${GuiTestOptions.getDebugPort()}")
.plus("-Duse.linux.keychain=false")
}
private fun getCurrentJavaExec(): String {
return PathUtils.getJreBinPath()
}
private fun getOsSpecificClasspath(moduleName: String, testClassNames: List<String>): String = ClassPathBuilder.buildOsSpecific(
getFullClasspath(moduleName, testClassNames).map { it.path })
/**
* return union of classpaths for current test (get from classloader) and classpaths of main and intellij.platform.testGuiFramework modules*
*/
private fun getFullClasspath(moduleName: String, testClassNames: List<String>): List<File> {
val classpath: MutableSet<File> = substituteAllMacro(getExtendedClasspath(moduleName))
classpath.addAll(getTestClasspath(testClassNames))
classpath.add(getToolsJarFile())
return classpath.toList()
}
private fun getToolsJarFile(): File {
val toolsJarUrl = getUrlPathsFromClassloader().firstOrNull {
it.endsWith("/tools.jar") or it.endsWith("\\tools.jar")
} ?: throw Exception("Unable to find tools.jar URL in the classloader URLs of ${GuiTestLocalLauncher::class.java.name} class")
return File(toolsJarUrl)
}
/**
* Finds in a current classpath that built from a test module dependencies resolved macro path
* macroName = "\$MAVEN_REPOSITORY\$"
*/
private fun resolveMacro(classpath: MutableSet<File>, macroName: String): String {
val pathWithMacro = classpath.firstOrNull { it.startsWith(macroName) }?.path ?: throw Exception(
"Unable to find file in a classpath starting with next macro: '$macroName'")
val tailOfPathWithMacro = pathWithMacro.substring(macroName.length)
val urlPaths = getUrlPathsFromClassloader()
val fullPathWithResolvedMacro = urlPaths.firstOrNull { it.endsWith(tailOfPathWithMacro) } ?: throw Exception(
"Unable to find in classpath URL with the next tail: $tailOfPathWithMacro")
return fullPathWithResolvedMacro.substring(0..(fullPathWithResolvedMacro.length - tailOfPathWithMacro.length))
}
private fun substituteAllMacro(classpath: MutableSet<File>): MutableSet<File> {
val macroList = listOf("\$MAVEN_REPOSITORY\$", "\$KOTLIN_BUNDLED\$")
val macroMap = mutableMapOf<String, String>()
macroList.forEach { macroMap.put(it, resolveMacro(classpath, it)) }
val mutableClasspath = mutableListOf<File>()
classpath.forEach { file ->
val macro = file.path.findStartsWith(macroList)
if (macro != null) {
val resolvedMacro = macroMap.get(macro)
val newPath = resolvedMacro + file.path.substring(macro.length + 1)
mutableClasspath.add(File(newPath))
} else mutableClasspath.add(file)
}
return mutableClasspath.toMutableSet()
}
private fun String.findStartsWith(list: List<String>): String? {
return list.find { this.startsWith(it) }
}
private fun getUrlPathsFromClassloader(): List<String> {
val classLoader = this.javaClass.classLoader
val urlClassLoaderClass = classLoader.javaClass
val getUrlsMethod = urlClassLoaderClass.methods.firstOrNull { it.name.toLowerCase() == "geturls" }!!
@Suppress("UNCHECKED_CAST")
val urlsListOrArray = getUrlsMethod.invoke(classLoader)
var urls = (urlsListOrArray as? List<*> ?: (urlsListOrArray as Array<*>).toList()).filterIsInstance(URL::class.java)
if (SystemInfo.isWin()) {
val classPathUrl = urls.find { it.toString().contains(Regex("classpath[\\d]*.jar")) }
if (classPathUrl != null) {
val jarStream = JarInputStream(File(classPathUrl.path).inputStream())
val mf = jarStream.manifest
urls = mf.mainAttributes.getValue("Class-Path").split(" ").map { URL(it) }
}
}
return urls.map { Paths.get(it.toURI()).toFile().path }
}
private fun getTestClasspath(testClassNames: List<String>): List<File> {
if (testClassNames.isEmpty()) return emptyList()
val fileSet = mutableSetOf<File>()
testClassNames.forEach {
fileSet.add(getClassFile(it))
}
return fileSet.toList()
}
/**
* returns a file (directory or a jar) containing class loaded by a class loader with a given name
*/
private fun getClassFile(className: String): File {
val classLoader = this.javaClass.classLoader
val cls = classLoader.loadClass(className) ?: throw Exception(
"Unable to load class ($className) with a given classloader. Check the path to class or a classloader URLs.")
val name = "${cls.simpleName}.class"
val packagePath = cls.`package`.name.replace(".", "/")
val fullPath = "$packagePath/$name"
val resourceUrl = classLoader.getResource(fullPath) ?: throw Exception(
"Unable to get resource path to a \"$fullPath\". Check the path to class or a classloader URLs.")
val correctPath = resourceUrl.correctPath()
var cutPath = correctPath.substring(0, correctPath.length - fullPath.length)
if (cutPath.endsWith("!") or cutPath.endsWith("!/")) cutPath = cutPath.substring(0..(cutPath.length - 3)) // in case of it is a jar
val file = File(cutPath)
if (!file.exists()) throw Exception("File for a class '$className' doesn't exist by path: $cutPath")
return file
}
/**
* return union of classpaths for @moduleName and intellij.platform.testGuiFramework modules
*/
private fun getExtendedClasspath(moduleName: String): MutableSet<File> {
// here we trying to analyze output path for project from classloader path and from modules classpath.
// If they didn't match than change it to output path from classpath
val resultSet = LinkedHashSet<File>()
val module = modulesList.module(moduleName) ?: throw Exception("Unable to find module with name: $moduleName")
resultSet.addAll(module.getClasspath())
return resultSet
}
private fun List<JpsModule>.module(moduleName: String): JpsModule? =
this.firstOrNull { it.name == moduleName }
//get production dependencies and test root of the current module
private fun JpsModule.getClasspath(): MutableCollection<File> {
val result = JpsJavaExtensionService.dependencies(
this).productionOnly().runtimeOnly().recursively().classes().roots.toMutableSet()
result.addAll(JpsJavaExtensionService.dependencies(this).withoutDepModules().withoutLibraries().withoutSdk().classes().roots)
return result.toMutableList()
}
private fun getOutputRootFromClassloader(): File {
val pathFromClassloader = PathManager.getJarPathForClass(GuiTestLocalLauncher::class.java)
val productionDir = File(pathFromClassloader).parentFile
assert(productionDir.isDirectory)
val outputDir = productionDir.parentFile
assert(outputDir.isDirectory)
return outputDir
}
/**
* @return true if classloader's output path is the same to module's output path (and also same to project)
*/
private fun needToChangeProjectOutput(project: JpsProject): Boolean =
JpsJavaExtensionService.getInstance().getProjectExtension(project)?.outputUrl ==
getOutputRootFromClassloader().path
private fun JpsProject.changeOutputIfNeeded() {
if (!needToChangeProjectOutput(this)) {
val projectExtension = JpsJavaExtensionService.getInstance().getOrCreateProjectExtension(this)
projectExtension.outputUrl = VfsUtilCore.pathToUrl(FileUtil.toSystemIndependentName(getOutputRootFromClassloader().path))
}
}
private fun URL.correctPath(): String {
return Paths.get(this.toURI()).toFile().path
}
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/launcher/GuiTestLocalLauncher.kt | 2662860165 |
package com.bachhuberdesign.deckbuildergwent.features.deckbuild
import android.content.ContentValues
import com.bachhuberdesign.deckbuildergwent.features.shared.exception.CardException
import com.bachhuberdesign.deckbuildergwent.features.shared.exception.DeckException
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Card
import com.bachhuberdesign.deckbuildergwent.features.shared.model.CardType
import com.bachhuberdesign.deckbuildergwent.features.shared.model.Faction
import com.bachhuberdesign.deckbuildergwent.features.stattrack.Match
import com.bachhuberdesign.deckbuildergwent.inject.annotation.PersistedScope
import com.squareup.sqlbrite.BriteDatabase
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.text.Normalizer
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
/**
* Helper class which contains functions that pertain to SQLite [Deck] queries and persistence.
*
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
@PersistedScope
class DeckRepository
@Inject constructor(val database: BriteDatabase) {
companion object {
@JvmStatic val TAG: String = DeckRepository::class.java.name
}
/**
* Checks if a given [deckName] has been persisted in the database.
*
* @return True if a deck with [deckName] is persisted. False if no deck with [deckName] is persisted.
*/
fun deckNameExists(deckName: String): Boolean {
var normalizedDeckName = Normalizer.normalize(deckName, Normalizer.Form.NFD).replace("[^\\p{ASCII}]", "")
normalizedDeckName = normalizedDeckName.replace("'", "''")
val count = database.readableDatabase.compileStatement("SELECT COUNT(*) FROM ${Deck.TABLE} WHERE ${Deck.NAME} = '$normalizedDeckName';")
return count.simpleQueryForLong() > 0
}
/**
* @return [Deck]
*/
fun getDeckById(deckId: Int): Deck? {
if (deckId <= 0) {
throw DeckException("Expected a valid deck id but received $deckId.")
}
val deckCursor = database.query("SELECT * FROM ${Deck.TABLE} WHERE ${Deck.ID} = $deckId")
var deck: Deck? = null
deckCursor.use {
while (deckCursor.moveToNext()) {
deck = Deck.MAPPER.apply(deckCursor)
}
}
if (deck == null) {
throw DeckException("Unable to load deck $deckId")
} else {
deck!!.leader = getLeaderCardForDeck(deck!!.leaderId)
deck!!.cards = getCardsForDeck(deckId)
}
return deck
}
/**
*
* @return [Deck]
*/
fun getMostRecentDeck(): Deck? {
val cursor = database.query("SELECT * FROM ${Deck.TABLE} " +
"ORDER BY last_update DESC " +
"LIMIT 1")
cursor.use { cursor ->
if (cursor.moveToNext()) {
return Deck.MAPPER.apply(cursor)
} else {
return null
}
}
}
/**
*
*/
fun observeRecentlyUpdatedDecks(): Observable<MutableList<Deck>> {
val query = "SELECT * FROM ${Deck.TABLE} " +
"ORDER BY last_update DESC " +
"LIMIT 5"
return database.createQuery(Deck.TABLE, query)
.mapToList(Deck.MAP1)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
/**
*
*/
fun observeCardUpdates(deckId: Int): Observable<MutableList<Card>> {
val tables: MutableList<String> = arrayListOf(Card.TABLE, "user_decks_cards")
val query: String = "SELECT * FROM ${Card.TABLE} " +
"JOIN user_decks_cards as t2 " +
"ON ${Card.ID} = t2.card_id " +
"WHERE t2.deck_id = $deckId"
return database.createQuery(tables, query)
.mapToList(Card.MAP1)
.skip(1)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
}
/**
*
*/
fun getCardsForDeck(deckId: Int): MutableList<Card> {
val cursor = database.query("SELECT * FROM ${Card.TABLE} " +
"JOIN user_decks_cards as t2 " +
"ON ${Card.ID} = t2.card_id " +
"WHERE t2.deck_id = $deckId")
val cards: MutableList<Card> = ArrayList()
cursor.use {
while (cursor.moveToNext()) {
cards.add(Card.MAPPER.apply(cursor))
}
}
return cards
}
/**
* @return [Card]
*/
private fun getLeaderCardForDeck(leaderCardId: Int): Card {
val cursor = database.query("SELECT * FROM ${Card.TABLE} WHERE ${Card.ID} = $leaderCardId")
cursor.use { cursor ->
while (cursor.moveToNext()) {
return Card.MAPPER.apply(cursor)
}
}
throw CardException("Leader $leaderCardId not found.")
}
/**
* @return
*/
fun getAllUserCreatedDecks(): List<Deck> {
val cursor = database.query("SELECT * FROM ${Deck.TABLE}")
val decks: MutableList<Deck> = ArrayList()
cursor.use {
while (cursor.moveToNext()) {
decks.add(Deck.MAPPER.apply(cursor))
}
}
decks.forEach { deck ->
deck.leader = getLeaderCardForDeck(deck.id)
}
return decks
}
/**
* @return [Int]
*/
fun countUserDecksWithLeader(leaderCardId: Int): Int {
val cursor = database.query("SELECT * FROM ${Deck.TABLE} " +
"WHERE ${Deck.LEADER_ID} = $leaderCardId")
cursor.use { cursor ->
return cursor.count
}
}
/**
*
*/
fun getFactions(): List<Faction> {
val factions: MutableList<Faction> = ArrayList()
val factionsCursor = database.query("SELECT * FROM ${Faction.TABLE}")
factionsCursor.use {
while (factionsCursor.moveToNext()) {
factions.add(Faction.MAPPER.apply(factionsCursor))
}
}
factions.forEach { faction ->
faction.leaders = getLeadersForFaction(faction.id) as MutableList<Card>
}
return factions
}
/**
*
*/
fun getLeadersForFaction(factionId: Int): List<Card> {
val cursor = database.query("SELECT * FROM ${Card.TABLE} " +
"WHERE ${Card.TYPE} = ${CardType.LEADER} " +
"AND ${Card.FACTION} = $factionId")
val leaders: MutableList<Card> = ArrayList()
cursor.use {
while (cursor.moveToNext()) {
leaders.add(Card.MAPPER.apply(cursor))
}
}
return leaders
}
/**
*
*/
fun saveDeck(deck: Deck): Int {
val currentTime = Date().time
val deckValues = ContentValues()
deckValues.put(Deck.NAME, deck.name)
deckValues.put(Deck.FACTION, deck.faction)
deckValues.put(Deck.LEADER_ID, deck.leader!!.cardId)
deckValues.put(Deck.FAVORITED, deck.isFavorited)
deckValues.put(Deck.LAST_UPDATE, currentTime)
if (deck.id == 0) {
deckValues.put(Deck.CREATED_DATE, currentTime)
deck.id = database.insert(Deck.TABLE, deckValues).toInt()
} else {
database.update(Deck.TABLE, deckValues, "${Deck.ID} = ${deck.id}")
}
return deck.id
}
/**
*
*/
fun updateLeaderForDeck(deckId: Int, leaderId: Int) {
val deckValues = ContentValues()
deckValues.put(Deck.LEADER_ID, leaderId)
database.update(Deck.TABLE, deckValues, "${Deck.ID} = $deckId")
}
/**
*
*/
fun addCardToDeck(card: Card, deckId: Int) {
val values = ContentValues()
values.put("card_id", card.cardId)
values.put("deck_id", deckId)
if (card.selectedLane > 0) {
values.put(Card.SELECTED_LANE, card.selectedLane)
} else {
values.put(Card.SELECTED_LANE, card.lane)
}
database.insert(Deck.JOIN_CARD_TABLE, values)
saveDeckLastUpdateTime(deckId)
}
/**
*
*/
fun renameDeck(newDeckName: String, deckId: Int) {
val values = ContentValues()
values.put(Deck.NAME, newDeckName)
database.update(Deck.TABLE, values, "${Deck.ID} = $deckId")
}
/**
*
*/
fun removeCardFromDeck(card: Card, deckId: Int) {
val query: String
if (card.selectedLane == 0) {
query = "join_id = " +
"(SELECT MIN(join_id) " +
"FROM user_decks_cards " +
"WHERE deck_id = $deckId " +
"AND card_id = ${card.cardId})"
} else {
query = "join_id = " +
"(SELECT MIN(join_id) " +
"FROM user_decks_cards " +
"WHERE deck_id = $deckId " +
"AND card_id = ${card.cardId} " +
"AND ${Card.SELECTED_LANE} = ${card.selectedLane})"
}
database.delete(Deck.JOIN_CARD_TABLE, query)
saveDeckLastUpdateTime(deckId)
}
/**
*
*/
fun deleteDeck(deckId: Int) {
database.delete(Deck.JOIN_CARD_TABLE, "deck_id = $deckId")
database.delete(Deck.TABLE, "${Deck.ID} = $deckId")
database.delete(Match.TABLE, "${Match.DECK_ID} = $deckId")
}
private fun saveDeckLastUpdateTime(deckId: Int) {
val deckValues = ContentValues()
deckValues.put(Deck.LAST_UPDATE, Date().time)
database.update(Deck.TABLE, deckValues, "${Deck.ID} = $deckId")
}
} | app/src/main/java/com/bachhuberdesign/deckbuildergwent/features/deckbuild/DeckRepository.kt | 3316081963 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.presentation.library
import android.database.Cursor
import android.support.v7.widget.RecyclerView
import com.doctoror.commons.reactivex.TestSchedulersProvider
import com.doctoror.fuckoffmusicplayer.presentation.widget.CursorRecyclerViewAdapter
import com.nhaarman.mockitokotlin2.*
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import org.junit.Assert.*
import org.junit.Test
import java.io.IOException
class LibraryListPresenterTest {
private val libraryPermissionProvider: LibraryPermissionsProvider = mock()
private val optionsMenuInvalidator: OptionsMenuInvalidator = mock()
private val searchQuerySource = PublishSubject.create<String>()
private val viewModel = LibraryListViewModel()
private val underTest = LibraryListPresenter(
libraryPermissionProvider,
optionsMenuInvalidator,
mock(),
TestSchedulersProvider(),
searchQuerySource,
viewModel)
private fun givenPermissionDenied() {
whenever(libraryPermissionProvider.permissionsGranted())
.thenReturn(false)
whenever(libraryPermissionProvider.requestPermission())
.thenReturn(Observable.just(false))
}
private fun givenPermissionGranted() {
whenever(libraryPermissionProvider.permissionsGranted())
.thenReturn(true)
whenever(libraryPermissionProvider.requestPermission())
.thenReturn(Observable.just(true))
}
private fun givenDataSourceReturns(toReturn: Observable<Cursor>): LibraryDataSource {
val dataSource: LibraryDataSource = mock {
on(it.invoke(any())).doReturn(toReturn)
}
underTest.setDataSource(dataSource)
return dataSource
}
private fun givenRecyclerAdapterMocked() {
viewModel.recyclerAdapter.set(mock<CursorRecyclerViewAdapter<RecyclerView.ViewHolder>>())
}
@Test
fun requestsPermissionOnStart() {
// Given
givenPermissionDenied()
// When
underTest.onStart()
// Then
verify(libraryPermissionProvider).requestPermission()
}
@Test
fun showsViewPermissionDeniedWhenPermissionDenied() {
// Given
givenPermissionDenied()
// When
underTest.onStart()
// Then
assertEquals(
viewModel.animatorChildPermissionDenied,
viewModel.displayedChild.get())
}
@Test
fun showsViewProgressWhenPermissionGranted() {
// Given
givenPermissionGranted()
// When
underTest.onStart()
// Then
assertEquals(
viewModel.animatorChildProgress,
viewModel.displayedChild.get())
}
@Test
fun invalidatesOptionsMenuWhenPermissionGranted() {
// Given
givenPermissionGranted()
// When
underTest.onStart()
// Then
verify(optionsMenuInvalidator).invoke()
}
@Test
fun subscribesToQuerySourceWhenPermissionGranted() {
// Given
assertFalse(searchQuerySource.hasObservers())
givenPermissionGranted()
// When
underTest.onStart()
// Then
assertTrue(searchQuerySource.hasObservers())
}
@Test
fun doesNotLoadFromDataSourceIfPermissionLost() {
// Given
givenPermissionGranted()
val dataSource: LibraryDataSource = mock()
underTest.setDataSource(dataSource)
underTest.onStart()
// When
givenPermissionDenied()
searchQuerySource.onNext("")
// Then
verifyZeroInteractions(dataSource)
}
@Test
fun loadsFromDataSourceOnQuery() {
// Given
givenPermissionGranted()
val dataSource = givenDataSourceReturns(Observable.empty())
underTest.onStart()
val query = "query"
// When
searchQuerySource.onNext(query)
// Then
verify(dataSource).invoke(query)
}
@Test
fun showsViewErrorAndResetsCursorOnQueryError() {
// Given
givenPermissionGranted()
givenDataSourceReturns(Observable.error(IOException()))
givenRecyclerAdapterMocked()
underTest.onStart()
// When
searchQuerySource.onNext("")
// Then
assertEquals(
viewModel.animatorChildError,
viewModel.displayedChild.get())
verify(viewModel.recyclerAdapter.get() as CursorRecyclerViewAdapter).changeCursor(null)
}
@Test
fun setsLoadedCursorToAdapter() {
// Given
givenPermissionGranted()
givenRecyclerAdapterMocked()
val cursor: Cursor = mock()
givenDataSourceReturns(Observable.just(cursor))
underTest.onStart()
// When
searchQuerySource.onNext("")
// Then
verify(viewModel.recyclerAdapter.get() as CursorRecyclerViewAdapter).changeCursor(cursor)
}
@Test
fun showsEmptyViewForEmptyCursor() {
// Given
givenPermissionGranted()
givenRecyclerAdapterMocked()
givenDataSourceReturns(Observable.just(mock()))
underTest.onStart()
// When
searchQuerySource.onNext("")
// Then
assertEquals(
viewModel.animatorChildEmpty,
viewModel.displayedChild.get())
}
@Test
fun showsViewContentForEmptyCursorIfCannotShowEmptyView() {
// Given
underTest.canShowEmptyView = false
givenPermissionGranted()
givenRecyclerAdapterMocked()
givenDataSourceReturns(Observable.just(mock()))
underTest.onStart()
// When
searchQuerySource.onNext("")
// Then
assertEquals(
viewModel.animatorChildContent,
viewModel.displayedChild.get())
}
@Test
fun showsViewContentForNonEmptyCursor() {
// Given
givenPermissionGranted()
givenRecyclerAdapterMocked()
val cursor: Cursor = mock()
whenever(cursor.count).thenReturn(1)
givenDataSourceReturns(Observable.just(cursor))
underTest.onStart()
// When
searchQuerySource.onNext("")
// Then
assertEquals(
viewModel.animatorChildContent,
viewModel.displayedChild.get())
}
@Test(expected = IllegalStateException::class)
fun throwsWhenAdapterNotSetOnStop() {
// When
underTest.onStop()
}
}
| presentation/src/test/java/com/doctoror/fuckoffmusicplayer/presentation/library/LibraryListPresenterTest.kt | 3985969147 |
package com.commit451.gitlab.widget
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.commit451.gitlab.R
import com.commit451.gitlab.activity.BaseActivity
import com.commit451.gitlab.adapter.ProjectsPagerAdapter
import com.commit451.gitlab.api.GitLab
import com.commit451.gitlab.api.GitLabFactory
import com.commit451.gitlab.api.GitLabService
import com.commit451.gitlab.api.OkHttpClientFactory
import com.commit451.gitlab.fragment.ProjectsFragment
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.model.api.Project
import kotlinx.android.synthetic.main.activity_project_feed_widget_configure.*
/**
* You chose your account, now choose your project!
*/
class ProjectFeedWidgetConfigureProjectActivity : BaseActivity(), ProjectsFragment.Listener {
companion object {
const val EXTRA_PROJECT = "project"
const val EXTRA_ACCOUNT = "account"
fun newIntent(context: Context, account: Account): Intent {
val intent = Intent(context, ProjectFeedWidgetConfigureProjectActivity::class.java)
intent.putExtra(EXTRA_ACCOUNT, account)
return intent
}
}
private lateinit var gitLabInstance: GitLab
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_project_feed_widget_configure)
val account = intent.getParcelableExtra<Account>(EXTRA_ACCOUNT)!!
gitLabInstance = GitLabFactory.createGitLab(account, OkHttpClientFactory.create(account, false))
viewPager.adapter = ProjectsPagerAdapter(this, supportFragmentManager)
tabLayout.setupWithViewPager(viewPager)
}
override fun onProjectClicked(project: Project) {
val data = Intent()
data.putExtra(EXTRA_PROJECT, project)
setResult(Activity.RESULT_OK, data)
finish()
}
override fun providedGitLab(): GitLab {
return gitLabInstance
}
}
| app/src/main/java/com/commit451/gitlab/widget/ProjectFeedWidgetConfigureProjectActivity.kt | 993488755 |
package com.garymcgowan.moviepedia.view.search
import android.content.Intent
import android.os.Bundle
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.navigation.Navigation
import com.garymcgowan.moviepedia.R
import com.garymcgowan.moviepedia.model.Movie
import com.garymcgowan.moviepedia.view.details.MovieDetailsFragment
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.item_movie.view.*
class MovieListAdapter(private val movieList: List<Movie>?, private val favCallback: (Movie) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_movie, parent, false)
// RxView.clicks(view)
// .map(v -> vh.getAdapterPosition())
// .subscribe(onClickSubject);
return ViewHolder(view)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val currentMovie = movieList!![position]
when (holder) {
is ViewHolder -> {
//set movie title
holder.titleTextView.text = currentMovie.titleYear()
//load image with Picasso
Picasso.with(holder.parentView.context).load(currentMovie.posterURL).placeholder(R.color.imagePlaceholder).error(R.color.imagePlaceholder).into(holder.posterImageView)
holder.parentView.setOnClickListener { v ->
Navigation.findNavController(v)
.navigate(
R.id.navigation_details,
MovieDetailsFragment.safeArgs(currentMovie.imdbID, currentMovie.title)
)
}
holder.favouriteButton.setOnClickListener {
favCallback.invoke(currentMovie)
}
}
}
}
override fun getItemCount(): Int {
return movieList?.size ?: 0
}
internal class ViewHolder(val parentView: View) : RecyclerView.ViewHolder(parentView) {
var titleTextView: TextView = parentView.titleTextView
var posterImageView: ImageView = parentView.posterImageView
var favouriteButton: View = parentView.favourite_button
}
}
| app/src/main/java/com/garymcgowan/moviepedia/view/search/MovieListAdapter.kt | 2074371439 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.swing
import com.intellij.openapi.project.Project
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.editor.HtmlPanelHost
import com.vladsch.md.nav.editor.resources.SwingHtmlGeneratorProvider
import com.vladsch.md.nav.editor.util.HtmlCompatibility
import com.vladsch.md.nav.editor.util.HtmlPanel
import com.vladsch.md.nav.editor.util.HtmlPanelProvider
import com.vladsch.md.nav.settings.MdPreviewSettings
object SwingHtmlPanelProvider : HtmlPanelProvider() {
val NAME = MdBundle.message("editor.swing.html.panel.provider.name")
val ID = "com.vladsch.md.nav.editor.swing.html.panel"
override val INFO = HtmlPanelProvider.Info(ID, NAME)
override val COMPATIBILITY = HtmlCompatibility(ID, 3f, 1f, 0f, arrayOf(SwingHtmlGeneratorProvider.ID), arrayOf<String>())
override fun isSupportedSetting(settingName: String): Boolean {
return when (settingName) {
MdPreviewSettings.MAX_IMAGE_WIDTH -> true
MdPreviewSettings.ZOOM_FACTOR -> true
// FIX: sync preview work for swing browser
MdPreviewSettings.SYNCHRONIZE_PREVIEW_POSITION -> false
else -> false
}
}
override fun createHtmlPanel(project: Project, htmlPanelHost: HtmlPanelHost): HtmlPanel {
return SwingHtmlPanel(project, htmlPanelHost)
}
override val isAvailable: HtmlPanelProvider.AvailabilityInfo
get() = HtmlPanelProvider.AvailabilityInfo.AVAILABLE
}
| src/main/java/com/vladsch/md/nav/editor/swing/SwingHtmlPanelProvider.kt | 2898241414 |
package iii_properties
import junit.framework.Assert
import org.junit.Test as test
import java.util.HashMap
class _20_Delegates_Examples {
@test fun testCommodity() {
val data = hashMapOf<String, Any?>("description" to "snowboard", "price" to 349, "isAvailable" to true)
val p = Commodity(data)
Assert.assertEquals("snowboard", p.description)
Assert.assertEquals(349, p.price)
Assert.assertEquals(true, p.isAvailable)
data["price"] = 421
Assert.assertEquals("Commodity class should reflect the data in map", 421, p.price)
p.isAvailable = false
Assert.assertEquals("The data in map should reflect the commodity class", false, data["isAvailable"])
}
} | test/iii_properties/_20_Delegates_Examples.kt | 3307624611 |
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.loan.usecase
import jp.toastkid.loan.Calculator
import jp.toastkid.loan.model.Factor
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.FlowPreview
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
class DebouncedCalculatorUseCase(
private val inputChannel: Channel<String>,
private val currentFactorProvider: () -> Factor,
private val onResult: (Long) -> Unit,
private val calculator: Calculator = Calculator(),
private val debounceMillis: Long = 1000,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main
) {
@FlowPreview
operator fun invoke() {
CoroutineScope(ioDispatcher).launch {
inputChannel
.receiveAsFlow()
.distinctUntilChanged()
.debounce(debounceMillis)
.flowOn(mainDispatcher)
.collect {
val factor = currentFactorProvider()
val payment = calculator(factor)
onResult(payment)
}
}
}
} | loan/src/main/java/jp/toastkid/loan/usecase/DebouncedCalculatorUseCase.kt | 3858356728 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.psi.element
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.tree.IElementType
import com.vladsch.md.nav.psi.util.MdTypes
class MdImageLinkStubElementType(debugName: String) : MdLinkElementStubElementType<MdImageLink, MdImageLinkStub>(debugName) {
override fun createPsi(stub: MdImageLinkStub) = MdImageLinkImpl(stub, this)
override fun getExternalId(): String = "markdown.link-element.image-link"
override fun createStub(parentStub: StubElement<PsiElement>, linkRefWithAnchorText: String): MdImageLinkStub = MdImageLinkStubImpl(parentStub, linkRefWithAnchorText)
override fun getLinkRefTextType(): IElementType = MdTypes.IMAGE_LINK_REF
override fun getLinkRefAnchorMarkerType(): IElementType? = null
override fun getLinkRefAnchorType(): IElementType? = null
}
| src/main/java/com/vladsch/md/nav/psi/element/MdImageLinkStubElementType.kt | 2168527682 |
package org.jetbrains.changelog.tasks
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction
import org.jetbrains.changelog.ChangelogPluginExtension
import java.io.File
open class InitializeChangelogTask : DefaultTask() {
private val extension = project.extensions.getByType(ChangelogPluginExtension::class.java)
@TaskAction
fun run() {
File(extension.path).apply {
if (!exists()) {
createNewFile()
}
}.writeText(
"""
# Changelog
## ${extension.unreleasedTerm}
### ${extension.groups.first()}
${extension.itemPrefix} Example item
""".trimIndent() + extension.groups.drop(1).joinToString("\n") { "### $it\n" }
)
}
}
| gradle-changelog-plugin-main/src/main/kotlin/org/jetbrains/changelog/tasks/InitializeChangelogTask.kt | 1168675125 |
package com.github.ramonrabello.kiphy.common.data
import com.github.ramonrabello.kiphy.BuildConfig
import com.github.ramonrabello.kiphy.trends.TrendingApi
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
* Singleton that handle all network setup for API calls.
*/
object ApiProvider {
private const val API_KEY_PARAM = "api_key"
private const val BASE_URL = "http://api.giphy.com"
private const val TIMEOUT_LIMIT_IN_MILLIS = 30_000L
private var retrofit: Retrofit
init {
val okHttpClient = buildOkHttpClient()
retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
private fun buildOkHttpClient(): OkHttpClient {
val okHttpClient = OkHttpClient.Builder()
okHttpClient.addInterceptor { chain ->
val original = chain.request()
val requestBuilder = original.newBuilder()
requestBuilder.addHeader(API_KEY_PARAM, BuildConfig.GIPHY_API_KEY)
val request = requestBuilder.build()
chain.proceed(request)
}
if (BuildConfig.DEBUG) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.HEADERS
okHttpClient.connectTimeout(TIMEOUT_LIMIT_IN_MILLIS, TimeUnit.MILLISECONDS)
okHttpClient.readTimeout(TIMEOUT_LIMIT_IN_MILLIS, TimeUnit.MILLISECONDS)
okHttpClient.writeTimeout(TIMEOUT_LIMIT_IN_MILLIS, TimeUnit.MILLISECONDS)
okHttpClient.addInterceptor(loggingInterceptor)
}
return okHttpClient.build()
}
fun providesTrendingApi(): TrendingApi = retrofit.create(TrendingApi::class.java)
} | app/src/main/kotlin/com/github/ramonrabello/kiphy/common/data/ApiProvider.kt | 2751241006 |
package com.safechat.conversation.symmetrickey
import com.safechat.conversation.symmetrickey.post.PostSymmetricKeyController
import com.safechat.conversation.symmetrickey.retrieve.RetrieveSymmetricKeyController
import com.safechat.conversation.symmetrickey.retrieve.RetrieveSymmetricKeyController.RetrieveResult
import com.safechat.conversation.symmetrickey.retrieve.RetrieveSymmetricKeyController.RetrieveResult.KEY_RETRIEVED
import rx.Observable
import rx.Observable.just
class ExchangeSymmetricKeyControllerImpl(
val view: ExchangeSymmetricKeyView,
val repository: ExchangeSymmetricKeyRepository,
val retrieveController: RetrieveSymmetricKeyController,
val postController: PostSymmetricKeyController) : ExchangeSymmetricKeyController {
override fun onCreate(otherPublicKey: String) {
if (repository.containsSymmetricKey(otherPublicKey)) {
view.complete()
} else {
retrieveKey(otherPublicKey)
.doOnSubscribe { view.showLoader() }
.doOnTerminate { view.hideLoader() }
.subscribe(onSuccess, onError)
}
}
private fun retrieveKey(otherPublicKey: String): Observable<Unit> {
return retrieveController.retrieveKey(otherPublicKey)
.flatMap(doIfNotPresent({ postController.postKey(otherPublicKey) }))
}
private fun doIfNotPresent(onKeyNotPresent: () -> Observable<Unit>): (RetrieveResult) -> Observable<Unit> {
return {
if (it == KEY_RETRIEVED)
just(Unit)
else {
onKeyNotPresent()
}
}
}
val onSuccess: (Unit) -> Unit = {
view.complete()
}
val onError: (Throwable) -> Unit = {
view.showError()
}
} | exchange-symmetric-key-core/src/main/java/com/safechat/conversation/symmetrickey/ExchangeSymmetricKeyControllerImpl.kt | 2735368359 |
/*
* Copyright (c) 2020. Rei Matsushita
*
* 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 me.rei_m.hyakuninisshu.state.question.action
import me.rei_m.hyakuninisshu.state.core.Action
import me.rei_m.hyakuninisshu.state.question.model.QuestionState
/**
* 問題に回答したアクション.
*/
sealed class AnswerQuestionAction(override val error: Throwable? = null) : Action {
class Success(val state: QuestionState.Answered) : AnswerQuestionAction() {
override fun toString() = "$name(state=$state)"
}
class Failure(error: Throwable) : AnswerQuestionAction(error) {
override fun toString() = "$name(error=$error)"
}
override val name = "AnswerQuestionAction"
}
| state/src/main/java/me/rei_m/hyakuninisshu/state/question/action/AnswerQuestionAction.kt | 2434524882 |
package cs.ut.json
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonProperty
import cs.ut.configuration.ConfigurationReader
import cs.ut.engine.item.ModelParameter
import cs.ut.util.Algorithm
import cs.ut.util.Node
enum class JSONKeys(val value: String) {
UI_DATA("ui_data"),
EVALUATION("evaluation"),
OWNER("job_owner"),
LOG_FILE("log_file"),
START("start_time"),
METRIC("metric"),
VALUE("value")
}
data class TrainingConfiguration(
@get:JsonIgnore val encoding: ModelParameter,
@get:JsonIgnore val bucketing: ModelParameter,
@get:JsonIgnore val learner: ModelParameter,
@get:JsonIgnore val outcome: ModelParameter
) {
lateinit var info: JobInformation
@JsonIgnore get
lateinit var evaluation: Report
@JsonIgnore get
@JsonAnyGetter
fun getProperties(): Map<String, Any> {
fun String.safeConvert(): Number = this.toIntOrNull() ?: this.toFloat()
val map = mutableMapOf<String, Any>()
val learnerMap = mutableMapOf<String, Any>()
if (bucketing.id == Algorithm.PREFIX.value) {
val propMap = mutableMapOf<String, Any>()
learner.properties.forEach { propMap[it.id] = it.property.safeConvert() }
val node = ConfigurationReader.findNode("models/parameters/prefix_length_based").
valueWithIdentifier(Node.EVENT_NUMBER.value).value<Int>()
for (i in 1..node) {
learnerMap[i.toString()] = propMap
}
} else {
learner.properties.forEach { learnerMap[it.id] = it.property.safeConvert() }
}
val encodingMap = mapOf<String, Any>(learner.parameter to learnerMap)
val bucketingMap = mapOf<String, Any>(encoding.parameter to encodingMap)
val targetMap = mapOf<String, Any>(bucketing.parameter to bucketingMap)
map[outcome.parameter] = targetMap
map[JSONKeys.UI_DATA.value] = JSONHandler().toMap(info)
return map
}
}
data class JobInformation(
@field:JsonProperty(value = "job_owner") var owner: String,
@field:JsonProperty(value = "log_file") var logFile: String,
@field:JsonProperty(value = "start_time") var startTime: String
) {
constructor() : this("", "", "")
}
class Report {
var metric: String = ""
var value: Double = 0.0
}
class TrainingData {
@JsonProperty(value = "static_cat_cols")
var staticCategorical = listOf<String>()
@JsonProperty(value = "dynamic_cat_cols")
var dynamicCategorical = listOf<String>()
@JsonProperty(value = "static_num_cols")
var staticNumeric = listOf<String>()
@JsonProperty(value = "dynamic_num_cols")
var dynamicNumeric = listOf<String>()
@JsonProperty(value = "case_id_col")
var caseId = ""
@JsonProperty(value = "activity_col")
var activity = ""
@JsonProperty(value = "timestamp_col")
var timestamp = ""
@JsonProperty(value = "future_values")
var futureValues = listOf<String>()
fun getAllColumns(): List<String> = ((staticCategorical + staticNumeric + futureValues).toList() - activity)
} | src/main/kotlin/cs/ut/json/Entities.kt | 2457814295 |
package org.ooverkommelig.graph
import org.ooverkommelig.definition.ObjectCreatingDefinition
internal class UninitializedObjectGraphState : FollowingObjectGraphState {
private lateinit var graph: ObjectGraphImpl
override fun enter(graph: ObjectGraphImpl) {
this.graph = graph
try {
runSetUpOfObjectlessLifecycles()
graph.transition(InitializedObjectGraphState())
} catch (exception: Exception) {
graph.transition(DisposingObjectGraphState())
throw exception
}
}
private fun runSetUpOfObjectlessLifecycles() {
graph.objectlessLifecycles.forEach { lifecycle ->
lifecycle.init()
graph.objectlessLifecyclesOfWhichSetUpHasRun += lifecycle
}
}
override fun creationStarted(definition: ObjectCreatingDefinition<*>, argument: Any?) = throw UnsupportedOperationException("Cannot create objects while uninitialized.")
override fun <TObject> creationEnded(definition: ObjectCreatingDefinition<TObject>, argument: Any?, createdObject: TObject?) = throw UnsupportedOperationException("Cannot create objects while uninitialized.")
override fun creationFailed() = throw UnsupportedOperationException("Cannot create objects while uninitialized.")
override fun logCleanUpError(sourceObject: Any, operation: String, exception: Exception) = throw UnsupportedOperationException("Cannot clean up sub graphs and objects while uninitialized.")
override fun dispose() {
graph.transition(DisposedObjectGraphState())
}
}
| main/src/commonMain/kotlin/org/ooverkommelig/graph/UninitializedObjectGraphState.kt | 880504767 |
package com.beyondtechnicallycorrect.visitordetector
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.os.Build
import com.beyondtechnicallycorrect.visitordetector.broadcastreceivers.AlarmReceiver
import org.joda.time.DateTime
import org.joda.time.LocalTime
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
class AlarmSchedulingHelperImpl @Inject constructor(
val alarmManager: AlarmManager,
@Named("applicationContext") val applicationContext: Context
) : AlarmSchedulingHelper {
override fun setupAlarm() {
Timber.v("Setting up alarm")
val intent = Intent(applicationContext, AlarmReceiver::class.java)
val pendingIntent =
PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val now = DateTime()
val timeToExecute = LocalTime(23, 0)
val isCloseToOrAfterTimeToExecute = now.isAfter(now.withTime(timeToExecute).minusSeconds(15))
val nextTimeToExecute =
if (isCloseToOrAfterTimeToExecute)
now.plusDays(1).withTime(timeToExecute)
else
now.withTime(timeToExecute)
Timber.d("Setting alarm for %s", nextTimeToExecute)
val nextTimeToExecuteMillis = nextTimeToExecute.millis
alarmManager.setExactAndAllowWhileIdle(
AlarmManager.RTC_WAKEUP,
nextTimeToExecuteMillis,
pendingIntent
)
}
}
| app/src/main/kotlin/com/beyondtechnicallycorrect/visitordetector/AlarmSchedulingHelperImpl.kt | 1348244975 |
package com.otaliastudios.cameraview.demo
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.MediaController
import android.widget.Toast
import android.widget.VideoView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.otaliastudios.cameraview.VideoResult
import com.otaliastudios.cameraview.size.AspectRatio
class VideoPreviewActivity : AppCompatActivity() {
companion object {
var videoResult: VideoResult? = null
}
private val videoView: VideoView by lazy { findViewById<VideoView>(R.id.video) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video_preview)
val result = videoResult ?: run {
finish()
return
}
videoView.setOnClickListener { playVideo() }
val actualResolution = findViewById<MessageView>(R.id.actualResolution)
val isSnapshot = findViewById<MessageView>(R.id.isSnapshot)
val rotation = findViewById<MessageView>(R.id.rotation)
val audio = findViewById<MessageView>(R.id.audio)
val audioBitRate = findViewById<MessageView>(R.id.audioBitRate)
val videoCodec = findViewById<MessageView>(R.id.videoCodec)
val audioCodec = findViewById<MessageView>(R.id.audioCodec)
val videoBitRate = findViewById<MessageView>(R.id.videoBitRate)
val videoFrameRate = findViewById<MessageView>(R.id.videoFrameRate)
val ratio = AspectRatio.of(result.size)
actualResolution.setTitleAndMessage("Size", "${result.size} ($ratio)")
isSnapshot.setTitleAndMessage("Snapshot", result.isSnapshot.toString())
rotation.setTitleAndMessage("Rotation", result.rotation.toString())
audio.setTitleAndMessage("Audio", result.audio.name)
audioBitRate.setTitleAndMessage("Audio bit rate", "${result.audioBitRate} bits per sec.")
videoCodec.setTitleAndMessage("VideoCodec", result.videoCodec.name)
audioCodec.setTitleAndMessage("AudioCodec", result.audioCodec.name)
videoBitRate.setTitleAndMessage("Video bit rate", "${result.videoBitRate} bits per sec.")
videoFrameRate.setTitleAndMessage("Video frame rate", "${result.videoFrameRate} fps")
val controller = MediaController(this)
controller.setAnchorView(videoView)
controller.setMediaPlayer(videoView)
videoView.setMediaController(controller)
videoView.setVideoURI(Uri.fromFile(result.file))
videoView.setOnPreparedListener { mp ->
val lp = videoView.layoutParams
val videoWidth = mp.videoWidth.toFloat()
val videoHeight = mp.videoHeight.toFloat()
val viewWidth = videoView.width.toFloat()
lp.height = (viewWidth * (videoHeight / videoWidth)).toInt()
videoView.layoutParams = lp
playVideo()
if (result.isSnapshot) {
// Log the real size for debugging reason.
Log.e("VideoPreview", "The video full size is " + videoWidth + "x" + videoHeight)
}
}
}
fun playVideo() {
if (!videoView.isPlaying) {
videoView.start()
}
}
override fun onDestroy() {
super.onDestroy()
if (!isChangingConfigurations) {
videoResult = null
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.share, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.share) {
Toast.makeText(this, "Sharing...", Toast.LENGTH_SHORT).show()
val intent = Intent(Intent.ACTION_SEND)
intent.type = "video/*"
val uri = FileProvider.getUriForFile(this,
this.packageName + ".provider",
videoResult!!.file)
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(intent)
return true
}
return super.onOptionsItemSelected(item)
}
} | demo/src/main/kotlin/com/otaliastudios/cameraview/demo/VideoPreviewActivity.kt | 3922102164 |
package com.scottmeschke.resume2017.core.activity.github
/**
* Created by Scott on 5/12/2017.
*/
data class Contribution(val date: String, val repositoryId: String, val pullRequest: PullRequest)
data class PullRequest(val url: String, val description: String)
data class Repository(val id: String, val personal: Boolean, val url: String, val description: String) | resume2017/app/src/main/java/com/scottmeschke/resume2017/core/activity/github/Entities.kt | 2258625760 |
package me.sweetll.tucao.extension
import com.shuyu.gsyvideoplayer.video.PreviewGSYVideoPlayer
import me.sweetll.tucao.AppApplication
import me.sweetll.tucao.model.xml.Durl
import java.io.File
import java.io.FileOutputStream
fun PreviewGSYVideoPlayer.setUp(durls: MutableList<Durl>, cache: Boolean, vararg objects: Any) {
/*
* 使用concat协议拼接多段视频
*/
try {
val outputFile = File.createTempFile("tucao", ".concat", AppApplication.get().cacheDir)
val outputStream = FileOutputStream(outputFile)
val concatContent = buildString {
appendln("ffconcat version 1.0")
for (durl in durls) {
appendln("file '${if (cache) durl.getCacheAbsolutePath() else durl.url}'")
appendln("duration ${durl.length / 1000f}")
}
}
// val concatContent = buildString {
// appendln("ffconcat version 1.0")
// appendln("file 'http://58.216.103.180/youku/697354F8AE94983EA216016D28/0300010900553A4D76DD1718581209B15F3A81-E563-D647-2FC4-06C5A8F05A9A.flv?sid=048412648117712c2f3d3_00&ctype=12'")
// appendln("duration 200.992")
// appendln("file 'http://222.73.245.134/youku/6772EA596B8368109D3AE55035/0300010901553A4D76DD1718581209B15F3A81-E563-D647-2FC4-06C5A8F05A9A.flv?sid=048412648117712c2f3d3_00&ctype=12'")
// appendln("duration 181.765")
// }
outputStream.write(concatContent.toByteArray())
outputStream.flush()
outputStream.close()
this.setUp(outputFile.absolutePath)
} catch (e: Exception) {
e.message?.toast()
e.printStackTrace()
}
}
| app/src/main/kotlin/me/sweetll/tucao/extension/PlayerExtensions.kt | 297535809 |
package kodando.rxjs.operators
import kodando.rxjs.JsFunction
import kodando.rxjs.Observable
import kodando.rxjs.fromModule
import kodando.rxjs.import
private val retry_: JsFunction =
fromModule("rxjs/operators") import "retry"
fun <T> Observable<T>.retry(times: Int): Observable<T> {
return pipe(retry_.call(this, times))
}
| kodando-rxjs/src/main/kotlin/kodando/rxjs/operators/Retry.kt | 4152422108 |
package com.mifos.mifosxdroid.online.checkerinbox
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel;
import android.util.Log
import com.mifos.api.datamanager.DataManagerCheckerInbox
import com.mifos.objects.CheckerTask
import com.mifos.objects.checkerinboxandtasks.CheckerInboxSearchTemplate
import com.mifos.objects.checkerinboxandtasks.RescheduleLoansTask
import rx.Subscriber
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
import javax.inject.Inject
class CheckerInboxTasksViewModel @Inject constructor(
val dataManager: DataManagerCheckerInbox,
val subscription: CompositeSubscription): ViewModel() {
private val checkerTasksLive: MutableLiveData<List<CheckerTask>> by lazy {
MutableLiveData<List<CheckerTask>>().also {
loadCheckerTasks()
}
}
var status = MutableLiveData<Boolean>()
private val rescheduleLoanTasksLive: MutableLiveData<List<RescheduleLoansTask>> by lazy {
MutableLiveData<List<RescheduleLoansTask>>().also {
loadRescheduleLoanTasks()
}
}
fun getRescheduleLoanTasks(): MutableLiveData<List<RescheduleLoansTask>> {
return rescheduleLoanTasksLive
}
fun loadRescheduleLoanTasks() {
subscription.add(dataManager.getRechdeduleLoansTaskList()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<List<RescheduleLoansTask>>() {
override fun onCompleted() {
}
override fun onError(e: Throwable) {
status.value = false
}
override fun onNext(rescheduleLoanTasks: List<RescheduleLoansTask>) {
rescheduleLoanTasksLive.postValue(rescheduleLoanTasks)
}
}))
}
fun getCheckerTasks(): LiveData<List<CheckerTask>> {
return checkerTasksLive
}
fun loadCheckerTasks() {
subscription.add(dataManager.getCheckerTaskList()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(object : Subscriber<List<CheckerTask>>() {
override fun onCompleted() {
}
override fun onError(e: Throwable) {
status.value = false
}
override fun onNext(checkerTasks: List<CheckerTask>) {
checkerTasksLive.postValue(checkerTasks)
status.value = true
}
}))
}
} | mifosng-android/src/main/java/com/mifos/mifosxdroid/online/checkerinbox/CheckerInboxTasksViewModel.kt | 1507969748 |
package me.panpf.sketch.sample.ui
import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.text.format.Formatter
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import kotlinx.android.synthetic.main.fragment_image.*
import me.panpf.androidxkt.app.bindBooleanArgOr
import me.panpf.androidxkt.app.bindParcelableArg
import me.panpf.androidxkt.app.bindStringArgOrNull
import me.panpf.sketch.Sketch
import me.panpf.sketch.datasource.DataSource
import me.panpf.sketch.decode.ImageAttrs
import me.panpf.sketch.display.FadeInImageDisplayer
import me.panpf.sketch.drawable.SketchDrawable
import me.panpf.sketch.drawable.SketchGifDrawable
import me.panpf.sketch.drawable.SketchRefBitmap
import me.panpf.sketch.request.*
import me.panpf.sketch.sample.AppConfig
import me.panpf.sketch.sample.R
import me.panpf.sketch.sample.base.BaseFragment
import me.panpf.sketch.sample.base.BindContentView
import me.panpf.sketch.sample.bean.Image
import me.panpf.sketch.sample.event.AppConfigChangedEvent
import me.panpf.sketch.sample.event.RegisterEvent
import me.panpf.sketch.sample.util.ApplyWallpaperAsyncTask
import me.panpf.sketch.sample.util.FixedThreeLevelScales
import me.panpf.sketch.sample.util.SaveImageAsyncTask
import me.panpf.sketch.sample.widget.MappingView
import me.panpf.sketch.sample.widget.SampleImageView
import me.panpf.sketch.state.MemoryCacheStateImage
import me.panpf.sketch.uri.FileUriModel
import me.panpf.sketch.uri.GetDataSourceException
import me.panpf.sketch.uri.UriModel
import me.panpf.sketch.util.SketchUtils
import me.panpf.sketch.zoom.AdaptiveTwoLevelScales
import me.panpf.sketch.zoom.ImageZoomer
import me.panpf.sketch.zoom.Size
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import java.io.File
import java.io.IOException
import java.util.*
@RegisterEvent
@BindContentView(R.layout.fragment_image)
class ImageFragment : BaseFragment() {
private val image by bindParcelableArg<Image>(PARAM_REQUIRED_STRING_IMAGE_URI)
private val loadingImageOptionsKey: String? by bindStringArgOrNull(PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY)
private val showTools: Boolean by bindBooleanArgOr(PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS)
private lateinit var finalShowImageUrl: String
private val showHelper = ShowHelper()
private val zoomHelper = ZoomHelper()
private var mappingHelper = MappingHelper()
private val clickHelper = ClickHelper()
private val setWindowBackgroundHelper = SetWindowBackgroundHelper()
private val gifPlayFollowPageVisibleHelper = GifPlayFollowPageVisibleHelper()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activity = activity ?: return
setWindowBackgroundHelper.onCreate(activity)
val showHighDefinitionImage = AppConfig.getBoolean(activity, AppConfig.Key.SHOW_UNSPLASH_RAW_IMAGE)
finalShowImageUrl = if (showHighDefinitionImage) image.rawQualityUrl else image.normalQualityUrl
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
zoomHelper.onViewCreated()
mappingHelper.onViewCreated()
clickHelper.onViewCreated()
showHelper.onViewCreated()
EventBus.getDefault().register(this)
}
override fun onUserVisibleChanged(isVisibleToUser: Boolean) {
zoomHelper.onUserVisibleChanged()
setWindowBackgroundHelper.onUserVisibleChanged()
gifPlayFollowPageVisibleHelper.onUserVisibleChanged()
}
@Suppress("unused")
@Subscribe
fun onEvent(event: AppConfigChangedEvent) {
if (AppConfig.Key.SUPPORT_ZOOM == event.key) {
zoomHelper.onConfigChanged()
mappingHelper.onViewCreated()
} else if (AppConfig.Key.READ_MODE == event.key) {
zoomHelper.onReadModeConfigChanged()
}
}
override fun onDestroyView() {
EventBus.getDefault().unregister(this)
super.onDestroyView()
}
class PlayImageEvent
private inner class ShowHelper {
fun onViewCreated() {
image_imageFragment_image.displayListener = ImageDisplayListener()
image_imageFragment_image.downloadProgressListener = ImageDownloadProgressListener()
initOptions()
image_imageFragment_image.displayImage(finalShowImageUrl)
}
private fun initOptions() {
val activity = activity ?: return
image_imageFragment_image.page = SampleImageView.Page.DETAIL
val options = image_imageFragment_image.options
// 允许播放 GIF
options.isDecodeGifImage = true
// 有占位图选项信息的话就使用内存缓存占位图但不使用任何显示器,否则就是用渐入显示器
if (!TextUtils.isEmpty(loadingImageOptionsKey)) {
val uriModel = UriModel.match(activity, finalShowImageUrl)
var cachedRefBitmap: SketchRefBitmap? = null
var memoryCacheKey: String? = null
if (uriModel != null) {
memoryCacheKey = SketchUtils.makeRequestKey(image.normalQualityUrl, uriModel, loadingImageOptionsKey!!)
cachedRefBitmap = Sketch.with(activity).configuration.memoryCache.get(memoryCacheKey)
}
if (cachedRefBitmap != null && memoryCacheKey != null) {
options.loadingImage = MemoryCacheStateImage(memoryCacheKey, null)
} else {
options.displayer = FadeInImageDisplayer()
}
} else {
options.displayer = FadeInImageDisplayer()
}
}
inner class ImageDisplayListener : DisplayListener {
override fun onStarted() {
if (view == null) {
return
}
hint_imageFragment_hint.loading(null)
}
override fun onCompleted(drawable: Drawable, imageFrom: ImageFrom, imageAttrs: ImageAttrs) {
if (view == null) {
return
}
hint_imageFragment_hint.hidden()
setWindowBackgroundHelper.onDisplayCompleted()
gifPlayFollowPageVisibleHelper.onDisplayCompleted()
}
override fun onError(cause: ErrorCause) {
if (view == null) {
return
}
hint_imageFragment_hint.hint(R.drawable.ic_error, "Image display failed", "Again", View.OnClickListener { image_imageFragment_image.displayImage(finalShowImageUrl) })
}
override fun onCanceled(cause: CancelCause) {
if (view == null) {
return
}
@Suppress("NON_EXHAUSTIVE_WHEN")
when (cause) {
CancelCause.PAUSE_DOWNLOAD -> hint_imageFragment_hint.hint(R.drawable.ic_error, "Pause to download new image for saving traffic", "I do not care", View.OnClickListener {
val requestLevel = image_imageFragment_image.options.requestLevel
image_imageFragment_image.options.requestLevel = RequestLevel.NET
image_imageFragment_image.displayImage(finalShowImageUrl)
image_imageFragment_image.options.requestLevel = requestLevel
})
CancelCause.PAUSE_LOAD -> hint_imageFragment_hint.hint(R.drawable.ic_error, "Paused to load new image", "Forced to load", View.OnClickListener {
val requestLevel = image_imageFragment_image.options.requestLevel
image_imageFragment_image.options.requestLevel = RequestLevel.NET
image_imageFragment_image.displayImage(finalShowImageUrl)
image_imageFragment_image.options.requestLevel = requestLevel
})
}
}
}
inner class ImageDownloadProgressListener : DownloadProgressListener {
override fun onUpdateDownloadProgress(totalLength: Int, completedLength: Int) {
if (view == null) {
return
}
hint_imageFragment_hint.setProgress(totalLength, completedLength)
}
}
}
private inner class ZoomHelper {
fun onViewCreated() {
image_imageFragment_image.isZoomEnabled = AppConfig.getBoolean(image_imageFragment_image.context, AppConfig.Key.SUPPORT_ZOOM)
if (AppConfig.getBoolean(image_imageFragment_image.context, AppConfig.Key.FIXED_THREE_LEVEL_ZOOM_MODE)) {
image_imageFragment_image.zoomer?.setZoomScales(FixedThreeLevelScales())
} else {
image_imageFragment_image.zoomer?.setZoomScales(AdaptiveTwoLevelScales())
}
onReadModeConfigChanged() // 初始化阅读模式
onUserVisibleChanged() // 初始化超大图查看器的暂停状态,这一步很重要
}
fun onConfigChanged() {
onViewCreated()
}
fun onUserVisibleChanged() {
val activity = activity ?: return
image_imageFragment_image.zoomer?.let {
if (AppConfig.getBoolean(activity, AppConfig.Key.PAUSE_BLOCK_DISPLAY_WHEN_PAGE_NOT_VISIBLE)) {
it.blockDisplayer.setPause(!isVisibleToUser) // 不可见的时候暂停超大图查看器,节省内存
} else if (isVisibleToUser && it.blockDisplayer.isPaused) {
it.blockDisplayer.setPause(false) // 因为有 PAUSE_BLOCK_DISPLAY_WHEN_PAGE_NOT_VISIBLE 开关的存在,可能会出现关闭开关后依然处于暂停状态的情况,因此这里恢复一下,加个保险
}
}
}
fun onReadModeConfigChanged() {
val activity = activity ?: return
image_imageFragment_image.zoomer?.let {
it.isReadMode = AppConfig.getBoolean(activity, AppConfig.Key.READ_MODE)
}
}
}
private inner class MappingHelper {
val zoomMatrixChangedListener = ZoomMatrixChangedListener()
fun onViewCreated() {
if (!showTools) {
mapping_imageFragment.visibility = View.GONE
return
}
if (image_imageFragment_image.zoomer != null) {
// MappingView 跟随 Matrix 变化刷新显示区域
image_imageFragment_image.zoomer?.addOnMatrixChangeListener(zoomMatrixChangedListener)
// MappingView 跟随碎片变化刷新碎片区域
image_imageFragment_image.zoomer?.blockDisplayer?.setOnBlockChangedListener { mapping_imageFragment.blockChanged(it) }
// 点击 MappingView 定位到指定位置
mapping_imageFragment.setOnSingleClickListener(object : MappingView.OnSingleClickListener {
override fun onSingleClick(x: Float, y: Float): Boolean {
val drawable = image_imageFragment_image.drawable ?: return false
if (drawable.intrinsicWidth == 0 || drawable.intrinsicHeight == 0) {
return false
}
if (mapping_imageFragment.width == 0 || mapping_imageFragment.height == 0) {
return false
}
val widthScale = drawable.intrinsicWidth.toFloat() / mapping_imageFragment.width
val heightScale = drawable.intrinsicHeight.toFloat() / mapping_imageFragment.height
val realX = x * widthScale
val realY = y * heightScale
val showLocationAnimation = AppConfig.getBoolean(image_imageFragment_image.context, AppConfig.Key.LOCATION_ANIMATE)
location(realX, realY, showLocationAnimation)
return true
}
})
} else {
mapping_imageFragment.setOnSingleClickListener(null)
mapping_imageFragment.update(Size(0, 0), Rect())
}
mapping_imageFragment.options.displayer = FadeInImageDisplayer()
mapping_imageFragment.options.setMaxSize(600, 600)
mapping_imageFragment.displayImage(finalShowImageUrl)
}
fun location(x: Float, y: Float, animate: Boolean): Boolean {
image_imageFragment_image.zoomer?.location(x, y, animate)
return true
}
private inner class ZoomMatrixChangedListener : ImageZoomer.OnMatrixChangeListener {
internal var visibleRect = Rect()
override fun onMatrixChanged(imageZoomer: ImageZoomer) {
imageZoomer.getVisibleRect(visibleRect)
mapping_imageFragment.update(imageZoomer.drawableSize, visibleRect)
}
}
}
private inner class SetWindowBackgroundHelper {
private var pageBackgApplyCallback: PageBackgApplyCallback? = null
fun onCreate(activity: Activity) {
if (activity is PageBackgApplyCallback) {
setWindowBackgroundHelper.pageBackgApplyCallback = activity
}
}
fun onUserVisibleChanged() {
if (pageBackgApplyCallback != null && isVisibleToUser) {
pageBackgApplyCallback!!.onApplyBackground(finalShowImageUrl)
}
}
fun onDisplayCompleted() {
onUserVisibleChanged()
}
}
private inner class GifPlayFollowPageVisibleHelper {
fun onUserVisibleChanged() {
val drawable = image_imageFragment_image.drawable
val lastDrawable = SketchUtils.getLastDrawable(drawable)
if (lastDrawable != null && lastDrawable is SketchGifDrawable) {
(lastDrawable as SketchGifDrawable).followPageVisible(isVisibleToUser, false)
}
}
fun onDisplayCompleted() {
val drawable = image_imageFragment_image.drawable
val lastDrawable = SketchUtils.getLastDrawable(drawable)
if (lastDrawable != null && lastDrawable is SketchGifDrawable) {
(lastDrawable as SketchGifDrawable).followPageVisible(isVisibleToUser, true)
}
}
}
private inner class ClickHelper {
fun onViewCreated() {
// 将单击事件传递给上层 Activity
val zoomer = image_imageFragment_image.zoomer
zoomer?.setOnViewTapListener { view, x, y ->
val parentFragment = parentFragment
if (parentFragment != null && parentFragment is ImageZoomer.OnViewTapListener) {
(parentFragment as ImageZoomer.OnViewTapListener).onViewTap(view, x, y)
} else {
val drawablePoint = zoomer.touchPointToDrawablePoint(x.toInt(), y.toInt())
val block = if(drawablePoint != null) zoomer.getBlockByDrawablePoint(drawablePoint.x, drawablePoint.y) else null
if (block?.bitmap != null) {
val imageView = ImageView(activity).apply {
setImageBitmap(block.bitmap)
}
AlertDialog.Builder(activity).setView(imageView).setPositiveButton("取消", null).show()
}
}
}
image_imageFragment_image.setOnLongClickListener {
val menuItemList = LinkedList<MenuItem>()
menuItemList.add(MenuItem(
"Image Info",
DialogInterface.OnClickListener { _, _ -> activity?.let { it1 -> image_imageFragment_image.showInfo(it1) } }
))
menuItemList.add(MenuItem(
"Zoom/Rotate/Block Display",
DialogInterface.OnClickListener { _, _ -> showZoomMenu() }
))
menuItemList.add(MenuItem(
String.format("Toggle ScaleType (%s)", image_imageFragment_image.zoomer?.scaleType
?: image_imageFragment_image.scaleType),
DialogInterface.OnClickListener { _, _ -> showScaleTypeMenu() }
))
menuItemList.add(MenuItem(
"Auto Play",
DialogInterface.OnClickListener { _, _ -> play() }
))
menuItemList.add(MenuItem(
"Set as wallpaper",
DialogInterface.OnClickListener { _, _ -> setWallpaper() }
))
menuItemList.add(MenuItem(
"Share Image",
DialogInterface.OnClickListener { _, _ -> share() }
))
menuItemList.add(MenuItem(
"Save Image",
DialogInterface.OnClickListener { _, _ -> save() }
))
val items = arrayOfNulls<String>(menuItemList.size)
var w = 0
val size = menuItemList.size
while (w < size) {
items[w] = menuItemList[w].title
w++
}
val itemClickListener = DialogInterface.OnClickListener { dialog, which ->
dialog.dismiss()
menuItemList[which].clickListener?.onClick(dialog, which)
}
AlertDialog.Builder(activity)
.setItems(items, itemClickListener)
.show()
true
}
}
fun showZoomMenu() {
val menuItemList = LinkedList<MenuItem>()
// 缩放信息
val zoomer = image_imageFragment_image.zoomer
if (zoomer != null) {
val zoomInfoBuilder = StringBuilder()
val zoomScale = SketchUtils.formatFloat(zoomer.zoomScale, 2)
val visibleRect = Rect()
zoomer.getVisibleRect(visibleRect)
val visibleRectString = visibleRect.toShortString()
zoomInfoBuilder.append("Zoom: ").append(zoomScale).append(" / ").append(visibleRectString)
menuItemList.add(MenuItem(zoomInfoBuilder.toString(), null))
menuItemList.add(MenuItem("canScrollHorizontally: ${zoomer.canScrollHorizontally().toString()}", null))
menuItemList.add(MenuItem("canScrollVertically: ${zoomer.canScrollVertically().toString()}", null))
} else {
menuItemList.add(MenuItem("Zoom (Disabled)", null))
}
// 分块显示信息
if (zoomer != null) {
val blockDisplayer = zoomer.blockDisplayer
val blockInfoBuilder = StringBuilder()
when {
blockDisplayer.isReady -> {
blockInfoBuilder.append("Blocks:")
.append(blockDisplayer.blockBaseNumber)
.append("/")
.append(blockDisplayer.blockSize)
.append("/")
.append(Formatter.formatFileSize(context, blockDisplayer.allocationByteCount))
blockInfoBuilder.append("\n")
blockInfoBuilder.append("Blocks Area:").append(blockDisplayer.decodeRect.toShortString())
blockInfoBuilder.append("\n")
blockInfoBuilder.append("Blocks Area (SRC):").append(blockDisplayer.decodeSrcRect.toShortString())
}
blockDisplayer.isInitializing -> {
blockInfoBuilder.append("\n")
blockInfoBuilder.append("Blocks initializing...")
}
else -> blockInfoBuilder.append("Blocks (No need)")
}
menuItemList.add(MenuItem(blockInfoBuilder.toString(), null))
} else {
menuItemList.add(MenuItem("Blocks (Disabled)", null))
}
// 分块边界开关
if (zoomer != null) {
val blockDisplayer = zoomer.blockDisplayer
if (blockDisplayer.isReady || blockDisplayer.isInitializing) {
menuItemList.add(MenuItem(if (blockDisplayer.isShowBlockBounds) "Hide block bounds" else "Show block bounds",
DialogInterface.OnClickListener { _, _ -> image_imageFragment_image.zoomer?.blockDisplayer?.let { it.isShowBlockBounds = !it.isShowBlockBounds } }))
} else {
menuItemList.add(MenuItem("Block bounds (No need)", null))
}
} else {
menuItemList.add(MenuItem("Block bounds (Disabled)", null))
}
// 阅读模式开关
if (zoomer != null) {
menuItemList.add(MenuItem(if (zoomer.isReadMode) "Close read mode" else "Open read mode",
DialogInterface.OnClickListener { _, _ -> image_imageFragment_image.zoomer?.let { it.isReadMode = !it.isReadMode } }))
} else {
menuItemList.add(MenuItem("Read mode (Zoom disabled)", null))
}
// 旋转菜单
if (zoomer != null) {
menuItemList.add(MenuItem(String.format("Clockwise rotation 90°(%d)", zoomer.rotateDegrees),
DialogInterface.OnClickListener { _, _ ->
image_imageFragment_image.zoomer?.let {
if (!it.rotateBy(90)) {
Toast.makeText(context, "The rotation angle must be a multiple of 90", Toast.LENGTH_LONG).show()
}
}
}))
} else {
menuItemList.add(MenuItem("Clockwise rotation 90° (Zoom disabled)", null))
}
val items = arrayOfNulls<String>(menuItemList.size)
var w = 0
val size = menuItemList.size
while (w < size) {
items[w] = menuItemList[w].title
w++
}
val itemClickListener = DialogInterface.OnClickListener { dialog, which ->
dialog.dismiss()
menuItemList[which].clickListener?.onClick(dialog, which)
}
AlertDialog.Builder(activity)
.setItems(items, itemClickListener)
.show()
}
fun showScaleTypeMenu() {
val builder = AlertDialog.Builder(activity)
builder.setTitle("Toggle ScaleType")
val items = arrayOfNulls<String>(7)
items[0] = "CENTER"
items[1] = "CENTER_CROP"
items[2] = "CENTER_INSIDE"
items[3] = "FIT_START"
items[4] = "FIT_CENTER"
items[5] = "FIT_END"
items[6] = "FIT_XY"
builder.setItems(items) { dialog, which ->
dialog.dismiss()
when (which) {
0 -> image_imageFragment_image.scaleType = ImageView.ScaleType.CENTER
1 -> image_imageFragment_image.scaleType = ImageView.ScaleType.CENTER_CROP
2 -> image_imageFragment_image.scaleType = ImageView.ScaleType.CENTER_INSIDE
3 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_START
4 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_CENTER
5 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_END
6 -> image_imageFragment_image.scaleType = ImageView.ScaleType.FIT_XY
}
}
builder.setNegativeButton("Cancel", null)
builder.show()
}
fun getImageFile(imageUri: String?): File? {
val context = context ?: return null
if (TextUtils.isEmpty(imageUri)) {
return null
}
val uriModel = UriModel.match(context, imageUri!!)
if (uriModel == null) {
Toast.makeText(activity, "Unknown format uri: $imageUri", Toast.LENGTH_LONG).show()
return null
}
val dataSource: DataSource
try {
dataSource = uriModel.getDataSource(context, imageUri, null)
} catch (e: GetDataSourceException) {
e.printStackTrace()
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return null
}
return try {
dataSource.getFile(context.externalCacheDir, null)
} catch (e: IOException) {
e.printStackTrace()
null
}
}
fun share() {
val activity = activity ?: return
val drawable = image_imageFragment_image.drawable
val imageUri = if (drawable != null && drawable is SketchDrawable) (drawable as SketchDrawable).uri else null
if (TextUtils.isEmpty(imageUri)) {
Toast.makeText(activity, "Please wait later", Toast.LENGTH_LONG).show()
return
}
val imageFile = getImageFile(imageUri)
if (imageFile == null) {
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return
}
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile))
intent.type = "image/" + parseFileType(imageFile.name)!!
val infoList = activity.packageManager.queryIntentActivities(intent, 0)
if (infoList == null || infoList.isEmpty()) {
Toast.makeText(activity, "There is no APP on your device to share the picture", Toast.LENGTH_LONG).show()
return
}
startActivity(intent)
}
fun setWallpaper() {
val activity = activity ?: return
val drawable = image_imageFragment_image.drawable
val imageUri = if (drawable != null && drawable is SketchDrawable) (drawable as SketchDrawable).uri else null
if (TextUtils.isEmpty(imageUri)) {
Toast.makeText(activity, "Please wait later", Toast.LENGTH_LONG).show()
return
}
val imageFile = getImageFile(imageUri)
if (imageFile == null) {
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return
}
ApplyWallpaperAsyncTask(activity, imageFile).execute(0)
}
fun play() {
EventBus.getDefault().post(PlayImageEvent())
}
fun save() {
val context = context ?: return
val drawable = image_imageFragment_image.drawable
val imageUri = if (drawable != null && drawable is SketchDrawable) (drawable as SketchDrawable).uri else null
if (TextUtils.isEmpty(imageUri)) {
Toast.makeText(activity, "Please wait later", Toast.LENGTH_LONG).show()
return
}
val uriModel = UriModel.match(context, imageUri!!)
if (uriModel == null) {
Toast.makeText(activity, "Unknown format uri: $imageUri", Toast.LENGTH_LONG).show()
return
}
if (uriModel is FileUriModel) {
Toast.makeText(activity, "This image is the local no need to save", Toast.LENGTH_LONG).show()
return
}
val dataSource: DataSource
try {
dataSource = uriModel.getDataSource(context, imageUri, null)
} catch (e: GetDataSourceException) {
e.printStackTrace()
Toast.makeText(activity, "The Image is not ready yet", Toast.LENGTH_LONG).show()
return
}
SaveImageAsyncTask(activity, dataSource, imageUri).execute("")
}
fun parseFileType(fileName: String): String? {
val lastIndexOf = fileName.lastIndexOf("")
if (lastIndexOf < 0) {
return null
}
val fileType = fileName.substring(lastIndexOf + 1)
if ("" == fileType.trim { it <= ' ' }) {
return null
}
return fileType
}
private inner class MenuItem(val title: String, var clickListener: DialogInterface.OnClickListener?)
}
companion object {
const val PARAM_REQUIRED_STRING_IMAGE_URI = "PARAM_REQUIRED_STRING_IMAGE_URI"
const val PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY = "PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY"
const val PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS = "PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS"
fun build(image: Image, loadingImageOptionsId: String?, showTools: Boolean): ImageFragment {
val bundle = Bundle()
bundle.putParcelable(PARAM_REQUIRED_STRING_IMAGE_URI, image)
bundle.putString(PARAM_REQUIRED_STRING_LOADING_IMAGE_OPTIONS_KEY, loadingImageOptionsId)
bundle.putBoolean(PARAM_REQUIRED_BOOLEAN_SHOW_TOOLS, showTools)
val fragment = ImageFragment()
fragment.arguments = bundle
return fragment
}
}
} | sample/src/main/java/me/panpf/sketch/sample/ui/ImageFragment.kt | 826589624 |
package com.infinum.dbinspector.ui.shared.headers
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.infinum.dbinspector.databinding.DbinspectorItemHeaderBinding
internal class HeaderAdapter : RecyclerView.Adapter<HeaderViewHolder>() {
private var headerItems: List<Header> = listOf()
var isClickable: Boolean = false
var onClick: ((Header) -> Unit)? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HeaderViewHolder =
HeaderViewHolder(
DbinspectorItemHeaderBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
override fun onBindViewHolder(holder: HeaderViewHolder, position: Int) =
holder.bind(
headerItems[position % headerItems.size],
isClickable,
onClick
)
override fun onViewRecycled(holder: HeaderViewHolder) =
with(holder) {
holder.unbind()
super.onViewRecycled(this)
}
override fun getItemCount(): Int =
headerItems.size
fun setItems(headers: List<Header>) {
headerItems = headers
notifyDataSetChanged()
}
fun updateHeader(header: Header) {
headerItems = headerItems.map {
if (it.name == header.name) {
header.copy(active = true)
} else {
it.copy(active = false)
}
}
notifyDataSetChanged()
}
}
| dbinspector/src/main/kotlin/com/infinum/dbinspector/ui/shared/headers/HeaderAdapter.kt | 3273520750 |
/****************************************************************************************
* Copyright (c) 2013 Bibek Shrestha <[email protected]> *
* Copyright (c) 2013 Zaur Molotnikov <[email protected]> *
* Copyright (c) 2013 Nicolas Raoul <[email protected]> *
* Copyright (c) 2013 Flavio Lerda <[email protected]> *
* Copyright (c) 2020 Mike Hardy <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.web
import android.content.Context
import com.ichi2.async.Connection
import com.ichi2.compat.CompatHelper
import com.ichi2.libanki.sync.Tls12SocketFactory
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.VersionUtils.pkgVersionName
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import timber.log.Timber
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.URL
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit
/**
* Helper class to download from web.
* <p>
* Used in AsyncTasks in Translation and Pronunciation activities, and more...
*/
object HttpFetcher {
/**
* Get an OkHttpClient configured with correct timeouts and headers
*
* @param fakeUserAgent true if we should issue "fake" User-Agent header 'Mozilla/5.0' for compatibility
* @return OkHttpClient.Builder ready for use or further configuration
*/
fun getOkHttpBuilder(fakeUserAgent: Boolean): OkHttpClient.Builder {
val clientBuilder = OkHttpClient.Builder()
Tls12SocketFactory.enableTls12OnPreLollipop(clientBuilder)
.connectTimeout(Connection.CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
.writeTimeout(Connection.CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
.readTimeout(Connection.CONN_TIMEOUT.toLong(), TimeUnit.SECONDS)
if (fakeUserAgent) {
clientBuilder.addNetworkInterceptor(
Interceptor { chain: Interceptor.Chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("Referer", "com.ichi2.anki")
.header("User-Agent", "Mozilla/5.0 ( compatible ) ")
.header("Accept", "*/*")
.build()
)
}
)
} else {
clientBuilder.addNetworkInterceptor(
Interceptor { chain: Interceptor.Chain ->
chain.proceed(
chain.request()
.newBuilder()
.header("User-Agent", "AnkiDroid-$pkgVersionName")
.build()
)
}
)
}
return clientBuilder
}
fun fetchThroughHttp(address: String?, encoding: String? = "utf-8"): String {
Timber.d("fetching %s", address)
var response: Response? = null
return try {
val requestBuilder = Request.Builder()
requestBuilder.url(address!!).get()
val httpGet: Request = requestBuilder.build()
val client: OkHttpClient = getOkHttpBuilder(true).build()
response = client.newCall(httpGet).execute()
if (response.code != 200) {
Timber.d("Response code was %s, returning failure", response.code)
return "FAILED"
}
val reader = BufferedReader(
InputStreamReader(
response.body!!.byteStream(),
Charset.forName(encoding)
)
)
val stringBuilder = StringBuilder()
var line: String?
@KotlinCleanup("it's strange")
while (reader.readLine().also { line = it } != null) {
stringBuilder.append(line)
}
stringBuilder.toString()
} catch (e: Exception) {
Timber.d(e, "Failed with an exception")
"FAILED with exception: " + e.message
} finally {
response?.body?.close()
}
}
fun downloadFileToSdCard(UrlToFile: String, context: Context, prefix: String?): String {
var str = downloadFileToSdCardMethod(UrlToFile, context, prefix, "GET")
if (str.startsWith("FAIL")) {
str = downloadFileToSdCardMethod(UrlToFile, context, prefix, "POST")
}
return str
}
private fun downloadFileToSdCardMethod(UrlToFile: String, context: Context, prefix: String?, method: String): String {
var response: Response? = null
return try {
val url = URL(UrlToFile)
val extension = UrlToFile.substring(UrlToFile.length - 4)
val requestBuilder = Request.Builder()
requestBuilder.url(url)
if ("GET" == method) {
requestBuilder.get()
} else {
requestBuilder.post(ByteArray(0).toRequestBody(null, 0, 0))
}
val request: Request = requestBuilder.build()
val client: OkHttpClient = getOkHttpBuilder(true).build()
response = client.newCall(request).execute()
val file = File.createTempFile(prefix!!, extension, context.cacheDir)
val inputStream = response.body!!.byteStream()
CompatHelper.compat.copyFile(inputStream, file.canonicalPath)
inputStream.close()
file.absolutePath
} catch (e: Exception) {
Timber.w(e)
"FAILED " + e.message
} finally {
response?.body?.close()
}
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/web/HttpFetcher.kt | 4093890034 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.