repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
TachiWeb/TachiWeb-Server | Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/data/database/queries/CategoryQueries.kt | 1 | 1687 | package eu.kanade.tachiyomi.data.database.queries
import com.pushtorefresh.storio.sqlite.queries.Query
import com.pushtorefresh.storio.sqlite.queries.RawQuery
import eu.kanade.tachiyomi.data.database.DbProvider
import eu.kanade.tachiyomi.data.database.models.Category
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.database.tables.CategoryTable
interface CategoryQueries : DbProvider {
fun getCategory(id: Int) = db.get()
.`object`(Category::class.java)
.withQuery(Query.builder()
.table(CategoryTable.TABLE)
.where("${CategoryTable.COL_ID} = ?")
.whereArgs(id)
.build())
.prepare()
fun getCategories() = db.get()
.listOfObjects(Category::class.java)
.withQuery(Query.builder()
.table(CategoryTable.TABLE)
.orderBy(CategoryTable.COL_ORDER)
.build())
.prepare()
fun getCategoriesForManga(manga: Manga) = db.get()
.listOfObjects(Category::class.java)
.withQuery(RawQuery.builder()
.query(getCategoriesForMangaQuery())
.args(manga.id)
.build())
.prepare()
fun insertCategory(category: Category) = db.put().`object`(category).prepare()
fun insertCategories(categories: List<Category>) = db.put().objects(categories).prepare()
fun deleteCategory(category: Category) = db.delete().`object`(category).prepare()
fun deleteCategories(categories: List<Category>) = db.delete().objects(categories).prepare()
} | apache-2.0 | f5652529c234ac4d7981334277acd4b9 | 36.511111 | 96 | 0.621814 | 4.59673 | false | false | false | false |
excref/kotblog | blog/service/impl/src/test/kotlin/com/excref/kotblog/blog/service/tag/TagServiceIntegrationTest.kt | 1 | 1637 | package com.excref.kotblog.blog.service.tag
import com.excref.kotblog.blog.service.test.AbstractServiceIntegrationTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
/**
* @author Arthur Asatryan
* @since 6/4/17 4:12 PM
*/
class TagServiceIntegrationTest : AbstractServiceIntegrationTest() {
//region Dependencies
@Autowired
private lateinit var tagService: TagService
//endregion
//region Test methods
@Test
fun testCreate() {
// given
val name = "C++"
// when
val result = tagService.create(name)
// then
assertThat(result).isNotNull().extracting("name").containsOnly(name)
}
@Test
fun testGetByUuid() {
// given
val tag = helper.persistTag()
// when
val result = tagService.getByUuid(tag.uuid)
// then
assertThat(result).isNotNull().isEqualTo(tag)
}
@Test
fun testGetByUuids() {
// given
val tag = helper.persistTag()
val tag2 = helper.persistTag()
val tags = listOf(tag, tag2)
val tagsUuids = tags.map { it -> it.uuid }.toList()
// when
val result = tagService.getByUuids(tagsUuids)
// then
assertThat(result).isNotNull.containsAll(tags)
}
@Test
fun testExistsForName() {
// given
val name = "C++"
helper.persistTag(name)
// when
val existsForName = tagService.existsForName(name)
// then
assertThat(existsForName).isTrue()
}
//endregion
} | apache-2.0 | 21474f5018b72eed70393084b1a9fdc4 | 24.2 | 76 | 0.616982 | 4.319261 | false | true | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/activity/WidgetActivity.kt | 2 | 4886 | /*
* Copyright 2017 Vector Creations Ltd
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.activity
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import com.airbnb.mvrx.viewModel
import im.vector.R
import im.vector.fragments.roomwidgets.*
import im.vector.ui.themes.ThemeUtils
import im.vector.widgets.Widget
/*
* This class displays a widget
*/
class WidgetActivity : VectorAppCompatActivity() {
val viewModel: RoomWidgetViewModel by viewModel()
/* ==========================================================================================
* LIFE CYCLE
* ========================================================================================== */
override fun getLayoutRes() = R.layout.activity_widget
override fun getMenuRes() = R.menu.menu_room_widget
override fun getTitleRes() = R.string.room_widget_activity_title
@SuppressLint("NewApi")
override fun initUiAndData() {
configureToolbar()
supportActionBar?.setHomeAsUpIndicator(ContextCompat.getDrawable(this, R.drawable.ic_material_leave)?.let {
ThemeUtils.tintDrawableWithColor(it, Color.WHITE)
})
viewModel.selectSubscribe(this, RoomWidgetViewModelState::status) { ws ->
when (ws) {
WidgetState.UNKNOWN -> {
}
WidgetState.WIDGET_NOT_ALLOWED -> {
val dFrag = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_PERMISSION) as? RoomWidgetPermissionBottomSheet
if (dFrag != null && dFrag.dialog?.isShowing == true && !dFrag.isRemoving) {
//already there
} else {
RoomWidgetPermissionBottomSheet
.newInstance(viewModel.session!!.myUserId, viewModel.widget).apply {
onFinish = { accepted ->
if (!accepted) finish()
}
}
.show(supportFragmentManager, FRAGMENT_TAG_PERMISSION)
}
}
WidgetState.WIDGET_ALLOWED -> {
//mount the webview fragment if needed
if (supportFragmentManager.findFragmentByTag(FRAGMENT_TAG_WEBVIEW) == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, RoomWidgetFragment(), FRAGMENT_TAG_WEBVIEW)
.commit()
}
}
}
}
viewModel.selectSubscribe(this, RoomWidgetViewModelState::widgetName) { name ->
supportActionBar?.title = name
}
viewModel.selectSubscribe(this, RoomWidgetViewModelState::canManageWidgets) {
invalidateOptionsMenu()
}
viewModel.navigateEvent.observe(this, Observer { uxStateEvent ->
when (uxStateEvent?.getContentIfNotHandled()) {
RoomWidgetViewModel.NAVIGATE_FINISH -> {
finish()
}
}
})
viewModel.toastMessageEvent.observe(this, Observer {
it?.getContentIfNotHandled()?.let {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
}
})
}
/* ==========================================================================================
* companion
* ========================================================================================== */
companion object {
private const val FRAGMENT_TAG_PERMISSION = "FRAGMENT_TAG_PERMISSION"
private const val FRAGMENT_TAG_WEBVIEW = "WebView"
/**
* The linked widget
*/
const val EXTRA_WIDGET_ID = "EXTRA_WIDGET_ID"
fun getIntent(context: Context, widget: Widget): Intent {
return Intent(context, WidgetActivity::class.java)
.apply {
putExtra(EXTRA_WIDGET_ID, widget)
}
}
}
} | apache-2.0 | 6a5c1d2d531932f3262b4a66755142be | 36.592308 | 133 | 0.544208 | 5.648555 | false | false | false | false |
spinnaker/kork | kork-sql/src/main/kotlin/com/netflix/spinnaker/kork/sql/config/SecondaryPoolDialectCondition.kt | 3 | 2396 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.sql.config
import org.springframework.boot.autoconfigure.condition.ConditionOutcome
import org.springframework.boot.autoconfigure.condition.SpringBootCondition
import org.springframework.boot.context.properties.bind.Bindable
import org.springframework.boot.context.properties.bind.Binder
import org.springframework.boot.context.properties.source.ConfigurationPropertyName
import org.springframework.context.annotation.ConditionContext
import org.springframework.core.type.AnnotatedTypeMetadata
/**
* Condition that asserts if the secondary pool dialect matches the one defined by the primary.
*/
class SecondaryPoolDialectCondition : SpringBootCondition() {
override fun getMatchOutcome(context: ConditionContext?, metadata: AnnotatedTypeMetadata?): ConditionOutcome {
return ConditionOutcome(hasDifferentDialect(context), "SQL Dialect check did not pass")
}
private fun hasDifferentDialect(context: ConditionContext?): Boolean {
val sqlProperties: SqlProperties = Binder.get(context?.environment)
.bind(ConfigurationPropertyName.of("sql"), Bindable.of(SqlProperties::class.java))
.orElse(SqlProperties())
if (sqlProperties.connectionPools.size <= 1 || sqlProperties.connectionPools.size > 2) {
return false
}
val defaultPool: ConnectionPoolProperties = sqlProperties.connectionPools.first(default = true)
val secondaryPool: ConnectionPoolProperties = sqlProperties.connectionPools.first(default = false)
return defaultPool.dialect != secondaryPool.dialect
}
private fun MutableMap<String, ConnectionPoolProperties>.first(default: Boolean): ConnectionPoolProperties =
filter {
if (default) {
it.value.default
} else {
!it.value.default
}
}.values.first()
}
| apache-2.0 | 6e396e5a6f208a20a276f816bf178f69 | 39.610169 | 112 | 0.771703 | 4.572519 | false | true | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/dialogs/ManageExtendedDetailsDialog.kt | 1 | 2911 | package com.simplemobiletools.gallery.pro.dialogs
import androidx.appcompat.app.AlertDialog
import com.simplemobiletools.commons.activities.BaseSimpleActivity
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.helpers.*
import kotlinx.android.synthetic.main.dialog_manage_extended_details.view.*
class ManageExtendedDetailsDialog(val activity: BaseSimpleActivity, val callback: (result: Int) -> Unit) {
private var view = activity.layoutInflater.inflate(R.layout.dialog_manage_extended_details, null)
init {
val details = activity.config.extendedDetails
view.apply {
manage_extended_details_name.isChecked = details and EXT_NAME != 0
manage_extended_details_path.isChecked = details and EXT_PATH != 0
manage_extended_details_size.isChecked = details and EXT_SIZE != 0
manage_extended_details_resolution.isChecked = details and EXT_RESOLUTION != 0
manage_extended_details_last_modified.isChecked = details and EXT_LAST_MODIFIED != 0
manage_extended_details_date_taken.isChecked = details and EXT_DATE_TAKEN != 0
manage_extended_details_camera.isChecked = details and EXT_CAMERA_MODEL != 0
manage_extended_details_exif.isChecked = details and EXT_EXIF_PROPERTIES != 0
manage_extended_details_gps_coordinates.isChecked = details and EXT_GPS != 0
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok) { dialog, which -> dialogConfirmed() }
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
var result = 0
view.apply {
if (manage_extended_details_name.isChecked)
result += EXT_NAME
if (manage_extended_details_path.isChecked)
result += EXT_PATH
if (manage_extended_details_size.isChecked)
result += EXT_SIZE
if (manage_extended_details_resolution.isChecked)
result += EXT_RESOLUTION
if (manage_extended_details_last_modified.isChecked)
result += EXT_LAST_MODIFIED
if (manage_extended_details_date_taken.isChecked)
result += EXT_DATE_TAKEN
if (manage_extended_details_camera.isChecked)
result += EXT_CAMERA_MODEL
if (manage_extended_details_exif.isChecked)
result += EXT_EXIF_PROPERTIES
if (manage_extended_details_gps_coordinates.isChecked)
result += EXT_GPS
}
activity.config.extendedDetails = result
callback(result)
}
}
| gpl-3.0 | fe041bdda40560f67d6149584144ac1e | 45.951613 | 106 | 0.654071 | 4.665064 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/tv/account/TVAccountWizard.kt | 1 | 7255 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Author: Aline Bonnet <[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 cx.ring.tv.account
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.leanback.app.GuidedStepSupportFragment
import cx.ring.R
import cx.ring.account.AccountCreationModelImpl
import cx.ring.application.JamiApplication
import cx.ring.mvp.BaseActivity
import cx.ring.services.VCardServiceImpl
import dagger.hilt.android.AndroidEntryPoint
import ezvcard.VCard
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import net.jami.account.AccountWizardPresenter
import net.jami.account.AccountWizardView
import net.jami.model.Account
import net.jami.model.AccountConfig
import net.jami.model.AccountCreationModel
import net.jami.utils.VCardUtils
@AndroidEntryPoint
class TVAccountWizard : BaseActivity<AccountWizardPresenter>(), AccountWizardView {
private var mProgress: ProgressDialog? = null
private var mLinkAccount = false
private var mAccountType: String? = null
private var mAlertDialog: AlertDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
JamiApplication.instance?.startDaemon()
val intent = intent
if (intent != null) {
mAccountType = intent.action
}
if (mAccountType == null) {
mAccountType = AccountConfig.ACCOUNT_TYPE_RING
}
if (savedInstanceState == null) {
GuidedStepSupportFragment.addAsRoot(this, TVHomeAccountCreationFragment(), android.R.id.content)
} else {
mLinkAccount = savedInstanceState.getBoolean("mLinkAccount")
}
presenter.init(getIntent().action ?: AccountConfig.ACCOUNT_TYPE_RING)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("mLinkAccount", mLinkAccount)
}
override fun onDestroy() {
mProgress?.let { progress ->
progress.dismiss()
mProgress = null
}
super.onDestroy()
}
fun createAccount(accountCreationModel: AccountCreationModel) {
if (accountCreationModel.isLink) {
presenter.initJamiAccountLink(accountCreationModel, getText(R.string.ring_account_default_name).toString())
} else {
presenter.initJamiAccountCreation(accountCreationModel, getText(R.string.ring_account_default_name).toString())
}
}
override fun goToHomeCreation() {}
override fun goToSipCreation() {}
override fun onBackPressed() {
when (GuidedStepSupportFragment.getCurrentGuidedStepSupportFragment(supportFragmentManager)) {
is TVProfileCreationFragment -> finish()
is TVHomeAccountCreationFragment -> finishAffinity()
is TVJamiAccountCreationFragment -> supportFragmentManager.popBackStack()
else -> super.onBackPressed()
}
}
override fun goToProfileCreation(accountCreationModel: AccountCreationModel) {
GuidedStepSupportFragment.add(supportFragmentManager, TVProfileCreationFragment.newInstance(accountCreationModel as AccountCreationModelImpl))
}
override fun displayProgress(display: Boolean) {
if (display) {
mProgress = ProgressDialog(this).apply {
setTitle(R.string.dialog_wait_create)
setMessage(getString(R.string.dialog_wait_create_details))
setCancelable(false)
setCanceledOnTouchOutside(false)
show()
}
} else {
mProgress?.let { progress ->
if (progress.isShowing)
progress.dismiss()
mProgress = null
}
}
}
override fun displayCreationError() {
Toast.makeText(this@TVAccountWizard, "Error creating account", Toast.LENGTH_SHORT).show()
}
override fun blockOrientation() {
//Noop on TV
}
override fun finish(affinity: Boolean) {
if (affinity) {
val fm = fragmentManager
if (fm.backStackEntryCount >= 1) {
fm.popBackStack()
} else {
finish()
}
} else {
finishAffinity()
}
}
override fun saveProfile(account: Account, accountCreationModel: AccountCreationModel): Single<VCard> {
val filedir = filesDir
return accountCreationModel.toVCard()
.flatMap { vcard ->
account.loadedProfile = Single.fromCallable { VCardServiceImpl.readData(vcard) }.cache()
VCardUtils.saveLocalProfileToDisk(vcard, account.accountId, filedir)
}
.subscribeOn(Schedulers.io())
}
override fun displayGenericError() {
if (mAlertDialog != null && mAlertDialog!!.isShowing) {
return
}
mAlertDialog = AlertDialog.Builder(this@TVAccountWizard)
.setPositiveButton(android.R.string.ok, null)
.setTitle(R.string.account_cannot_be_found_title)
.setMessage(R.string.account_cannot_be_found_message)
.show()
}
override fun displayNetworkError() {
if (mAlertDialog != null && mAlertDialog!!.isShowing) {
return
}
mAlertDialog = AlertDialog.Builder(this@TVAccountWizard)
.setPositiveButton(android.R.string.ok, null)
.setTitle(R.string.account_no_network_title)
.setMessage(R.string.account_no_network_message)
.show()
}
override fun displayCannotBeFoundError() {
if (mAlertDialog != null && mAlertDialog!!.isShowing) {
return
}
mAlertDialog = AlertDialog.Builder(this@TVAccountWizard)
.setPositiveButton(android.R.string.ok, null)
.setTitle(R.string.account_cannot_be_found_title)
.setMessage(R.string.account_cannot_be_found_message)
.show()
}
override fun displaySuccessDialog() {
if (mAlertDialog != null && mAlertDialog!!.isShowing) {
return
}
setResult(RESULT_OK, Intent())
//startActivity(new Intent(this, HomeActivity.class));
finish()
}
fun profileCreated(accountCreationModel: AccountCreationModel, saveProfile: Boolean) {
presenter.profileCreated(accountCreationModel, saveProfile)
}
} | gpl-3.0 | 562d1cd37d9b90517aa8222b2b4337e7 | 35.646465 | 150 | 0.66368 | 4.75426 | false | false | false | false |
AlmasB/jweather | src/main/kotlin/com/almasb/jweather/WeatherData.kt | 1 | 390 | package com.almasb.jweather
data class WeatherData(var name: String = "",
var country: String = "",
var temperature: Double = 0.0,
var pressure: Double = 0.0,
var humidity: Double = 0.0,
var windSpeed: Double = 0.0,
var description: String = "") {
}
| mit | fc2b09949727469a6b1295f718756bbd | 34.454545 | 54 | 0.44359 | 4.875 | false | false | false | false |
VerifAPS/verifaps-lib | geteta/src/main/kotlin/edu/kit/iti/formal/automation/testtables/builder/automatonpipeline.kt | 1 | 13750 | package edu.kit.iti.formal.automation.testtables.builder
import edu.kit.iti.formal.automation.testtables.algorithms.StateReachability
import edu.kit.iti.formal.automation.testtables.model.*
import edu.kit.iti.formal.automation.testtables.model.automata.RowState
import edu.kit.iti.formal.automation.testtables.model.automata.SpecialState
import edu.kit.iti.formal.automation.testtables.model.automata.TestTableAutomaton
import edu.kit.iti.formal.automation.testtables.model.automata.TransitionType
import edu.kit.iti.formal.automation.testtables.model.options.Mode
import edu.kit.iti.formal.util.info
import kotlin.collections.set
class AutomatonBuilderPipeline(
val table: GeneralizedTestTable,
var steps: List<AutomatonConstructionTransformer> = listOf()) {
init {
steps = listOf(
RowGroupExpander(),
GotoRewriter(),
InitialAutomataCreator(),
if (table.options.mode == Mode.CONCRETE_TABLE)
AutomatonConcretizerTransformation()
else
RowStateCreator(),
TransitionCreator(),
InitialReachability()
)//AddMutualExclusionForStates())
}
fun transform(): AutomataTransformerState {
val automaton = TestTableAutomaton()
val init = AutomataTransformerState(table, automaton)
steps.fold(init) { acc, transformer -> transformer.transform(acc);acc }
return init
}
}
val Duration.minimum: Int
get() = when (this) {
is Duration.OpenInterval -> lower
is Duration.ClosedInterval -> lower
is Duration.Omega -> 0
}
val Duration.maximum: Int
get() = when (this) {
is Duration.OpenInterval -> minimum + 1
is Duration.ClosedInterval -> upper
is Duration.Omega -> 1
}
val stateNameError = "__ERROR__"
val stateNameSentinel = "__SENTINEL__"
/**
* This pipeline populates gotos from regions to rows.
* It also disables
*/
class GotoRewriter : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
rewriteGotos(model.testTable.region)
}
fun rewriteGotos(region: Region) {
}
}
/**
* If the gtt contains a row group with a minimum amount of iteration, we expand it under maintaining
* the reachability.
*
* Also maintins [AutomataTransformerState.flatRegion] and [AutomataTransformerState.stateReachability]
*/
open class RowGroupExpander : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
model.testTable.region = rewrite(model.testTable.region)
model.flatRegion = model.testTable.region.flat()
model.stateReachability = StateReachability(model.testTable.region)
}
companion object {
/**
* creates a new region, expand the children and itself.
*/
fun rewrite(region: Region): Region {
val m = region.duration.minimum
//expand this region if necessary
val r = if (m == 0) region else expand(region)
val children = ArrayList<TableNode>(r.children.size)
//expand this region if necessary
for (child in r.children) {
when (child) {
is TableRow -> children.add(child)
is Region -> children.add(rewrite(child))
}
}
r.children = children
return r
}
/**
* Unwind the given region
*/
fun expand(r: Region): Region {
val duration = r.duration
val dmodifier = duration.modifier
if (duration == Duration.Omega || !duration.isRepeatable
|| duration.minimum == 0/*TODO check if maximum==1 maybe required*/) {
return r
}
val seq = ArrayList<TableNode>(r.children.size)
val m = duration.maximum
for (iter in 1..m) {
val t = Region("${r.id}_${iter}")
t.duration = when {
(iter == m && duration is Duration.OpenInterval) ->
Duration.OpenInterval(0, dmodifier)
(duration is Duration.ClosedInterval && duration.minimum < iter && iter <= duration.maximum) ->
Duration.ClosedInterval(0, 1, dmodifier)
else ->
Duration.ClosedInterval(1, 1, dmodifier)
}
//TODO decide whether to copy/disable the goto commands
t.children = r.children.map {
val clone = it.clone()
clone.id = "${t.id}_${it.id}"
clone
}.toMutableList()
seq.add(t)
}
val new = Region(r.id, seq)
new.duration = Duration.ClosedInterval(1, 1, dmodifier)
return new
}
}
}
class InitialAutomataCreator : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
model.automaton.stateError = SpecialState(stateNameError)
model.automaton.stateSentinel = SpecialState(stateNameSentinel)
}
}
/* model.tableModule.stateVars.add(model.errorVariable)
// disable in the beginning
model.tableModule.initExpr.add(model.errorVariable.not())
val e = model.testTable.region.flat().stream()
.flatMap { s -> s.automataStates.stream() }
.map { s -> s.defFailed as SMVExpr }
.reduce { a, b -> a.or(b) }
.orElse(SLiteral.TRUE)
val a = SAssignment(model.errorVariable, e)
model.tableModule.nextAssignments.add(a)
val e = model.sentinelState.automataStates[0].incoming.stream()
.map { it.defForward }
.map { fwd -> fwd as SMVExpr }
.reduce(SMVFacade.reducer(SBinaryOperator.OR))
.orElse(SLiteral.FALSE)
val a = SAssignment(endSentinel, e.or(endSentinel))
tm.nextAssignments.add(a)
*/
/**
* Creates the rowStates and definition for each row and cycle including error and endSentinel.
* Created by weigl on 17.12.16.
*
* @version 3
*/
open class RowStateCreator : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
val flat = model.flatRegion
flat.forEach { this.introduceState(it) }
}
open fun createRowStates(s: TableRow): List<RowState> {
val duration = s.duration
return when (duration) {
is Duration.Omega -> {
val a = RowState(s, 1)
a.strongRepetition = true
listOf(a)
}
is Duration.OpenInterval ->
if (duration.lower == 0) {
listOf(RowState(s, 1).also { a ->
a.optional = true
a.weakRepeat = true
a.progressFlag = duration.pflag
})
} else
(1..duration.lower).map {
RowState(s, it).also { a ->
a.optional = it == duration.lower
a.weakRepeat = a.optional
if (a.optional)
a.progressFlag = duration.pflag
}
}
is Duration.ClosedInterval ->
(1..duration.upper).map {
RowState(s, it).also { a ->
a.optional = it >= duration.lower
if (a.optional)
a.progressFlag = duration.pflag
}
}
}
}
private fun introduceState(s: TableRow) {
val states = createRowStates(s)
model.automaton.rowStates[s] = states
}
}
/**
* Creates an mutual exclusion for states, based on the progress flag.
*
class AddMutualExclusionForStates : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
model.testTable.region.flat().forEach {
if(it.duration.pflag){
val astate = model.automaton.getState(it,)
model.automaton.mutualExclusiveStates.computeIfAbsent()
it.outgoing
}
}
//TODO("not implemented")
}
}*/
class InitialReachability : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
model.flatRegion
.filter { it.isInitialReachable }
.forEach { it ->
val astate = model.automaton.getState(it, 0)
astate?.let { model.automaton.initialStates += it }
}
}
}
class TransitionCreator : AbstractTransformer<AutomataTransformerState>() {
override fun transform() {
model.flatRegion.forEach(this::internalTransitions)
model.flatRegion.forEach(this::externalTransitions)
errorTransitions()
sentinelTransitions()
selfLoops()
}
private fun sentinelTransitions() {
val sentinel = model.stateReachability.endSentinel
val sentinelState = model.automaton.stateSentinel
sentinel.incoming.forEach { it ->
model.automaton.getStates(it)
?.filter { it.optional }
?.forEach { oFrom ->
model.automaton.addTransition(oFrom, sentinelState, TransitionType.ACCEPT)
}
}
}
private fun selfLoops() {
model.automaton.rowStates.values.flatMap { it }
.filter { it.weakRepeat || it.strongRepetition }
.forEach {
model.automaton.addTransition(it, it,
transitionTypeAccept(it.row.duration))
}
model.automaton.addTransition(model.automaton.stateSentinel,
model.automaton.stateSentinel, TransitionType.TRUE)
}
private fun errorTransitions() {
val errorState = model.automaton.stateError
model.flatRegion.forEach {
model.automaton.getStates(it)?.forEach { state ->
model.automaton.addTransition(
state, errorState, TransitionType.FAIL)
}
}
}
private fun internalTransitions(s: TableRow) {
model.automaton.getStates(s)?.let { states ->
states.zipWithNext { a, b ->
val pflag = s.duration.pflag && s.duration.isOptional(a.time)
model.automaton.addTransition(a, b,
if (pflag) TransitionType.ACCEPT_PROGRESS else TransitionType.ACCEPT)
}
}
}
private fun externalTransitions(s: TableRow) {
val jumpOut = model.automaton.getStates(s)?.filter { it.optional } ?: listOf()
s.outgoing.filter { it != model.stateReachability.endSentinel }
.forEach { to ->
model.automaton.getFirstState(to)?.let { toState ->
jumpOut.forEach { out ->
model.automaton.addTransition(out, toState,
transitionTypeAccept(s.duration))
}
}
}
}
}
/**
* This transformation ensures a specified minimal execution of cycles in rows.
*/
class AutomatonConcretizerTransformation : RowStateCreator() {
override fun createRowStates(s: TableRow): List<RowState> {
val cto = model.testTable.options.cycles
val c = cto.getCount(s.id, s.duration)
s.duration = Duration.ClosedInterval(c, c)
return super.createRowStates(s)
}
}
/*
*
private fun introduceAutomatonState(automatonTableRow: TableRow.AutomatonState) {
val `var` = automatonTableRow.smvVariable
// sate variable
model.tableModule.stateVars.add(`var`)
//initialize state variable with true iff isStartState
model.tableModule.initExpr.add(if (automatonTableRow.isStartState) `var` else `var`.not())
//If one predeccor is true, then we are true.
var incoming: Stream<TableRow.AutomatonState> = automatonTableRow.incoming.stream()
//remove self-loop on DET_WAIT, because we cannot use `_fwd`, we need `_keep`
if (automatonTableRow.state.duration.isDeterministicWait) {
incoming = incoming.filter { `as` -> `as` != automatonTableRow }
}
var activate = incoming
.map { inc ->
var fwd: SMVExpr = inc.defForward
/* If incoming state is det.wait, then this state becomes only active
* if it has not fired before.
*/
if (inc.state.duration.isDeterministicWait) {
val inputAndState = automatonTableRow.smvVariable.and(automatonTableRow.state.defInput).not()
fwd = fwd.and(inputAndState)
}
fwd
}
.map { SMVExpr::class.java.cast(it) }
.reduce(SMVFacade.reducer(SBinaryOperator.OR))
.orElse(SLiteral.FALSE)
if (automatonTableRow.state.duration.isDeterministicWait) {
// If this state is true, it stays true, until
// no successor was correctly guessed.
activate = activate.or(
`var`.and(automatonTableRow.state.defProgress
))
//TODO add following state (s->!s_in)
}
/*
if (automatonTableRow.isUnbounded()) {
or = SMVFacade.combine(SBinaryOperator.OR, or,
automatonTableRow.getDefForward());
}*/
val assignment = SAssignment(
automatonTableRow.smvVariable, activate)
model.tableModule.nextAssignments.add(assignment)
}
private fun define(defOutput: SVariable, combine: SMVExpr) {
model.tableModule.definitions[defOutput] = combine
}
}
private val Duration.isDeterministicWait: Boolean
get() =
when (this) {
is Duration.OpenInterval -> pflag
is Duration.ClosedInterval -> pflag
else -> false
}
*/
private fun transitionTypeAccept(duration: Duration) =
if (duration.pflag) TransitionType.ACCEPT_PROGRESS
else TransitionType.ACCEPT
| gpl-3.0 | 6361e41272e3b6f765ff2cea5598379a | 32.292978 | 115 | 0.602109 | 4.307644 | false | false | false | false |
funfunStudy/algorithm | kotlin/src/main/kotlin/LongestSubstringFromChanHo.kt | 1 | 1290 | import kotlin.math.max
fun main(args: Array<String>) {
val problems = listOf("abcabcbb", "bbbbb", "pwwkew", "", "dvdf", "asjrgapa")
val expected = listOf(3, 1, 3, 0, 3, 6)
problems.mapIndexed { index, s -> Pair(solution(s), expected.get(index)) }
.forEach { (result, expected) ->
println("result = $result, expected = $expected")
assert(result == expected)
}
}
fun solution(str: String): Int {
return maxLength(substring(str))
}
fun substring(str: String): List<String> {
return if (str.isEmpty())
listOf()
else {
str.fold(mutableListOf<String>()) { acc, ch ->
if (acc.size == 0) {
acc.add("$ch")
} else {
val tmp = acc[acc.size - 1]
if (tmp.contains("$ch")) {
acc.add("${tmp.drop(tmp.lastIndexOf(ch) + 1)}$ch")
} else {
acc[acc.size - 1] = "$tmp$ch"
}
}
acc
}
}
}
fun maxLength(strs: List<String>): Int {
return strs.map {
it.length
}.takeIf {
it.size >= 2
}?.reduce { acc, i ->
max(acc, i)
}?: run {
if (strs.isEmpty()) 0
else strs[0].length
}
}
| mit | 3d2c1c6fcb75c189b67752baf4941418 | 23.807692 | 80 | 0.466667 | 3.654391 | false | false | false | false |
funfunStudy/algorithm | kotlin/src/main/kotlin/SugarDelivery.kt | 1 | 793 | object SugarDelivery {
@JvmStatic
fun main(args: Array<String>) {
require(solve(18) == 4, { "error" })
require(solve(4) == -1, { "error" })
require(solve(6) == 2, { "error" })
require(solve(9) == 3, { "error" })
require(solve(11) == 3, { "error" })
require(solve(5000) == 1000, { "error" })
}
private fun solve(number: Int): Int = recursive(number, number / 5)
private tailrec fun recursive(number: Int, fiveModResult: Int): Int = when {
number % 5 == 0 -> fiveModResult
fiveModResult >= 0 -> if ((number - (fiveModResult * 5)) % 3 == 0) {
fiveModResult + (number - (fiveModResult * 5)) / 3
} else {
recursive(number, fiveModResult - 1)
}
else -> -1
}
}
| mit | 61c448cd1a2b9fb4bcd5eea1b10c2ef1 | 32.041667 | 80 | 0.517024 | 3.47807 | false | false | false | false |
FutureioLab/FastPeak | app/src/main/java/com/binlly/fastpeak/repo/DemoRepo.kt | 1 | 1566 | package com.binlly.fastpeak.repo
import com.binlly.fastpeak.api.ApiConfig
import com.binlly.fastpeak.base.net.ReqParams
import com.binlly.fastpeak.base.net.RetrofitManager
import com.binlly.fastpeak.base.rx.IoTransformer
import com.binlly.fastpeak.business.demo.fragment.DemoFragmentModel
import com.binlly.fastpeak.business.demo.model.DemoModel
import com.binlly.fastpeak.repo.service.DemoService
import io.reactivex.Observer
/**
* Created by binlly on 16/9/7.
*/
object DemoRepo {
private val TAG = DemoRepo::class.java.simpleName
private val mService = RetrofitManager.create(DemoService::class.java)
private val mMockService = RetrofitManager.createMock(
DemoService::class.java)
private val mServiceProxy = DynamicProxy(mService, mMockService).getProxy<DemoService>()
fun putUserCache(demo: DemoModel) {
val key = ApiConfig.URL_DEMO
RepoCache.put(key, demo)
}
fun requestDemo(observer: Observer<DemoModel>) {
val params = ReqParams(TAG)
try {
mServiceProxy.requestDemo(params.getFieldMap()).compose(IoTransformer()).subscribe(
observer)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun requestImageList(observer: Observer<DemoFragmentModel>) {
val params = ReqParams(TAG)
try {
mServiceProxy.requestImageList(params.getFieldMap()).compose(IoTransformer()).subscribe(
observer)
} catch (e: Exception) {
e.printStackTrace()
}
}
} | mit | bf0459ff145e90492dc040d357fa3338 | 30.979592 | 100 | 0.685824 | 4.164894 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/glNext/tut04/shaderPerspective.kt | 2 | 5107 | package glNext.tut04
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL3
import glNext.*
import glm.size
import main.framework.Framework
import uno.buffer.*
import uno.glsl.programOf
/**
* Created by GBarbieri on 22.02.2017.
*/
fun main(args: Array<String>) {
ShaderPerspective_Next().setup("Tutorial 04 - Shader Perspective")
}
class ShaderPerspective_Next : Framework() {
var theProgram = 0
var offsetUniform = 0
val vertexBufferObject = intBufferBig(1)
val vao = intBufferBig(1)
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeVertexBuffer(gl)
glGenVertexArray(vao)
glBindVertexArray(vao)
cullFace {
enable()
cullFace = back
frontFace = cw
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut04", "manual-perspective.vert", "standard-colors.frag")
withProgram(theProgram) {
offsetUniform = "offset".location
use {
"frustumScale".location.float = 1.0f
"zNear".location.float = 1.0f
"zFar".location.float = 3.0f
}
}
}
fun initializeVertexBuffer(gl: GL3) = with(gl) {
glGenBuffer(vertexBufferObject)
withArrayBuffer(vertexBufferObject) { data(vertexData, GL_STATIC_DRAW) }
}
override fun display(gl: GL3) = with(gl) {
clear { color(0) }
usingProgram(theProgram) {
glUniform2f(offsetUniform, 0.5f)
val colorData = vertexData.size / 2
withVertexLayout(vertexBufferObject, glf.pos4_col4, 0, colorData) { glDrawArrays(36) }
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffer(vertexBufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vao, vertexBufferObject, vertexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
}
}
val vertexData = floatBufferOf(
+0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
+0.25f, +0.25f, -2.75f, 1.0f,
-0.25f, +0.25f, -1.25f, 1.0f,
-0.25f, +0.25f, -2.75f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -1.25f, 1.0f,
+0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -2.75f, 1.0f,
-0.25f, -0.25f, -1.25f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.8f, 0.8f, 0.8f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
0.5f, 0.5f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f)
} | mit | 19bcbfc14e471350976d96dd694127f0 | 25.194872 | 105 | 0.462111 | 2.351289 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/command/profile/ProfileLinkCommand.kt | 1 | 2960 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.command.profile
import com.rpkit.core.command.RPKCommandExecutor
import com.rpkit.core.command.result.CommandResult
import com.rpkit.core.command.result.IncorrectUsageFailure
import com.rpkit.core.command.result.NoPermissionFailure
import com.rpkit.core.command.sender.RPKCommandSender
import com.rpkit.players.bukkit.RPKPlayersBukkit
import java.util.concurrent.CompletableFuture
/**
* Account link command.
* Links another account to the current player.
*/
class ProfileLinkCommand(private val plugin: RPKPlayersBukkit) : RPKCommandExecutor {
private val profileLinkIRCCommand = ProfileLinkIRCCommand(plugin)
private val profileLinkMinecraftCommand = ProfileLinkMinecraftCommand(plugin)
private val profileLinkDiscordCommand = ProfileLinkDiscordCommand(plugin)
private val profileLinkGithubCommand = ProfileLinkGithubCommand(plugin)
override fun onCommand(sender: RPKCommandSender, args: Array<out String>): CompletableFuture<out CommandResult> {
if (!sender.hasPermission("rpkit.players.command.profile.link")) {
sender.sendMessage(plugin.messages.noPermissionProfileLink)
return CompletableFuture.completedFuture(NoPermissionFailure("rpkit.players.command.profile.link"))
}
if (args.isNotEmpty()) {
val newArgs = args.drop(1).toTypedArray()
return when {
args[0].equals("irc", ignoreCase = true) ->
profileLinkIRCCommand.onCommand(sender, newArgs)
args[0].equals("minecraft", ignoreCase = true) || args[0].equals("mc", ignoreCase = true) ->
profileLinkMinecraftCommand.onCommand(sender, newArgs)
args[0].equals("discord", ignoreCase = true) ->
profileLinkDiscordCommand.onCommand(sender, newArgs)
args[0].equals("github", ignoreCase = true) ->
profileLinkGithubCommand.onCommand(sender, newArgs)
else -> {
sender.sendMessage(plugin.messages.profileLinkUsage)
CompletableFuture.completedFuture(IncorrectUsageFailure())
}
}
} else {
sender.sendMessage(plugin.messages.profileLinkUsage)
return CompletableFuture.completedFuture(IncorrectUsageFailure())
}
}
}
| apache-2.0 | 14a292be4f982988ef69945d914ad6f3 | 44.538462 | 117 | 0.702365 | 4.868421 | false | false | false | false |
ajalt/clikt | clikt/src/commonTest/kotlin/com/github/ajalt/clikt/parameters/types/IntTest.kt | 1 | 2317 | package com.github.ajalt.clikt.parameters.types
import com.github.ajalt.clikt.core.BadParameterValue
import com.github.ajalt.clikt.parameters.arguments.argument
import com.github.ajalt.clikt.parameters.arguments.multiple
import com.github.ajalt.clikt.parameters.arguments.optional
import com.github.ajalt.clikt.parameters.options.default
import com.github.ajalt.clikt.parameters.options.option
import com.github.ajalt.clikt.testing.TestCommand
import com.github.ajalt.clikt.testing.parse
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.data.blocking.forAll
import io.kotest.data.row
import io.kotest.matchers.shouldBe
import kotlin.js.JsName
import kotlin.test.Test
@Suppress("unused")
class IntTypeTest {
@Test
@JsName("int_option")
fun `int option`() = forAll(
row("", null),
row("--xx=4", 4),
row("-x5", 5)) { argv, expected ->
class C : TestCommand() {
val x by option("-x", "--xx").int()
override fun run_() {
x shouldBe expected
}
}
C().parse(argv)
}
@Test
@JsName("int_option_error")
fun `int option error`() {
class C : TestCommand(called = false) {
val foo by option().int()
}
shouldThrow<BadParameterValue> { C().parse("--foo bar") }
.message shouldBe "Invalid value for \"--foo\": bar is not a valid integer"
}
@Test
@JsName("int_option_with_default")
fun `int option with default`() = forAll(
row("", 111),
row("--xx=4", 4),
row("-x5", 5)) { argv, expected ->
class C : TestCommand() {
val x by option("-x", "--xx").int().default(111)
override fun run_() {
x shouldBe expected
}
}
C().parse(argv)
}
@Test
@JsName("int_argument")
fun `int argument`() = forAll(
row("", null, emptyList()),
row("1 2", 1, listOf(2)),
row("1 2 3", 1, listOf(2, 3))) { argv, ex, ey ->
class C : TestCommand() {
val x by argument().int().optional()
val y by argument().int().multiple()
override fun run_() {
x shouldBe ex
y shouldBe ey
}
}
C().parse(argv)
}
}
| apache-2.0 | bfa815e762d9351a1e1c11a4bc6fa14d | 28.329114 | 87 | 0.57186 | 3.987952 | false | true | false | false |
carmenlau/chat-SDK-Android | chat_example/src/main/java/io/skygear/chatexample/CreateConversationActivity.kt | 1 | 3372 | package io.skygear.chatexample
import android.app.ProgressDialog
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.Button
import android.widget.Toast
import io.skygear.plugins.chat.*
import io.skygear.skygear.Container
import io.skygear.skygear.Error
import java.util.*
class CreateConversationActivity : AppCompatActivity() {
private val LOG_TAG: String? = "CreateConversation"
private val mSkygear: Container
private val mChatContainer: ChatContainer
private val mAdapter: ChatUsesAdapter
private var mCreateBtn: Button? = null
private var mUserIdsRv: RecyclerView? = null
init {
mSkygear = Container.defaultContainer(this)
mChatContainer = ChatContainer.getInstance(mSkygear)
mAdapter = ChatUsesAdapter(mSkygear.auth.currentUser.id)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_create_conversation)
mUserIdsRv = findViewById<RecyclerView>(R.id.chat_users_rv)
mCreateBtn = findViewById<Button>(R.id.create_conversation_btn)
mUserIdsRv?.adapter = mAdapter
mUserIdsRv?.layoutManager = LinearLayoutManager(this)
mCreateBtn?.setOnClickListener {
val selectedUsers = mAdapter.getSelected()
if (selectedUsers.isNotEmpty()) {
createTitleDialog()
}
}
}
override fun onResume() {
super.onResume()
mChatContainer.getChatUsers(object : GetCallback<List<ChatUser>> {
override fun onSucc(list: List<ChatUser>?) {
mAdapter.setChatUsers(list);
}
override fun onFail(error: Error) {
}
})
}
fun createTitleDialog() {
val f = TitleFragment()
f.setOnOkBtnClickedListener { t -> createConversation(mAdapter.getSelected(), t) }
f.show(supportFragmentManager, "create_conversation")
}
fun createConversation(users: List<ChatUser>?, title: String?) {
if (users != null && users.isNotEmpty()) {
val participantIds = users.map { it.id }.toMutableSet()
val currentUser = mSkygear.auth.currentUser
if (currentUser != null) {
participantIds.add(currentUser.id)
}
val loading = ProgressDialog(this)
loading.setTitle(R.string.loading)
loading.setMessage(getString(R.string.creating))
loading.show()
mChatContainer.createConversation(participantIds, title, null, null, object : SaveCallback<Conversation> {
override fun onSucc(`object`: Conversation?) {
loading.dismiss()
finish()
}
override fun onFail(error: Error) {
loading.dismiss()
if (error.message != null) {
toast(error.message.toString())
}
}
})
}
}
fun toast(r: String) {
val context = applicationContext
val duration = Toast.LENGTH_SHORT
val toast = Toast.makeText(context, r, duration)
toast.show()
}
}
| apache-2.0 | ee035695916ad57e7a80b1cbfedd42b8 | 31.737864 | 118 | 0.625148 | 4.709497 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/ReplyUtils.kt | 1 | 3652 | package net.perfectdreams.loritta.morenitta.utils
import net.perfectdreams.loritta.morenitta.api.commands.CommandContext
import net.perfectdreams.loritta.morenitta.messages.LorittaReply
/**
* Class used for building styled replies with DSL to make creating
* multiple replies easier and nicer!
*/
class ReplyBuilder {
private val replies = mutableListOf<LorittaReply>()
/**
* Adds a standard [LorittaReply] to the [replies]
* list, that will be present on the [build] result
*
* @param reply The reply that will be appended
*/
fun append(reply: LorittaReply) =
replies.add(reply)
/**
* Appends a reply without using DSL, it's good for
* compact replies
*
* @param message The message that will be displayed after the prefix
* @param prefix The first thing displayed on the built message (usually an emoji/emote)
* @param hasPadding If [prefix] is null and this value is set to true, the prefix will be the blue diamond emoji (🔹)
* @param mentionUser If set to true, we'll mention the user on the reply
*/
fun append(message: String = " ", prefix: String? = null, forceMention: Boolean = false, hasPadding: Boolean = true, mentionUser: Boolean = true) =
append(LorittaReply(message, prefix, forceMention, hasPadding, mentionUser))
/**
* Appends a new reply with the provided data
* at the [reply] scope
*
* @param reply The reply data/message
*/
inline fun append(reply: StyledReplyWrapper.() -> Unit) =
append(StyledReplyWrapper().apply(reply).asLorittaReply())
/**
* If the [condition] is true, we'll append the provided
* reply wrapper
*
* @param condition The condition that will be checked
* @param reply The reply that will be added if [condition] is true
*/
inline fun appendIf(condition: Boolean, reply: StyledReplyWrapper.() -> Unit) {
if (condition) {
append(reply)
}
}
fun build(): List<LorittaReply> = replies
}
/**
* A mutable [LorittaReply] wrapper to provide a better DSL
* experience to replies
*
* @param message The message that will be displayed after the prefix
* @param prefix The first thing displayed on the built message (usually an emoji/emote)
* @param hasPadding If [prefix] is null and this value is set to true, the prefix will be the blue diamond emoji (🔹)
* @param mentionUser If set to true, we'll mention the user on the reply
*/
data class StyledReplyWrapper(
var message: String = " ",
var prefix: String? = null,
var forceMention: Boolean = false,
var hasPadding: Boolean = true,
var mentionUser: Boolean = true
) {
/**
* Create a [LorittaReply] instance with all the provided data
* at the constructor, or the data that was implemented later.
*
* @return The wrapped [LorittaReply]
*/
fun asLorittaReply() = LorittaReply(message, prefix, forceMention, hasPadding, mentionUser)
}
/**
* Creates a [ReplyBuilder], this makes replies much nicer and
* smoother, and of course, provides the extraordinary DSL experience!
*
* @param builder The reply builder
*/
suspend fun CommandContext.sendStyledReply(builder: ReplyBuilder.() -> Unit) =
reply(buildStyledReply(builder))
/**
* Just creates a [MutableList<LorittaReply>] of all the
* appended replies inside the DSL
*
* @param builder The reply builder
* @return All the provided replies inside the [builder] scope
*/
fun buildStyledReply(builder: ReplyBuilder.() -> Unit) =
ReplyBuilder().apply(builder).build() | agpl-3.0 | 9df47242d1edbbe226947d38a4c37195 | 33.733333 | 151 | 0.679375 | 4.319905 | false | false | false | false |
peterholak/mogul | native/src/mogul/microdom/testScene.kt | 2 | 1384 | package mogul.microdom
import mogul.microdom.primitives.microDom
@Suppress("unused")
fun testScene(): Scene {
val weirdBorders = Borders(
width = EdgeSizes(top = 2, right = 3, bottom = 3, left = 2),
color = EdgeColors(top = 0xAAAAAA.color, left = 0xAAAAAA.color, bottom = 0x444444.color, right = 0x444444.color)
)
val myStyle = style { width = 100; height = 100; border = weirdBorders }
return microDom {
row {
spacing = 50
style { padding = 50.all; margin = 50.all }
box { style = myStyle }
box {
style = myStyle
box {
style {
width = 50; height = 50
margin = 10.top and 30.left
backgroundColor = 0x00FF00.color
borders(1, 0x008000.color)
}
}
}
column {
spacing = 30
-"Hello world!"
text {
-"Other text"
style { color = 0x0000FF.color; margin = 30.left }
}
box {
style { border = Borders(1); padding = 10.all }
text("In a box") { style { color = 0xFF0000.color } }
}
}
}
}
}
| mit | 34f40dc5c81cb5d98893afadf40b6d84 | 30.454545 | 124 | 0.431358 | 4.522876 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/selectors/noneselector.kt | 1 | 5463 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExecutableSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.OwnedBySelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.ReadableSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.SymlinkSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.WritableSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface INoneSelectorNested : INestedComponent {
fun none(
error: String? = null,
nested: (KNoneSelector.() -> Unit)? = null)
{
_addNoneSelector(NoneSelector().apply {
component.project.setProjectReference(this);
_init(error, nested)
})
}
fun _addNoneSelector(value: NoneSelector)
}
fun NoneSelector._init(
error: String?,
nested: (KNoneSelector.() -> Unit)?)
{
if (error != null)
setError(error)
if (nested != null)
nested(KNoneSelector(this))
}
class KNoneSelector(override val component: NoneSelector) :
IFileSelectorNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IFilenameSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IDifferentSelectorNested,
ITypeSelectorNested,
IContainsRegexpSelectorNested,
IModifiedSelectorNested,
IReadableSelectorNested,
IWritableSelectorNested,
IExecutableSelectorNested,
ISymlinkSelectorNested,
IOwnedBySelectorNested
{
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value)
override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value)
override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value)
override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value)
override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value)
}
| apache-2.0 | 4cda90e324b9e5a7fdded7e30edb2d7e | 43.778689 | 108 | 0.794252 | 4.037694 | false | false | false | false |
RyanAndroidTaylor/Rapido | rapidosqlite/src/main/java/com/izeni/rapidosqlite/query/ManyToMany.kt | 1 | 1528 | package com.izeni.rapidosqlite.query
import com.izeni.rapidosqlite.table.Column
/**
* Created by ner on 2/8/17.
*/
class ManyToMany : Join() {
private lateinit var returnTableName: String
private lateinit var returnTableColumn: String
private lateinit var joinTableName: String
private lateinit var joinColumn: String
private lateinit var junctionTableName: String
private lateinit var junctionToReturnConnection: String
private lateinit var junctionToJoinConnection: String
fun returnTable(tableName: String, column: Column): ManyToMany {
returnTableName = tableName
returnTableColumn = column.name
return this
}
fun joinTable(tableName: String, column: Column): ManyToMany {
joinTableName = tableName
joinColumn = column.name
return this
}
fun junctionTable(tableName: String, returnConnection: Column, joinConnection: Column): ManyToMany {
junctionTableName = tableName
junctionToReturnConnection = returnConnection.name
junctionToJoinConnection = joinConnection.name
return this
}
fun build(): String {
return stringBuilder.append(returnTableName,
leftJoin, junctionTableName, on, returnTableName, period, returnTableColumn, equals, junctionToReturnConnection,
leftJoin, joinTableName, on, joinTableName, period, joinColumn, equals, junctionToJoinConnection)
.toString()
}
} | mit | 801f0811a9bfcdb8bf70e36e4f08049d | 30.854167 | 148 | 0.691754 | 5.110368 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/test/kotlin/org/jitsi/videobridge/cc/allocation/SingleSourceAllocationTest.kt | 1 | 16711 | /*
* Copyright @ 2021 - present 8x8, Inc.
* Copyright @ 2021 - Vowel, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NAME_SHADOWING")
package org.jitsi.videobridge.cc.allocation
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.shouldBe
import org.jitsi.nlj.MediaSourceDesc
import org.jitsi.nlj.RtpEncodingDesc
import org.jitsi.nlj.VideoType
import org.jitsi.nlj.util.bps
import org.jitsi.nlj.util.kbps
import org.jitsi.utils.logging.DiagnosticContext
import org.jitsi.utils.time.FakeClock
/**
* Test the logic for selecting the layers to be considered for a source and the "preferred" layer.
*/
class SingleSourceAllocationTest : ShouldSpec() {
private val clock = FakeClock()
private val diagnosticContext = DiagnosticContext()
private val ld7_5 = MockRtpLayerDesc(tid = 0, eid = 0, height = 180, frameRate = 7.5, bitrate = bitrateLd * 0.33)
private val ld15 = MockRtpLayerDesc(tid = 1, eid = 0, height = 180, frameRate = 15.0, bitrate = bitrateLd * 0.66)
private val ld30 = MockRtpLayerDesc(tid = 2, eid = 0, height = 180, frameRate = 30.0, bitrate = bitrateLd)
private val sd7_5 = MockRtpLayerDesc(tid = 0, eid = 1, height = 360, frameRate = 7.5, bitrate = bitrateSd * 0.33)
private val sd15 = MockRtpLayerDesc(tid = 1, eid = 1, height = 360, frameRate = 15.0, bitrate = bitrateSd * 0.66)
private val sd30 = MockRtpLayerDesc(tid = 2, eid = 1, height = 360, frameRate = 30.0, bitrate = bitrateSd)
private val hd7_5 = MockRtpLayerDesc(tid = 0, eid = 2, height = 720, frameRate = 7.5, bitrate = bitrateHd * 0.33)
private val hd15 = MockRtpLayerDesc(tid = 1, eid = 2, height = 720, frameRate = 15.0, bitrate = bitrateHd * 0.66)
private val hd30 = MockRtpLayerDesc(tid = 2, eid = 2, height = 720, frameRate = 30.0, bitrate = bitrateHd)
init {
context("Camera") {
context("When all layers are active") {
val endpointId = "A"
val mediaSource = MediaSourceDesc(
arrayOf(
RtpEncodingDesc(1L, arrayOf(ld7_5, ld15, ld30)),
RtpEncodingDesc(1L, arrayOf(sd7_5, sd15, sd30)),
RtpEncodingDesc(1L, arrayOf(hd7_5, hd15, hd30))
),
sourceName = sourceName,
owner = owner,
videoType = VideoType.CAMERA
)
context("Without constraints") {
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(720), false, diagnosticContext, clock
)
// We include all resolutions up to the preferred resolution, and only high-FPS (at least
// "preferred FPS") layers for higher resolutions.
allocation.preferredLayer shouldBe sd30
allocation.oversendLayer shouldBe null
allocation.layers.map { it.layer } shouldBe listOf(ld7_5, ld15, ld30, sd30, hd30)
}
context("With constraints") {
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(360), false, diagnosticContext, clock
)
// We include all resolutions up to the preferred resolution, and only high-FPS (at least
// "preferred FPS") layers for higher resolutions.
allocation.preferredLayer shouldBe sd30
allocation.oversendLayer shouldBe null
allocation.layers.map { it.layer } shouldBe listOf(ld7_5, ld15, ld30, sd30)
}
context("With constraints unmet by any layer") {
// Single high-res stream with 3 temporal layers.
val endpointId = "A"
val mediaSource = MediaSourceDesc(
// No simulcast.
arrayOf(RtpEncodingDesc(1L, arrayOf(hd7_5, hd15, hd30))),
sourceName = sourceName,
owner = owner,
videoType = VideoType.CAMERA
)
context("Non-zero constraints") {
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(360), false, diagnosticContext, clock
)
// The receiver set 360p constraints, but we only have a 720p stream.
allocation.preferredLayer shouldBe hd30
allocation.oversendLayer shouldBe null
allocation.layers.map { it.layer } shouldBe listOf(hd7_5, hd15, hd30)
}
context("Zero constraints") {
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(0), false, diagnosticContext, clock
)
// The receiver set a maxHeight=0 constraint.
allocation.preferredLayer shouldBe null
allocation.oversendLayer shouldBe null
allocation.layers.map { it.layer } shouldBe emptyList()
}
}
}
context("When some layers are inactive") {
// Override layers with bitrate=0. Simulate only up to 360p/15 being active.
val sd30 = MockRtpLayerDesc(tid = 2, eid = 1, height = 360, frameRate = 30.0, bitrate = 0.bps)
val hd7_5 = MockRtpLayerDesc(tid = 0, eid = 2, height = 720, frameRate = 7.5, bitrate = 0.bps)
val hd15 = MockRtpLayerDesc(tid = 1, eid = 2, height = 720, frameRate = 15.0, bitrate = 0.bps)
val hd30 = MockRtpLayerDesc(tid = 2, eid = 2, height = 720, frameRate = 30.0, bitrate = 0.bps)
val endpointId = "A"
val mediaSource = MediaSourceDesc(
arrayOf(
RtpEncodingDesc(1L, arrayOf(ld7_5, ld15, ld30)),
RtpEncodingDesc(1L, arrayOf(sd7_5, sd15, sd30)),
RtpEncodingDesc(1L, arrayOf(hd7_5, hd15, hd30))
),
sourceName = sourceName,
owner = owner,
videoType = VideoType.CAMERA
)
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(720), false, diagnosticContext, clock
)
// We include all resolutions up to the preferred resolution, and only high-FPS (at least
// "preferred FPS") layers for higher resolutions.
allocation.preferredLayer shouldBe ld30
allocation.oversendLayer shouldBe null
allocation.layers.map { it.layer } shouldBe listOf(ld7_5, ld15, ld30)
}
}
context("Screensharing") {
context("When all layers are active") {
val endpointId = "A"
val mediaSource = MediaSourceDesc(
arrayOf(
RtpEncodingDesc(1L, arrayOf(ld7_5, ld15, ld30)),
RtpEncodingDesc(1L, arrayOf(sd7_5, sd15, sd30)),
RtpEncodingDesc(1L, arrayOf(hd7_5, hd15, hd30))
),
sourceName = sourceName,
owner = owner,
videoType = VideoType.DESKTOP
)
context("With no constraints") {
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(720), true, diagnosticContext, clock
)
// For screensharing the "preferred" layer should be the highest -- always prioritized over other
// endpoints.
allocation.preferredLayer shouldBe hd30
allocation.oversendLayer shouldBe hd7_5
allocation.layers.map { it.layer } shouldBe
listOf(ld7_5, ld15, ld30, sd7_5, sd15, sd30, hd7_5, hd15, hd30)
}
context("With 360p constraints") {
val allocation =
SingleSourceAllocation(
endpointId, mediaSource, VideoConstraints(360), true, diagnosticContext, clock
)
allocation.preferredLayer shouldBe sd30
allocation.oversendLayer shouldBe sd7_5
allocation.layers.map { it.layer } shouldBe listOf(ld7_5, ld15, ld30, sd7_5, sd15, sd30)
}
}
context("The high layers are inactive (send-side bwe restrictions)") {
// Override layers with bitrate=0. Simulate only up to 360p/30 being active.
val hd7_5 = MockRtpLayerDesc(tid = 0, eid = 2, height = 720, frameRate = 7.5, bitrate = 0.bps)
val hd15 = MockRtpLayerDesc(tid = 1, eid = 2, height = 720, frameRate = 15.0, bitrate = 0.bps)
val hd30 = MockRtpLayerDesc(tid = 2, eid = 2, height = 720, frameRate = 30.0, bitrate = 0.bps)
val mediaSource = MediaSourceDesc(
arrayOf(
RtpEncodingDesc(1L, arrayOf(ld7_5, ld15, ld30)),
RtpEncodingDesc(1L, arrayOf(sd7_5, sd15, sd30)),
RtpEncodingDesc(1L, arrayOf(hd7_5, hd15, hd30))
),
sourceName = sourceName,
owner = owner,
videoType = VideoType.DESKTOP
)
val allocation =
SingleSourceAllocation(
"A", mediaSource, VideoConstraints(720), true, diagnosticContext, clock
)
// For screensharing the "preferred" layer should be the highest -- always prioritized over other
// endpoints.
allocation.preferredLayer shouldBe sd30
allocation.oversendLayer shouldBe sd7_5
allocation.layers.map { it.layer } shouldBe listOf(ld7_5, ld15, ld30, sd7_5, sd15, sd30)
}
context("The low layers are inactive (simulcast signaled but not used)") {
// Override layers with bitrate=0. Simulate simulcast being signaled but effectively disabled.
val ld7_5 = MockRtpLayerDesc(tid = 0, eid = 2, height = 720, frameRate = 7.5, bitrate = 0.bps)
val ld15 = MockRtpLayerDesc(tid = 1, eid = 2, height = 720, frameRate = 15.0, bitrate = 0.bps)
val ld30 = MockRtpLayerDesc(tid = 2, eid = 2, height = 720, frameRate = 30.0, bitrate = 0.bps)
val sd7_5 = MockRtpLayerDesc(tid = 0, eid = 1, height = 360, frameRate = 7.5, bitrate = 0.bps)
val sd15 = MockRtpLayerDesc(tid = 1, eid = 1, height = 360, frameRate = 15.0, bitrate = 0.bps)
val sd30 = MockRtpLayerDesc(tid = 2, eid = 1, height = 360, frameRate = 30.0, bitrate = 0.bps)
val mediaSource = MediaSourceDesc(
arrayOf(
RtpEncodingDesc(1L, arrayOf(ld7_5, ld15, ld30)),
RtpEncodingDesc(1L, arrayOf(sd7_5, sd15, sd30)),
RtpEncodingDesc(1L, arrayOf(hd7_5, hd15, hd30))
),
sourceName = sourceName,
owner = owner,
videoType = VideoType.DESKTOP
)
context("With no constraints") {
val allocation =
SingleSourceAllocation(
"A", mediaSource, VideoConstraints(720), true, diagnosticContext, clock
)
// For screensharing the "preferred" layer should be the highest -- always prioritized over other
// endpoints.
allocation.preferredLayer shouldBe hd30
allocation.oversendLayer shouldBe hd7_5
allocation.layers.map { it.layer } shouldBe listOf(hd7_5, hd15, hd30)
}
context("With 180p constraints") {
val allocation =
SingleSourceAllocation(
"A", mediaSource, VideoConstraints(180), true, diagnosticContext, clock
)
// For screensharing the "preferred" layer should be the highest -- always prioritized over other
// endpoints. Since no layers satisfy the resolution constraints, we consider layers from the
// lowest available resolution (which is high).
allocation.preferredLayer shouldBe hd30
allocation.oversendLayer shouldBe hd7_5
allocation.layers.map { it.layer } shouldBe listOf(hd7_5, hd15, hd30)
}
}
context("VP9") {
val l1 = MockRtpLayerDesc(tid = 0, eid = 0, sid = 0, height = 720, frameRate = -1.0, bitrate = 150.kbps)
val l2 = MockRtpLayerDesc(tid = 0, eid = 0, sid = 1, height = 720, frameRate = -1.0, bitrate = 370.kbps)
val l3 = MockRtpLayerDesc(tid = 0, eid = 0, sid = 2, height = 720, frameRate = -1.0, bitrate = 750.kbps)
val mediaSource = MediaSourceDesc(
arrayOf(
RtpEncodingDesc(1L, arrayOf(l1)),
RtpEncodingDesc(1L, arrayOf(l2)),
RtpEncodingDesc(1L, arrayOf(l3))
),
sourceName = sourceName,
owner = owner,
videoType = VideoType.DESKTOP
)
context("With no constraints") {
val allocation =
SingleSourceAllocation(
"A", mediaSource, VideoConstraints(720), true, diagnosticContext, clock
)
allocation.preferredLayer shouldBe l3
allocation.oversendLayer shouldBe l1
allocation.layers.map { it.layer } shouldBe listOf(l1, l2, l3)
}
context("With 180p constraints") {
// For screensharing the "preferred" layer should be the highest -- always prioritized over other
// endpoints. Since no layers satisfy the resolution constraints, we consider layers from the
// lowest available resolution (which is high). If we are off-stage we only consider the first of
// these layers.
context("On stage") {
val allocation = SingleSourceAllocation(
"A", mediaSource, VideoConstraints(180), true, diagnosticContext, clock
)
allocation.preferredLayer shouldBe l3
allocation.oversendLayer shouldBe l1
allocation.layers.map { it.layer } shouldBe listOf(l1, l2, l3)
}
context("Off stage") {
val allocation = SingleSourceAllocation(
"A", mediaSource, VideoConstraints(180), false, diagnosticContext, clock
)
allocation.preferredLayer shouldBe l1
allocation.oversendLayer shouldBe null
allocation.layers.map { it.layer } shouldBe listOf(l1)
}
}
}
}
}
}
private val sourceName = "sourceName"
private val owner = "owner"
| apache-2.0 | 0e51dc1c2851443aa5a51cd84790cacf | 51.221875 | 120 | 0.531087 | 5.019826 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/contact/Email.kt | 1 | 1761 | package mil.nga.giat.mage.contact
import android.net.Uri
class Email private constructor(
private val emailAddress: String,
message: String,
username: String?,
authenticationStrategy: String?,
) {
private val subject: String = if (message.contains("device", ignoreCase = true)) {
if (message.contains("register")) {
"Please approve my device"
} else {
"Device ID issue"
}
} else {
if (message.contains("approved", true) || message.contains("activate", true)) {
"Please activate my MAGE account"
} else if (message.contains("disabled",true)) {
"Please Enable My MAGE Account"
} else if (message.contains("locked", true)) {
"Please Unlock My MAGE Account"
} else {
"User Sign-in Issue"
}
}
private val body: String =
listOf(
username?.let { "username:\n$it\n\n" } ?: "",
authenticationStrategy?.let { "Authentication Strategy:\n$it\n\n" } ?: "",
"Message:\n$message").joinToString("")
fun uri(): Uri {
return Uri.Builder()
.scheme("mailto")
.opaquePart(emailAddress)
.appendQueryParameter("subject", subject)
.appendQueryParameter("body", body)
.build()
}
data class Builder(
val emailAddress: String,
val message: String
) {
private var username: String? = null
private var authenticationStrategy: String? = null
fun username(username: String?) = apply { this.username = username }
fun authenticationStrategy(authenticationStrategy: String?) = apply { this.authenticationStrategy = authenticationStrategy }
fun build() = Email(emailAddress, message, username, authenticationStrategy)
}
} | apache-2.0 | a72b807f67546c75fb83354c06de80e3 | 30.464286 | 130 | 0.622942 | 4.413534 | false | false | false | false |
JetBrains/resharper-unity | rider/src/test/kotlin/base/integrationTests/UnityTestEnvironment.kt | 1 | 1237 | package base.integrationTests
import com.jetbrains.rider.test.framework.TestMethod
@Target(AnnotationTarget.FUNCTION)
annotation class UnityTestEnvironment(
val withCoverage: Boolean = false,
val resetEditorPrefs: Boolean = false,
val useRiderTestPath: Boolean = false,
val batchMode: Boolean = true
)
class UnityTestEnvironmentInstance(
val withCoverage: Boolean = false,
val resetEditorPrefs: Boolean = false,
val useRiderTestPath: Boolean = false,
val batchMode: Boolean = true
) {
companion object {
fun getFromAnnotation(unityTestEnvironment: UnityTestEnvironment?): UnityTestEnvironmentInstance? {
if (unityTestEnvironment == null) {
return null
}
return UnityTestEnvironmentInstance(
unityTestEnvironment.withCoverage,
unityTestEnvironment.resetEditorPrefs,
unityTestEnvironment.useRiderTestPath,
unityTestEnvironment.batchMode
)
}
}
}
val TestMethod.unityEnvironment: UnityTestEnvironmentInstance?
get() = UnityTestEnvironmentInstance.getFromAnnotation(
method.annotations.filterIsInstance<UnityTestEnvironment>().firstOrNull()) | apache-2.0 | b109f9b7135c431be6a8e436bf771628 | 32.459459 | 107 | 0.703314 | 5.473451 | false | true | false | false |
thermatk/FastHub-Libre | app/src/main/java/com/fastaccess/ui/modules/editor/EditorActivity.kt | 1 | 8788 | package com.fastaccess.ui.modules.editor
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.annotation.StringRes
import android.support.transition.TransitionManager
import android.support.v4.app.FragmentManager
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.View.GONE
import android.view.ViewGroup
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.ListView
import butterknife.BindView
import butterknife.OnClick
import com.evernote.android.state.State
import com.fastaccess.R
import com.fastaccess.data.dao.EditReviewCommentModel
import com.fastaccess.data.dao.model.Comment
import com.fastaccess.helper.*
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.provider.markdown.MarkDownProvider
import com.fastaccess.ui.base.BaseActivity
import com.fastaccess.ui.widgets.FontTextView
import com.fastaccess.ui.widgets.dialog.MessageDialogView
import com.fastaccess.ui.widgets.markdown.MarkDownLayout
import com.fastaccess.ui.widgets.markdown.MarkdownEditText
import java.util.*
/**
* Created by Kosh on 27 Nov 2016, 1:32 AM
*/
class EditorActivity : BaseActivity<EditorMvp.View, EditorPresenter>(), EditorMvp.View {
private var participants: ArrayList<String>? = null
private val sentFromFastHub: String by lazy {
"\n\n_" + getString(R.string.sent_from_fasthub, AppHelper.getDeviceName(), "",
"[" + getString(R.string.app_name) + "](https://github.com/thermatk/FastHub-Libre/)") + "_"
}
@BindView(R.id.replyQuote) lateinit var replyQuote: LinearLayout
@BindView(R.id.replyQuoteText) lateinit var quote: FontTextView
@BindView(R.id.markDownLayout) lateinit var markDownLayout: MarkDownLayout
@BindView(R.id.editText) lateinit var editText: MarkdownEditText
@BindView(R.id.list_divider) lateinit var listDivider: View
@BindView(R.id.parentView) lateinit var parentView: View
@BindView(R.id.autocomplete) lateinit var mention: ListView
@State @BundleConstant.ExtraType var extraType: String? = null
@State var itemId: String? = null
@State var login: String? = null
@State var issueNumber: Int = 0
@State var commentId: Long = 0
@State var sha: String? = null
@State var reviewComment: EditReviewCommentModel? = null
override fun layout(): Int = R.layout.editor_layout
override fun isTransparent(): Boolean = false
override fun canBack(): Boolean = true
override fun isSecured(): Boolean = false
override fun providePresenter(): EditorPresenter = EditorPresenter()
@OnClick(R.id.replyQuoteText) internal fun onToggleQuote() {
TransitionManager.beginDelayedTransition((parentView as ViewGroup))
if (quote.maxLines == 3) {
quote.maxLines = Integer.MAX_VALUE
} else {
quote.maxLines = 3
}
quote.setCompoundDrawablesWithIntrinsicBounds(0, 0,
if (quote.maxLines == 3) R.drawable.ic_arrow_drop_down
else R.drawable.ic_arrow_drop_up, 0)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
markDownLayout.markdownListener = this
setToolbarIcon(R.drawable.ic_clear)
if (savedInstanceState == null) {
onCreate()
}
invalidateOptionsMenu()
editText.initListView(mention, listDivider, participants)
editText.requestFocus()
}
override fun onSendResultAndFinish(commentModel: Comment, isNew: Boolean) {
hideProgress()
val intent = Intent()
intent.putExtras(Bundler.start()
.put(BundleConstant.ITEM, commentModel)
.put(BundleConstant.EXTRA, isNew)
.end())
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onSendMarkDownResult() {
val intent = Intent()
intent.putExtras(Bundler.start().put(BundleConstant.EXTRA, editText.savedText).end())
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onSendReviewResultAndFinish(comment: EditReviewCommentModel, isNew: Boolean) {
hideProgress()
val intent = Intent()
intent.putExtras(Bundler.start()
.put(BundleConstant.ITEM, comment)
.put(BundleConstant.EXTRA, isNew)
.end())
setResult(Activity.RESULT_OK, intent)
finish()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.done_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.submit) {
if (PrefGetter.isSentViaEnabled()) {
val temp = editText.savedText.toString()
if (!temp.contains(sentFromFastHub)) {
editText.savedText = editText.savedText.toString() + sentFromFastHub
}
}
presenter.onHandleSubmission(editText.savedText, extraType, itemId, commentId, login, issueNumber, sha, reviewComment)
return true
}
return super.onOptionsItemSelected(item)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
if (menu.findItem(R.id.submit) != null) {
menu.findItem(R.id.submit).isEnabled = true
}
if (BundleConstant.ExtraType.FOR_RESULT_EXTRA.equals(extraType, ignoreCase = true)) {
menu.findItem(R.id.submit).setIcon(R.drawable.ic_done)
}
return super.onPrepareOptionsMenu(menu)
}
override fun showProgress(@StringRes resId: Int) {
super.showProgress(resId)
invalidateOptionsMenu()
}
override fun hideProgress() {
invalidateOptionsMenu()
super.hideProgress()
}
override fun onBackPressed() {
if (!InputHelper.isEmpty(editText)) {
ViewHelper.hideKeyboard(editText)
MessageDialogView.newInstance(getString(R.string.close), getString(R.string.unsaved_data_warning),
Bundler.start()
.put("primary_extra", getString(R.string.discard))
.put("secondary_extra", getString(R.string.cancel))
.put(BundleConstant.EXTRA, true)
.end())
.show(supportFragmentManager, MessageDialogView.TAG)
return
}
super.onBackPressed()
}
override fun onMessageDialogActionClicked(isOk: Boolean, bundle: Bundle?) {
super.onMessageDialogActionClicked(isOk, bundle)
if (isOk && bundle != null) {
finish()
}
}
override fun onAppendLink(title: String?, link: String?, isLink: Boolean) {
markDownLayout.onAppendLink(title, link, isLink)
}
override fun getEditText(): EditText = editText
override fun getSavedText(): CharSequence? = editText.savedText
override fun fragmentManager(): FragmentManager = supportFragmentManager
@SuppressLint("SetTextI18n")
override fun onEmojiAdded(emoji: Emoji?) {
markDownLayout.onEmojiAdded(emoji)
}
private fun onCreate() {
val intent = intent
if (intent != null && intent.extras != null) {
val bundle = intent.extras
extraType = bundle.getString(BundleConstant.EXTRA_TYPE)
reviewComment = bundle.getParcelable(BundleConstant.REVIEW_EXTRA)
itemId = bundle.getString(BundleConstant.ID)
login = bundle.getString(BundleConstant.EXTRA_TWO)
if (extraType.equals(BundleConstant.ExtraType.EDIT_COMMIT_COMMENT_EXTRA, ignoreCase = true)
|| extraType.equals(BundleConstant.ExtraType.NEW_COMMIT_COMMENT_EXTRA, ignoreCase = true)) {
sha = bundle.getString(BundleConstant.EXTRA_THREE)
} else {
issueNumber = bundle.getInt(BundleConstant.EXTRA_THREE)
}
commentId = bundle.getLong(BundleConstant.EXTRA_FOUR)
val textToUpdate = bundle.getString(BundleConstant.EXTRA)
if (!InputHelper.isEmpty(textToUpdate)) {
editText.setText(String.format("%s ", textToUpdate))
editText.setSelection(InputHelper.toString(editText).length)
}
if (bundle.getString("message", "").isBlank()) {
replyQuote.visibility = GONE
} else {
MarkDownProvider.setMdText(quote, bundle.getString("message", ""))
}
participants = bundle.getStringArrayList("participants")
}
}
} | gpl-3.0 | dfb8bcff145ca83c302fba7549262e97 | 37.213043 | 130 | 0.659763 | 4.714592 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/cleanup/src/main/kotlin/org/gradle/gradlebuild/testing/integrationtests/cleanup/Process.kt | 1 | 3664 | /*
* Copyright 2017 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.
*/
// To make it easier to access these functions from Groovy
@file:JvmName("Process")
package org.gradle.gradlebuild.testing.integrationtests.cleanup
import org.gradle.api.Project
import org.gradle.gradlebuild.BuildEnvironment
import org.gradle.testing.LeakingProcessKillPattern
import java.io.ByteArrayOutputStream
fun Project.pkill(pid: String) {
val killOutput = ByteArrayOutputStream()
val result = exec {
commandLine =
if (BuildEnvironment.isWindows) {
listOf("taskkill.exe", "/F", "/T", "/PID", pid)
} else {
listOf("kill", "-9", pid)
}
standardOutput = killOutput
errorOutput = killOutput
isIgnoreExitValue = true
}
if (result.exitValue != 0) {
val out = killOutput.toString()
if (!out.contains("No such process")) {
logger.warn(
"""Failed to kill daemon process $pid. Maybe already killed?
Output: $killOutput
""")
}
}
}
data class ProcessInfo(val pid: String, val process: String)
fun Project.forEachLeakingJavaProcess(action: ProcessInfo.() -> Unit) {
val output = ByteArrayOutputStream()
val error = ByteArrayOutputStream()
val (result, pidPattern) =
if (BuildEnvironment.isWindows) {
exec {
commandLine("wmic", "process", "get", "processid,commandline")
standardOutput = output
errorOutput = error
isIgnoreExitValue = true
} to "([0-9]+)\\s*$".toRegex()
} else {
exec {
commandLine("ps", "x")
standardOutput = output
errorOutput = output
isIgnoreExitValue = true
} to "([0-9]+)".toRegex()
}
if (result.exitValue != 0) {
val errorLog = file("${rootProject.buildDir}/errorLogs/process-list-${System.currentTimeMillis()}.log")
mkdir(errorLog.parent)
errorLog.writeText("[Output]\n$output\n[Error Output]\n$error")
logger.quiet("Error obtaining process list, output log created at $errorLog")
result.assertNormalExitValue()
}
val processPattern = generateLeakingProcessKillPattern()
forEachLineIn(output.toString()) { line ->
val processMatcher = processPattern.find(line)
if (processMatcher != null) {
val pidMatcher = pidPattern.find(line)
if (pidMatcher != null) {
val pid = pidMatcher.groupValues[1]
val process = processMatcher.groupValues[1]
if (!isMe(process)) {
action(ProcessInfo(pid, process))
}
}
}
}
}
fun Project.generateLeakingProcessKillPattern() =
LeakingProcessKillPattern.generate(rootProject.projectDir.absolutePath).toRegex()
inline
fun forEachLineIn(s: String, action: (String) -> Unit) =
s.lineSequence().forEach(action)
fun Project.isMe(process: String) =
process.contains(gradle.gradleHomeDir!!.path)
| apache-2.0 | cf3bab499003ccbe3b91b9e66c746352 | 32.009009 | 111 | 0.626638 | 4.495706 | false | false | false | false |
kysersozelee/KotlinStudy | JsonParser/bin/JsonObject.kt | 1 | 1872 | class JsonObject : JsonValue() {
var names: MutableList<String> = mutableListOf()
var values: MutableList<JsonValue> = mutableListOf()
override fun write(writer: JsonWriter): String {
writer.writeObjectOpen()
var namesIterator = this.names.iterator()
var valuesIterator = this.values.iterator()
if (namesIterator.hasNext()) {
writer.writeMemberName(namesIterator.next())
writer.writeMemberSeparator()
valuesIterator.next().write(writer)
while (namesIterator.hasNext()) {
writer.writeObjectSeparator()
writer.writeMemberName(namesIterator.next())
writer.writeMemberSeparator()
valuesIterator.next().write(writer)
}
}
writer.writeObjectClose()
return writer.string
}
fun add(name: String, value: Any?): JsonObject {
this.names.add(name)
if (value is Int || value is Float || value is Double) {
this.values.add(JsonNumber(value))
} else if (null == value) {
this.values.add(JsonString(value))
} else if (value is String) {
this.values.add(JsonString(value.toString()))
} else if (value is JsonObject) {
this.values.add(value)
} else if (value is Boolean) {
this.values.add(JsonLiteral(value))
} else if (value is JsonArray) {
this.values.add(JsonArray(value))
} else {
throw Exception("Invalid type of value")
}
return this
}
override fun asObject(): JsonObject {
return this
}
override fun equals(other: Any?): Boolean {
if (null == other || other !is JsonObject) return false
return this.names.equals(other) && this.values.equals(other)
}
fun get(name: String): JsonValue? {
return getValue(name)
}
fun getValue(name: String): JsonValue? {
var idx: Int = 0
for (item: String in names) {
if (name.equals(item)) {
return values.get(idx)
}
idx++
}
return null
}
} | bsd-2-clause | 236988943374237d9a2a79cb5571db09 | 23.671233 | 62 | 0.659722 | 3.216495 | false | false | false | false |
sharaquss/todo | app/src/main/java/com/android/szparag/todoist/models/implementations/TodoistFrontModel.kt | 1 | 4384 | package com.android.szparag.todoist.models.implementations
import com.android.szparag.todoist.models.contracts.FrontModel
import com.android.szparag.todoist.models.entities.RenderDay
import com.android.szparag.todoist.models.entities.TodoistDay
import com.android.szparag.todoist.utils.Logger
import com.android.szparag.todoist.utils.ReactiveList
import com.android.szparag.todoist.utils.ReactiveListEvent
import com.android.szparag.todoist.utils.ReactiveMutableList
import com.android.szparag.todoist.utils.dayUnixTimestamp
import com.android.szparag.todoist.utils.range
import com.android.szparag.todoist.utils.toRenderDay
import com.android.szparag.todoist.utils.weekAsDays
import io.reactivex.BackpressureStrategy.ERROR
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Observable
import io.realm.Realm
import org.joda.time.LocalDate
import java.util.Locale
import java.util.Random
import javax.inject.Inject
private const val WEEKDAYS_COUNT = 7
private const val INITIAL_DAYS_CAPACITY = WEEKDAYS_COUNT * 8
//todo: locale is useless here
//todo: or is it not?
//todo: make constructor injection
class TodoistFrontModel @Inject constructor(private var locale: Locale, private val random: Random, private val realm: Realm) : FrontModel {
override val logger by lazy { Logger.create(this::class.java, this.hashCode()) }
private lateinit var currentDay: LocalDate
private val datesList: ReactiveList<LocalDate> = ReactiveMutableList(INITIAL_DAYS_CAPACITY, true)
override fun attach(): Completable {
logger.debug("attach")
return Completable.fromAction {
setupCalendarInstance()
logger.debug("attach.action.finished") //todo refactor
}
}
override fun detach(): Completable = Completable.fromAction {
logger.debug("detach")
realm.close()
}
private fun setupCalendarInstance() {
logger.debug("setupCalendarInstance")
currentDay = LocalDate()
}
override fun fetchInitialCalendarData(weekFetchMultiplier: Int) {
logger.debug("fetchInitialCalendarData")
if (datesList.size == 0) {
loadDaysFromCalendar(true, 2 * weekFetchMultiplier)
loadDaysFromCalendar(false, 2)
}
}
override fun loadDaysFromCalendar(weekForward: Boolean, weeksCount: Int) {
logger.debug("loadDaysFromCalendar, weekForward: $weekForward, weeksCount: $weeksCount")
val boundaryLocalDate = if (datesList.size == 0) {
currentDay
} else {
datesList.boundary(weekForward)
}
val appendingLocalDates = mutableListOf<LocalDate>()
range(0, weeksCount - 2).forEach { weekIndex ->
//todo range 0 fetch-2 is little ambiguous, make it more readable
if (weekForward)
appendingLocalDates.addAll(boundaryLocalDate.plusWeeks(weekIndex).plusDays(1).weekAsDays())
else
appendingLocalDates.addAll(boundaryLocalDate.minusWeeks(weekIndex + 1).weekAsDays())
}.also {
if (weekForward) {
datesList.insert(appendingLocalDates)
} else {
datesList.insert(0, appendingLocalDates)
}
logger.debug("loadDaysFromCalendar, appendingLocalDates: $appendingLocalDates, datesList: $datesList")
}
}
override fun getDay(unixTimestamp: Long): TodoistDay? {
logger.debug("getDay, unixTimestamp: $unixTimestamp")
return realm.where(TodoistDay::class.java).equalTo("unixTimestamp", unixTimestamp).findFirst()
}
override fun subscribeForDaysList(): Flowable<ReactiveListEvent<RenderDay>> {
logger.debug("subscribeForDaysList")
return subscribeForDaysListEvents()
.map { it -> ReactiveListEvent(
it.eventType,
it.affectedItems.map {
it.toRenderDay(
locale = locale,
tasksList = getDay(it.dayUnixTimestamp())?.tasks?.map { it.name } ?: emptyList(),
tasksCompletedCount = -1, //todo
tasksRemainingCount = -1
)
},
it.fromIndexInclusive
) }
.toFlowable(ERROR)
}
override fun subscribeForDaysListEvents(): Observable<ReactiveListEvent<LocalDate>> {
logger.debug("subscribeForDaysListEvents")
return datesList.subscribeForListEvents()
}
override fun subscribeForDaysListData(): Observable<ReactiveList<LocalDate>> {
logger.debug("subscribeForDaysListData")
return datesList.subscribeForListData()
}
} | mit | b6797169505c2d404d5cb69d9800af38 | 35.541667 | 140 | 0.729015 | 4.248062 | false | false | false | false |
google/horologist | sample/src/main/java/com/google/android/horologist/auth/oauth/devicegrant/AuthDeviceGrantSampleScreen.kt | 1 | 2419 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.auth.oauth.devicegrant
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.android.horologist.auth.composables.dialog.SignedInConfirmationDialog
import com.google.android.horologist.auth.composables.screens.AuthErrorScreen
import com.google.android.horologist.auth.ui.oauth.devicegrant.AuthDeviceGrantScreen
import com.google.android.horologist.auth.ui.oauth.devicegrant.AuthDeviceGrantScreenState
@Composable
fun AuthDeviceGrantSampleScreen(
onAuthSuccess: () -> Unit,
modifier: Modifier = Modifier,
viewModel: AuthDeviceGrantSampleViewModel = viewModel(factory = AuthDeviceGrantSampleViewModel.Factory)
) {
val state by viewModel.uiState.collectAsStateWithLifecycle()
when (state) {
AuthDeviceGrantScreenState.Idle,
AuthDeviceGrantScreenState.Loading,
is AuthDeviceGrantScreenState.CheckPhone -> {
AuthDeviceGrantScreen(viewModel = viewModel)
}
AuthDeviceGrantScreenState.Failed -> {
AuthErrorScreen(modifier)
}
AuthDeviceGrantScreenState.Success -> {
var showDialog by rememberSaveable { mutableStateOf(true) }
SignedInConfirmationDialog(
showDialog = showDialog,
onDismissOrTimeout = {
showDialog = false
onAuthSuccess()
},
modifier = modifier
)
}
}
}
| apache-2.0 | 5862cd460ef65ff5b6c5ab649d804c59 | 36.215385 | 107 | 0.732947 | 4.818725 | false | false | false | false |
jdinkla/groovy-java-ray-tracer | src/main/kotlin/net/dinkla/raytracer/objects/utilities/PlyFile.kt | 1 | 2816 | package net.dinkla.raytracer.objects.utilities
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.io.FileReader
class PlyFile(val filename: String) {
var numVertices: Int = 0
var vertexProperties: Map<String, String> = hashMapOf()
var numFaces: Int = 0
var facesProperties: List<String> = listOf()
var format: String = ""
var formatVersion: String = ""
var vertexDataLength: Int? = null
var headerLength = 0
init {
readHeader()
}
fun readHeader() {
LOGGER.info("PLY: reading file '${filename}'")
var isInHeader = true
var isInVertexDef = false
var isInFaceDef = false
var numLine = 0
val br = BufferedReader(FileReader(filename));
assert(br.markSupported())
var line: String;
var isAtEndOfFile = true
while (!isAtEndOfFile && isInHeader) {
line = br.readLine()
isAtEndOfFile = line == null
if (isAtEndOfFile) break
headerLength += line.length + 1
numLine++
// if (line =~ /end_header/) {
// isInHeader = false
// } else if ("""^element\W+vertex""".toRegex().containsMatchIn(line) ) {
// line = line.replaceFirst(/element\W+vertex\W+/, '')
// numVertices = Integer.valueOf(line)
// isInVertexDef = true
// isInFaceDef = false
// LOGGER.info("PLY: ${numVertices} vertices")
// } else if (line =~ /^element\W+face/) {
// line = line.replaceFirst(/element\W+face\W+/, '')
// numFaces = Integer.valueOf(line)
// isInVertexDef = false
// isInFaceDef = true
// LOGGER.info("PLY: ${numFaces} faces")
// } else if (line =~ /^property/) {
// line = line.replaceFirst(/property\W+/, '')
// if (isInVertexDef) {
// def parts = line.split(/ /)
// assert parts.size() == 2
// vertexProperties.put(parts[1], PlyType.map.get(parts[0]))
// } else if (isInFaceDef) {
// facesProperties.add(line)
// } else {
// throw new RuntimeException("Unknown error in PLY file")
// }
// } else if (line =~ /^format/) {
// line = line.replaceFirst(/format\W+/, '')
// def parts = line.split(/ /)
// assert parts.size() == 2
// format = parts[0]
// formatVersion = parts[1]
// }
}
br.close();
}
fun read() {
}
companion object {
internal val LOGGER = LoggerFactory.getLogger(this::class.java)
}
} | apache-2.0 | 5fffab00898eb627bc6b6af69a0af9a4 | 32.939759 | 84 | 0.506037 | 4.159527 | false | false | false | false |
tmarsteel/compiler-fiddle | src/compiler/parser/grammar/dsl/eitherof.kt | 1 | 3306 | /*
* Copyright 2018 Tobias Marstaller
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package compiler.parser.grammar.dsl
import compiler.InternalCompilerError
import compiler.lexer.TokenType
import compiler.matching.ResultCertainty
import compiler.parser.TokenSequence
import compiler.parser.rule.RuleMatchingResult
import compiler.parser.rule.RuleMatchingResultImpl
import compiler.reportings.Reporting
import textutils.indentByFromSecondLine
internal fun tryMatchEitherOf(matcherFn: Grammar, input: TokenSequence, mismatchCertainty: ResultCertainty): RuleMatchingResult<*> {
input.mark()
try {
(object : BaseMatchingGrammarReceiver(input) {
override fun handleResult(result: RuleMatchingResult<*>) {
if (result.certainty >= ResultCertainty.MATCHED) {
throw SuccessfulMatchException(result)
}
}
}).matcherFn()
input.rollback()
return RuleMatchingResultImpl(
mismatchCertainty,
null,
setOf(
Reporting.parsingError(
"Unexpected ${input.peek()?.toStringWithoutLocation() ?: "end of input"}, expected ${describeEitherOfGrammar(matcherFn)}",
input.currentSourceLocation
)
)
)
}
catch (ex: SuccessfulMatchException) {
if (ex.result.item == null) {
input.rollback()
// TODO: FALLBACK!
}
else {
input.commit()
}
return ex.result
}
catch (ex: MatchingAbortedException) {
throw InternalCompilerError("How the heck did that happen?", ex)
}
}
internal fun describeEitherOfGrammar(grammar: Grammar): String {
val receiver = DescribingEitherOfGrammarReceiver()
receiver.grammar()
return receiver.collectedDescription
}
private class DescribingEitherOfGrammarReceiver : BaseDescribingGrammarReceiver() {
private val buffer = StringBuilder(50)
init {
buffer.append("one of:\n")
}
override fun handleItem(descriptionOfItem: String) {
buffer.append("- ")
buffer.append(descriptionOfItem.indentByFromSecondLine(2))
buffer.append("\n")
}
val collectedDescription: String
get() = buffer.toString()
override fun tokenOfType(type: TokenType) {
handleItem(type.name)
}
}
private class SuccessfulMatchException(result: RuleMatchingResult<*>) : MatchingAbortedException(result, "A rule was sucessfully matched; Throwing this exception because other rules dont need to be attempted.") | lgpl-3.0 | 50031e8c85d78899e11aedd63a616c53 | 33.092784 | 210 | 0.683001 | 4.812227 | false | false | false | false |
google/horologist | media-ui/src/main/java/com/google/android/horologist/media/ui/state/mapper/MediaUiModelMapper.kt | 1 | 1320 | /*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaApi::class)
package com.google.android.horologist.media.ui.state.mapper
import com.google.android.horologist.media.ExperimentalHorologistMediaApi
import com.google.android.horologist.media.model.Media
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import com.google.android.horologist.media.ui.state.model.MediaUiModel
/**
* Map a [Media] into a [MediaUiModel]
*/
@ExperimentalHorologistMediaUiApi
public object MediaUiModelMapper {
public fun map(media: Media): MediaUiModel = MediaUiModel(
id = media.id,
title = media.title,
artist = media.artist,
artworkUri = media.artworkUri
)
}
| apache-2.0 | 2fcc81425eb8107c882e64d7b8a79044 | 33.736842 | 78 | 0.756061 | 4.258065 | false | false | false | false |
Kiskae/Twitch-Archiver | ui/src/main/kotlin/net/serverpeon/twitcharchiver/fx/sections/VideoTable.kt | 1 | 8110 | package net.serverpeon.twitcharchiver.fx.sections
import javafx.beans.binding.Bindings
import javafx.beans.binding.When
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.event.EventHandler
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Group
import javafx.scene.Node
import javafx.scene.Scene
import javafx.scene.control.*
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.paint.Color
import javafx.scene.text.Text
import net.serverpeon.twitcharchiver.fx.*
import net.serverpeon.twitcharchiver.fx.merging.MergingDialog
import net.serverpeon.twitcharchiver.network.DownloadableVod
import net.serverpeon.twitcharchiver.twitch.api.KrakenApi
import net.serverpeon.twitcharchiver.twitch.playlist.Playlist
import java.text.DecimalFormat
import java.text.MessageFormat
import java.time.Instant
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.format.TextStyle
import java.time.temporal.ChronoField
import java.util.*
import kotlin.collections.filter
class VideoTable(val downloadControl: DownloadControl) : TableView<DownloadableVod>(), ChannelInput.VideoFeed {
private val videos: ObservableList<DownloadableVod> = FXCollections.observableArrayList()
override fun resetFeed() {
this.videos.clear()
}
override fun insertVideo(info: KrakenApi.VideoListResponse.Video, playlist: Playlist) {
this.videos.add(downloadControl.createVideo(info, playlist))
}
fun selectedVideos(): List<DownloadableVod> {
return videos.filter { it.shouldDownload.value }
}
init {
isEditable = true
column("D.", { shouldDownload }) {
editableProperty().bind(downloadControl.isDownloadingProp.not())
renderer(CheckBox::class) { previousNode, newValue ->
(previousNode ?: CheckBox().apply {
rowValue().shouldDownload.bind(selectedProperty())
}).apply {
isSelected = newValue
disableProperty().bind(Bindings.not(
tableView.editableProperty().and(
tableColumn.editableProperty())))
}
}
applyToCell {
alignment = Pos.CENTER
}
maxWidth = 3 * EM
tooltip { "Download this Video" }
}
column("Title", { title.toFxObservable() })
column("Length", { length.toFxObservable() }) {
textFormat { duration ->
val hours = duration.toHours()
val minutes = duration.minusHours(hours).toMinutes()
val seconds = duration.minusMinutes(duration.toMinutes()).seconds
DURATION_FORMATTER.get().format(arrayOf(hours, minutes, seconds))
}
}
column("Views", { views.toFxObservable() }) {
applyToCell {
alignment = Pos.CENTER_RIGHT
}
}
column("Approximate Size @ 2.5 Mbps", { approximateSize.toFxObservable() }) {
textFormat { size ->
if (size > BYTES_PER_MEGABYTE) {
"${size / BYTES_PER_MEGABYTE} MB"
} else if (size > BYTES_PER_KILOBYTE) {
//Kb
"${size / BYTES_PER_KILOBYTE} kB"
} else {
"$size B"
}
}
applyToCell {
alignment = Pos.CENTER_RIGHT
}
}
column("Recording Date", { recordedAt.toFxObservable() }) {
textFormat { moment -> INSTANT_FORMATTER.format(moment) }
}
column("TP", { parts.toFxObservable() }) {
tooltip { "Total parts" }
maxWidth = 4 * EM
applyToCell {
alignment = Pos.CENTER_RIGHT
}
}
column("DP", { downloadedParts }) {
tooltip { "Downloaded parts" }
maxWidth = 4 * EM
applyToCell {
alignment = Pos.CENTER_RIGHT
}
}
column("FP", { failedParts }) {
tooltip { "Failed to download parts" }
maxWidth = 4 * EM
applyToCell {
alignment = Pos.CENTER_RIGHT
}
}
column("Download Progress", { downloadProgress }) {
renderer(Node::class) { previousNode, progress ->
if (progress < 1) {
@Suppress("USELESS_CAST")
when (previousNode) {
is ProgressBar -> previousNode as ProgressBar
else -> ProgressBar()
}.apply {
this.progress = progress
}
} else {
@Suppress("USELESS_CAST")
when (previousNode) {
is Button -> previousNode as Button
else -> Button("Merge").apply {
padding = padding.let { oldPadding ->
Insets(0.0, 10.0, 0.0, 10.0)
}
onAction = EventHandler<javafx.event.ActionEvent> {
MergingDialog.show(tableView.items[tableRow.index].tracker.partFiles()!!)
}
}
}
}
}
applyToCell {
alignment = Pos.CENTER
}
}
column("MP", { mutedParts.toFxObservable() }) {
renderer(Label::class, { background = null }) { label, item ->
val bg = if (item > 0) Color.RED else Color.GREEN
background = Background(BackgroundFill(bg, null, Insets(1.0)))
label ?: Label(item.toString())
}
maxWidth = 4 * EM
applyToCell {
alignment = Pos.CENTER
}
tooltip { "Muted parts" }
}
val tableComparator = comparatorProperty()
val defaultComparator = Comparator.comparing<DownloadableVod, Instant> { it.recordedAt }.reversed()
this.items = videos.sorted().apply {
comparatorProperty().bind(
When(tableComparator.isNotNull)
.then(tableComparator)
.otherwise(defaultComparator)
)
}
}
companion object {
private val EM: Double = Text("m").let {
Scene(Group(it))
it.applyCss()
it.layoutBounds.width
}
private const val BYTES_PER_KILOBYTE = 1000
private const val BYTES_PER_MEGABYTE = BYTES_PER_KILOBYTE * 1000
private val DURATION_FORMATTER: ThreadLocal<MessageFormat> = object : ThreadLocal<MessageFormat>() {
override fun initialValue(): MessageFormat? {
return MessageFormat("{0}h{1}m{2}s").apply {
val formatter = DecimalFormat("00")
setFormatByArgumentIndex(1, formatter)
setFormatByArgumentIndex(2, formatter)
}
}
}
private val INSTANT_FORMATTER: DateTimeFormatter = DateTimeFormatterBuilder()
.appendValue(ChronoField.DAY_OF_MONTH)
.appendLiteral('-')
.appendText(ChronoField.MONTH_OF_YEAR, TextStyle.SHORT)
.appendLiteral('-')
.appendValue(ChronoField.YEAR)
.appendLiteral(' ')
.appendValue(ChronoField.HOUR_OF_DAY, 2)
.appendLiteral(':')
.appendValue(ChronoField.MINUTE_OF_HOUR, 2)
.appendLiteral(' ')
.appendZoneText(TextStyle.NARROW)
.toFormatter()
.withZone(ZoneId.ofOffset("UTC", ZoneOffset.UTC))
}
} | mit | 45aeaaae89cd7ddd0e8f22986a739532 | 33.079832 | 111 | 0.54291 | 5.103839 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/inspections/PyProtocolInspection.kt | 1 | 5647 | // 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.jetbrains.python.inspections
import com.intellij.codeInspection.LocalInspectionToolSession
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiNameIdentifierOwner
import com.intellij.util.containers.isNullOrEmpty
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.codeInsight.typing.inspectProtocolSubclass
import com.jetbrains.python.codeInsight.typing.isProtocol
import com.jetbrains.python.psi.PyCallExpression
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyKnownDecoratorUtil
import com.jetbrains.python.psi.PyKnownDecoratorUtil.KnownDecorator.TYPING_RUNTIME
import com.jetbrains.python.psi.PyTypedElement
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.resolve.RatedResolveResult
import com.jetbrains.python.psi.types.PyClassLikeType
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.PyTypeChecker
class PyProtocolInspection : PyInspection() {
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session)
private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
override fun visitPyClass(node: PyClass?) {
super.visitPyClass(node)
val type = node?.let { myTypeEvalContext.getType(it) } as? PyClassType ?: return
val superClassTypes = type.getSuperClassTypes(myTypeEvalContext)
checkCompatibility(type, superClassTypes)
checkProtocolBases(type, superClassTypes)
}
override fun visitPyCallExpression(node: PyCallExpression?) {
super.visitPyCallExpression(node)
if (node == null) return
checkRuntimeProtocolInIsInstance(node)
checkNewTypeWithProtocols(node)
}
private fun checkCompatibility(type: PyClassType, superClassTypes: List<PyClassLikeType?>) {
superClassTypes
.asSequence()
.filterIsInstance<PyClassType>()
.filter { isProtocol(it, myTypeEvalContext) }
.forEach { protocol ->
inspectProtocolSubclass(protocol, type, myTypeEvalContext).forEach {
val subclassElements = it.second
if (!subclassElements.isNullOrEmpty()) {
checkMemberCompatibility(it.first, subclassElements!!, type, protocol)
}
}
}
}
private fun checkProtocolBases(type: PyClassType, superClassTypes: List<PyClassLikeType?>) {
if (!isProtocol(type, myTypeEvalContext)) return
val correctBase: (PyClassLikeType?) -> Boolean = {
if (it == null) true
else {
val classQName = it.classQName
classQName == PyTypingTypeProvider.PROTOCOL ||
classQName == PyTypingTypeProvider.PROTOCOL_EXT ||
it is PyClassType && isProtocol(it, myTypeEvalContext)
}
}
if (!superClassTypes.all(correctBase)) {
registerProblem(type.pyClass.nameIdentifier, "All bases of a protocol must be protocols")
}
}
private fun checkRuntimeProtocolInIsInstance(node: PyCallExpression) {
if (node.isCalleeText(PyNames.ISINSTANCE, PyNames.ISSUBCLASS)) {
val base = node.arguments.getOrNull(1)
if (base != null) {
val type = myTypeEvalContext.getType(base)
if (type is PyClassType &&
isProtocol(type, myTypeEvalContext) &&
!PyKnownDecoratorUtil.getKnownDecorators(type.pyClass, myTypeEvalContext).contains(TYPING_RUNTIME)) {
registerProblem(base, "Only @runtime protocols can be used with instance and class checks", GENERIC_ERROR)
}
}
}
}
private fun checkNewTypeWithProtocols(node: PyCallExpression) {
val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext)
node
.multiResolveCalleeFunction(resolveContext)
.firstOrNull { it.qualifiedName == PyTypingTypeProvider.NEW_TYPE }
?.let {
val base = node.arguments.getOrNull(1)
if (base != null) {
val type = myTypeEvalContext.getType(base)
if (type is PyClassLikeType && isProtocol(type, myTypeEvalContext)) {
registerProblem(base, "NewType cannot be used with protocol classes")
}
}
}
}
private fun checkMemberCompatibility(protocolElement: PyTypedElement,
subclassElements: List<RatedResolveResult>,
type: PyClassType,
protocol: PyClassType) {
val expectedMemberType = myTypeEvalContext.getType(protocolElement)
subclassElements
.asSequence()
.map { it.element }
.filterIsInstance<PyTypedElement>()
.filter { it.containingFile == type.pyClass.containingFile }
.filterNot { PyTypeChecker.match(expectedMemberType, myTypeEvalContext.getType(it), myTypeEvalContext) }
.forEach {
val place = if (it is PsiNameIdentifierOwner) it.nameIdentifier else it
registerProblem(place, "Type of '${it.name}' is incompatible with '${protocol.name}'")
}
}
}
} | apache-2.0 | 864a32ff4bcd66a604abad8217eb5409 | 40.837037 | 140 | 0.695591 | 5.091975 | false | false | false | false |
yshrsmz/monotweety | app/src/test/java/net/yslibrary/monotweety/appdata/user/UserRepositoryImplTest.kt | 1 | 5099 | package net.yslibrary.monotweety.appdata.user
import com.gojuno.koptional.None
import com.google.common.truth.Truth.assertThat
import com.google.gson.Gson
import io.mockk.MockKAnnotations
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Single
import net.yslibrary.monotweety.appdata.user.local.UserLocalRepository
import net.yslibrary.monotweety.appdata.user.remote.UserRemoteRepository
import net.yslibrary.monotweety.base.Clock
import net.yslibrary.monotweety.readJsonFromAssets
import org.junit.Before
import org.junit.Test
import java.util.concurrent.TimeUnit
import com.twitter.sdk.android.core.models.User as TwitterUser
class UserRepositoryImplTest {
@MockK
lateinit var clock: Clock
@MockK
lateinit var localRepository: UserLocalRepository
@MockK
lateinit var remoteRepository: UserRemoteRepository
lateinit var repository: UserRepositoryImpl
val gson = Gson()
@Before
fun setup() {
MockKAnnotations.init(this, relaxUnitFun = true)
repository = UserRepositoryImpl(
remoteRepository = remoteRepository,
localRepository = localRepository,
clock = clock
)
}
@Test
fun get() {
every { localRepository.getById(any()) } returns Flowable.just(None)
repository.get(1).test()
.apply {
assertValue(None)
verify {
localRepository.getById(1)
}
confirmVerified(localRepository, remoteRepository, clock)
}
}
@Test
fun set() {
val time = System.currentTimeMillis()
val twitterUser = gson.fromJson(readJsonFromAssets("user.json"), TwitterUser::class.java)
val user = User(
id = twitterUser.id,
name = twitterUser.name,
screenName = twitterUser.screenName,
profileImageUrl = twitterUser.profileImageUrlHttps,
_updatedAt = time
)
every { localRepository.set(user) } returns Completable.complete()
repository.set(user).test()
.apply {
assertNoValues()
assertComplete()
verify {
localRepository.set(user)
}
confirmVerified(localRepository, remoteRepository, clock)
}
}
@Test
fun delete() {
every { localRepository.delete(any()) } returns Completable.complete()
repository.delete(1234).test()
.apply {
assertNoValues()
assertComplete()
verify {
localRepository.delete(1234)
}
confirmVerified(localRepository, remoteRepository, clock)
}
}
@Test
fun fetch() {
val time = System.currentTimeMillis()
val twitterUser = gson.fromJson(readJsonFromAssets("user.json"), TwitterUser::class.java)
val user = User(
id = twitterUser.id,
name = twitterUser.name,
screenName = twitterUser.screenName,
profileImageUrl = twitterUser.profileImageUrl,
_updatedAt = time
)
every { remoteRepository.get() } returns Single.just(user.copy(_updatedAt = -1))
every { localRepository.set(user) } returns Completable.complete()
every { clock.currentTimeMillis() } returns time
repository.fetch().test()
.apply {
assertNoValues()
assertComplete()
verify {
remoteRepository.get()
localRepository.set(user)
clock.currentTimeMillis()
}
confirmVerified(remoteRepository, localRepository, clock)
}
}
@Test
fun isValid_valid() {
val timestamp = System.currentTimeMillis()
val before11hours = timestamp - TimeUnit.HOURS.toMillis(11)
every { clock.currentTimeMillis() } returns timestamp
val user = User(
id = 1,
name = "test_name",
screenName = "test_screen_name",
profileImageUrl = "https://test.com/profile.jpg",
_updatedAt = before11hours
)
assertThat(repository.isValid(user)).isTrue()
}
@Test
fun isValid_null_user() {
assertThat(repository.isValid(null)).isFalse()
}
@Test
fun isValid_outdated() {
val timestamp = System.currentTimeMillis()
val before13hours = timestamp - TimeUnit.HOURS.toMillis(13)
every { clock.currentTimeMillis() } returns timestamp
val user = User(
id = 1,
name = "test_name",
screenName = "test_screen_name",
profileImageUrl = "https://test.com/profile.jpg",
_updatedAt = before13hours
)
assertThat(repository.isValid(user)).isFalse()
}
}
| apache-2.0 | df88bbbecd5708081e6112e38103db6c | 27.80791 | 97 | 0.600314 | 5.083749 | false | true | false | false |
google/ksp | integration-tests/src/test/resources/incremental-multi-chain/processors/src/main/kotlin/ImplGen.kt | 1 | 1390 | import com.google.devtools.ksp.processing.*
import com.google.devtools.ksp.symbol.*
import java.io.OutputStreamWriter
class ImplGen : SymbolProcessor {
lateinit var codeGenerator: CodeGenerator
lateinit var logger: KSPLogger
fun init(
options: Map<String, String>,
kotlinVersion: KotlinVersion,
codeGenerator: CodeGenerator,
logger: KSPLogger,
) {
this.codeGenerator = codeGenerator
this.logger = logger
}
override fun process(resolver: Resolver): List<KSAnnotated> {
resolver.getSymbolsWithAnnotation("NeedsImpl").forEach { decl ->
decl as KSClassDeclaration
val file = decl.containingFile!!
val baseName = decl.simpleName.asString()
val implName = baseName + "Impl"
OutputStreamWriter(
codeGenerator.createNewFile(
Dependencies(false, file),
"", implName
)
).use {
it.write("@Impl class $implName : $baseName\n")
}
}
return emptyList()
}
}
class ImplGenProvider : SymbolProcessorProvider {
override fun create(
env: SymbolProcessorEnvironment,
): SymbolProcessor {
return ImplGen().apply {
init(env.options, env.kotlinVersion, env.codeGenerator, env.logger)
}
}
}
| apache-2.0 | 0b0bdb74332bf2f5a9438dcc8c900c29 | 29.217391 | 79 | 0.602158 | 5.265152 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/utils/settings/SettingsRepository.kt | 1 | 3630 | package me.mrkirby153.KirBot.utils.settings
import com.google.common.cache.Cache
import com.google.common.cache.CacheBuilder
import com.google.common.util.concurrent.UncheckedExecutionException
import com.mrkirby153.bfs.Pair
import com.mrkirby153.bfs.model.Model
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.database.models.GuildSetting
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.sharding.ShardManager
object SettingsRepository {
private const val nullString = "\u0000";
private val settingsCache: Cache<String, String> = CacheBuilder.newBuilder().maximumSize(
10000).build()
private val settingsListeners = mutableMapOf<String, MutableList<(Guild, String?) -> Unit>>()
fun get(guildId: String, key: String): String? {
try {
val cachedValue = settingsCache.get("$guildId-$key") loader@{
Bot.LOG.debug("Retrieving $key from the database for $guildId")
val setting = Model.query(GuildSetting::class.java).where("guild", guildId).where(
"key",
key).first()
if (setting != null) {
Bot.LOG.debug("Retrieved \"${setting.value}\" from the database")
} else {
Bot.LOG.debug("Retrieved \"null\" from the database")
return@loader nullString
}
return@loader setting.value
}
return if (cachedValue == nullString)
null
else
cachedValue
} catch (e: UncheckedExecutionException) {
if (e.cause is NoSuchElementException) {
return null // The value does not exist in the database
} else {
throw e
}
}
}
fun set(guildId: String, key: String, value: String?) {
if (value == null) {
Model.query(GuildSetting::class.java).where("guild", guildId).where("key", key).delete()
} else {
val exists = Model.query(GuildSetting::class.java).where("guild", guildId).where("key",
key).exists()
if (exists) {
Model.query(GuildSetting::class.java).where("guild", guildId).where("key",
key).update(mutableListOf(Pair<String, Any>("one", "two")))
} else {
val gs = GuildSetting()
gs.guildId = guildId
gs.key = key
gs.value = value
gs.save()
}
}
if (value != null)
settingsCache.put("$guildId-$key", value)
else
settingsCache.invalidate("$guildId-$key")
}
fun onSettingsChange(guildId: String, key: String, newValue: String?) {
Bot.LOG.debug("$key on $guildId changed to \"$newValue\"")
if (newValue != null)
settingsCache.put("$guildId-$key", newValue) // Update our cached value
else
settingsCache.put("$guildId-$key", nullString)
val guild = Bot.applicationContext.get(ShardManager::class.java).getGuildById(guildId)
?: return
settingsListeners[key]?.forEach {
try {
it.invoke(guild, newValue)
} catch (e: Exception) {
Bot.LOG.error("An error occurred when invoking a settings change listener", e)
}
}
}
fun registerSettingsListener(key: String, listener: (Guild, String?) -> Unit) {
settingsListeners.getOrPut(key) { mutableListOf() }.add(listener)
}
} | mit | 19c776f7988432e40ca3159f8d3eea0d | 38.043011 | 100 | 0.570248 | 4.66581 | false | false | false | false |
HerbLuo/shop-api | src/main/java/cn/cloudself/model/ItemSellingInfoEntity.kt | 1 | 966 | package cn.cloudself.model
import org.hibernate.annotations.DynamicInsert
import javax.persistence.*
/**
* @author HerbLuo
* @version 1.0.0.d
*/
@Entity
@DynamicInsert
@Table(name = "item_selling_info", schema = "shop")
data class ItemSellingInfoEntity(
@get:Id
@get:Column(name = "item_id", nullable = false)
@get:GeneratedValue(strategy = GenerationType.IDENTITY)
var itemId: Int = 0,
@get:Basic
@get:Column(name = "quantity", nullable = false)
var quantity: Int = 0,
@get:Basic
@get:Column(name = "sales", nullable = false)
var sales: Int = 0,
@get:Basic
@get:Column(name = "comment_num", nullable = false)
var commentNum: Int = 0,
@get:Basic
@get:Column(name = "score", nullable = false, precision = 0)
var score: Double = 0.0,
@get:Basic
@get:Column(name = "in_ordering")
var inOrdering: Int = 0
)
| mit | e37c9a087a4f2ba4934bfd20677f25a5 | 23.769231 | 68 | 0.593168 | 3.525547 | false | false | false | false |
kvnxiao/kommandant | kommandant-core/src/main/kotlin/com/github/kvnxiao/kommandant/Kommandant.kt | 2 | 7902 | /*
* Copyright 2017 Ze Hao Xiao
*
* 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.github.kvnxiao.kommandant
import com.github.kvnxiao.kommandant.command.CommandContext
import com.github.kvnxiao.kommandant.command.CommandResult
import com.github.kvnxiao.kommandant.command.ICommand
import com.github.kvnxiao.kommandant.impl.CommandBank
import com.github.kvnxiao.kommandant.impl.CommandExecutor
import com.github.kvnxiao.kommandant.impl.CommandParser
import com.github.kvnxiao.kommandant.utility.ImmutableCommandMap
import com.github.kvnxiao.kommandant.utility.SplitString
import com.github.kvnxiao.kommandant.utility.StringSplitter
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.lang.reflect.InvocationTargetException
import kotlin.reflect.KClass
/**
* The default aggregation of a command registry, parser, and executor, which manages and executes commands.
*
* @property[cmdBank] The command registry, an implementation of [ICommandBank].
* @property[cmdExecutor] The command executor, an implementation of [ICommandExecutor].
* @property[cmdParser] The command parser, an implementation of [ICommandParser].
* @constructor Default constructor which uses default implementations of the registry, parser, and executor.
*/
open class Kommandant(protected val cmdBank: ICommandBank = CommandBank(), protected val cmdExecutor: ICommandExecutor = CommandExecutor(), protected val cmdParser: ICommandParser = CommandParser()) {
companion object {
/**
* Universal logger for logging Kommandant events. For example, registering a command, executing a command, etc.
*/
@JvmField
val LOGGER: Logger = LoggerFactory.getLogger(Kommandant::class.java)
}
/**
* Processes a string input with any additional variables for command execution.
*
* @param[input] The string input to parse into valid context and command.
* @param[opt] A nullable vararg of optional, extra input variables.
* @return[CommandResult] The result after attempting execution of the command. Will return false and null if there
* was no command to execute.
*/
open fun <T> process(input: String, vararg opt: Any?): CommandResult<T> {
val (alias, args) = SplitString(input)
if (alias !== null) {
val command: ICommand<*>? = this.getCommand(alias)
if (command !== null) {
val context = CommandContext(alias, args, command)
return processCommand(command, context, *opt)
}
}
return CommandResult(false)
}
open fun splitString(input: String): Array<String> = StringSplitter.split(input, StringSplitter.SPACE_LITERAL, 2)
/**
* Processes a provided command with a given command context and any additional variables for command execution.
*
* @param[command] The command to execute.
* @param[context] The context of the command, containing the calling alias and any args it may have.
* @param[opt] A nullable vararg of [Any], which can be useful in specific implementations when a command requires
* more than just context for execution.
* @return[CommandResult] The result after attempting execution of the command. Will return false and null if there
* was no command to execute.
*/
open protected fun <T> processCommand(command: ICommand<*>, context: CommandContext, vararg opt: Any?): CommandResult<T> = cmdExecutor.execute(command, context, *opt)
/* * *
*
* Wrapper functions for the command bank, parser, and executor
*
* * */
/**
* Deletes all commands from the registry and clears the registry's internal store.
*
* @see[CommandBank.clearAll]
*/
open fun clearAll() = cmdBank.clearAll()
/**
* Adds a [command] to the registry. Failure to add commands occur if an alias clashes with another command's alias
* for the provided prefix, or if the command's identifier / name is not unique.
*
* @see[CommandBank.addCommand]
*/
open fun addCommand(command: ICommand<*>): Boolean = cmdBank.addCommand(command)
/**
* Gets a command by providing a single string representing the combination of the command's prefix and alias.
*
* @see[CommandBank.getCommand]
*/
open fun getCommand(prefixedAlias: String): ICommand<*>? = cmdBank.getCommand(prefixedAlias)
/**
* Deletes a command from the registry by removing it and unlinking all subcommand references.
*
* @see[CommandBank.deleteCommand]
*/
open fun deleteCommand(command: ICommand<*>?): Boolean = if (command !== null) cmdBank.deleteCommand(command) else false
/**
* Changes a prefix of a command in the registry.
*
* @see[CommandBank.changePrefix]
*/
open fun changePrefix(command: ICommand<*>?, newPrefix: String): Boolean = if (command !== null) cmdBank.changePrefix(command, newPrefix) else false
/**
* Gets all the prefixes currently registered.
*
* @see[CommandBank.getPrefixes]
*/
open fun getPrefixes(): Set<String> = cmdBank.getPrefixes()
/**
* Gets all the 'aliases' to 'command' map currently registered under the specified prefix.
*
* @see[CommandBank.getCommandsForPrefix]
*/
open fun getCommandsForPrefix(prefix: String): ImmutableCommandMap = cmdBank.getCommandsForPrefix(prefix)
/**
* Gets all the 'prefix + aliases' to 'command' map from the registry.
*
* @see[CommandBank.getCommands]
*/
open fun getAllCommands(): ImmutableCommandMap = cmdBank.getCommands()
/**
* Gets an immutable list of all registered commands in the registry.
*
* @see[CommandBank.getCommandsUnique]
*/
open fun getCommandsUnique(): List<ICommand<*>> = cmdBank.getCommandsUnique()
/**
* Parse [CommandAnn][com.github.kvnxiao.kommandant.command.CommandAnn] annotations for a list of commands created from those annotations.
*
* @see[CommandParser.parseAnnotations]
*/
open fun parseAnnotations(instance: Any): List<ICommand<*>> = cmdParser.parseAnnotations(instance)
/**
* Parses a provided object instance for annotated commands in its class and adds them all to the command registry.
*/
open fun addAnnotatedCommands(instance: Any) {
try {
// Add each command resulting from parsed annotations to the bank
this.parseAnnotations(instance).forEach {
this.addCommand(it)
}
} catch (e: InvocationTargetException) {
LOGGER.error("'${e.localizedMessage}': Could not instantiate an object instance of class '${instance::class.java.name}'!")
} catch (e: IllegalAccessException) {
LOGGER.error("'${e.localizedMessage}': Failed to access method definition in class '${instance::class.java.name}'!")
}
}
/**
* Parses a provided (Java) class for annotated commands and adds them all to the command registry.
*/
open fun addAnnotatedCommands(clazz: Class<*>) = this.addAnnotatedCommands(clazz.newInstance())
/**
* Parses a provided (Kotlin) class for annotated commands and adds them all to the command registry.
*/
open fun addAnnotatedCommands(ktClazz: KClass<*>) = this.addAnnotatedCommands(ktClazz.java.newInstance())
} | apache-2.0 | eecf5699ce9796697272ba7cabae3c25 | 41.037234 | 200 | 0.697165 | 4.515429 | false | false | false | false |
RettyEng/redux-kt | sample/app/src/main/kotlin/me/retty/reduxkt/sample/redux/store/Store.kt | 1 | 1428 | package me.retty.reduxkt.sample.redux.store
import me.retty.reduxkt.Action
import me.retty.reduxkt.Store
import me.retty.reduxkt.sample.redux.ActionCreator
import me.retty.reduxkt.sample.redux.AsyncActionCreator
import me.retty.reduxkt.sample.redux.Subscriber
import me.retty.reduxkt.sample.redux.middleware.logger
import me.retty.reduxkt.sample.redux.reducer.RootReducerSet
import me.retty.reduxkt.sample.redux.state.ApplicationState
/**
* Created by atsukofukui on 2017/08/23.
*/
object Store {
private val store: Store<ApplicationState> by lazy {
Store(getInitialState(),
RootReducerSet.aggregatedReducer,
listOf(logger))
}
private fun getInitialState(): ApplicationState {
return ApplicationState()
}
fun getState(): ApplicationState = this.store.state
fun subscribe(subscriber: Subscriber) = this.store.subscribe(subscriber)
fun unsubscribe(subscriber: Subscriber) =
this.store.unsubscribe(subscriber)
fun dispatch(action: Action) = this.store.dispatch(action)
fun dispatch(actionCreator: ActionCreator) =
this.store.dispatch(actionCreator)
fun dispatch(actionCreator: AsyncActionCreator) =
this.store.dispatch(actionCreator)
fun dispatch(actionCreator: AsyncActionCreator,
callback: (ApplicationState) -> Unit) =
this.store.dispatch(actionCreator, callback)
} | mit | a0a349d47d4a68d8c394271442454ae8 | 33.02381 | 76 | 0.728291 | 4.25 | false | false | false | false |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/layers/ui/UILayer.kt | 1 | 1848 | package com.binarymonks.jj.core.layers.ui
import com.badlogic.gdx.InputMultiplexer
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.math.Vector
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.Actor
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.utils.ObjectMap
import com.badlogic.gdx.utils.viewport.Viewport
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.layers.Layer
import com.binarymonks.jj.core.layers.LayerStack
import com.binarymonks.jj.core.pools.new
import com.binarymonks.jj.core.scenes.Scene
open class UILayer(
override var inputMultiplexer: InputMultiplexer = InputMultiplexer(),
override var stack: LayerStack? = null
) : Stage(), Layer {
val namedActors: ObjectMap<String, Actor> = ObjectMap()
init {
this.inputMultiplexer.addProcessor(this)
}
constructor(
viewport: Viewport
) : this(inputMultiplexer = InputMultiplexer(), stack = null) {
this.viewport = viewport
}
fun addActor(name: String, actor: Actor) {
super.addActor(actor)
namedActors.put(name, actor)
}
fun getActor(name: String): Actor {
return namedActors.get(name)
}
override fun update() {
act(JJ.clock.deltaFloat)
draw()
}
override fun resize(width: Int, height: Int) {
viewport.update(width, height, true)
}
}
class SceneAwareActorProxy: Actor(){
val offset = new(Vector2::class)
var scene: Scene? = null
var innerActor: Actor? = null
override fun act(delta: Float) {
innerActor!!.act(delta)
}
override fun draw(batch: Batch?, parentAlpha: Float) {
val scenePosition = scene!!.physicsRoot.position()
scenePosition.add(offset)
super.draw(batch, parentAlpha)
}
} | apache-2.0 | 4c451dfdbf653e12e00443ab2714e8cb | 26.191176 | 77 | 0.690476 | 3.841996 | false | false | false | false |
laurencegw/jenjin | jenjin-spine/src/test/kotlin/com/binarymonks/jj/spine/components/SpineComponentTest.kt | 1 | 2559 | package com.binarymonks.jj.spine.components
import com.binarymonks.jj.core.JJ
import com.binarymonks.jj.core.audio.SoundMode
import com.binarymonks.jj.core.components.Component
import com.binarymonks.jj.core.mockoutGDXinJJ
import com.binarymonks.jj.core.specs.SceneSpecRef
import com.binarymonks.jj.spine.specs.SpineAnimations
import com.binarymonks.jj.spine.specs.SpineSpec
import com.esotericsoftware.spine.Event
import org.junit.Assert
import org.junit.Before
import org.junit.Test
class SpineComponentTest {
@Before
fun setUp(){
mockoutGDXinJJ()
}
@Test
fun testClone(){
val original = SpineComponent(SpineAnimations())
original.clone()
}
}
fun spineBoy(): SceneSpecRef {
return SpineSpec {
spineRender {
atlasPath = "spine/spineboy/spineboy-pma.atlas"
dataPath = "spine/spineboy/spineboy.json"
scale = 1 / 247f
originY = 247f
}
animations {
defaultMix=0.5f
startingAnimation="idle"
setMix("walk", "run", 0.4f)
setMix( "run", "walk",0.5f)
registerEventHandler("footstep", { component, _ ->
component.me().soundEffects.triggerSound("footstep", SoundMode.NORMAL)
})
registerEventHandler("footstep", SpineBoyComponent::class, SpineBoyComponent::onEvent)
registerEventFunction("footstep", SpineBoyComponent::class, SpineBoyComponent::step)
}
rootScene {
component(SpineBoyComponent())
sounds.sound("footstep", "sounds/step.mp3")
}
}
}
class SpineBoyComponent : Component() {
var nextTransition = "walk"
var scheduledID = -1
override fun onAddToWorld() {
scheduledID= JJ.clock.schedule(this::transition,delaySeconds = 3f, repeat = 0)
}
override fun onRemoveFromWorld() {
JJ.clock.cancel(scheduledID)
}
fun onEvent(event: Event) {
println("Just stepped for event: ${event.data.name}")
}
fun step() {
println("Just stepped because I was told to")
}
fun transition(){
when(nextTransition){
"walk" -> {
me().getComponent(SpineComponent::class)[0].transitionToAnimation("walk")
nextTransition="run"
}
"run" -> {
me().getComponent(SpineComponent::class)[0].transitionToAnimation("run")
nextTransition="walk"
}
else -> println("Confused")
}
}
} | apache-2.0 | 06f7e5e71a943c0a0348c1ee572f73bc | 26.826087 | 98 | 0.614693 | 4.120773 | false | false | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/MyApp.kt | 1 | 1933 | package im.fdx.v2ex
import android.app.Application
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatDelegate.*
import androidx.core.content.edit
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import im.fdx.v2ex.network.HttpHelper
import im.fdx.v2ex.network.cookie.SharedPrefsPersistor
import im.fdx.v2ex.utils.Keys
import im.fdx.v2ex.utils.extensions.logd
import org.jetbrains.anko.defaultSharedPreferences
import java.net.HttpCookie
val pref: SharedPreferences by lazy {
myApp.defaultSharedPreferences
}
@Deprecated("技术困难,下一期实现")
val userPref: SharedPreferences by lazy {
val fileName = pref.getString(Keys.KEY_USERNAME, "user")
myApp.getSharedPreferences(fileName, Context.MODE_PRIVATE)
}
val myApp: MyApp by lazy {
MyApp.get()
}
/**
* Created by fdx on 2015/8/16.
* 用于启动时获取app状态
*/
class MyApp : Application() {
companion object {
private lateinit var INSTANCE: MyApp
fun get(): MyApp {
return INSTANCE
}
}
internal var isLogin = false
override fun onCreate() {
super.onCreate()
INSTANCE = this
XLog.init(when {
BuildConfig.DEBUG -> LogLevel.ALL
else -> LogLevel.NONE
})
isLogin = pref.getBoolean(Keys.PREF_KEY_IS_LOGIN, false)
logd("onCreate\nisLogin:$isLogin")
// setDefaultNightMode(if (pref.getBoolean("NIGHT_MODE", false)) MODE_NIGHT_YES else MODE_NIGHT_NO)
}
}
fun setLogin(login: Boolean) {
myApp.isLogin = login
pref.edit {
putBoolean(Keys.PREF_KEY_IS_LOGIN, login)
}
if(!login){
HttpHelper.myCookieJar.clear()
}
LocalBroadcastManager.getInstance(myApp).sendBroadcast(
if (login){
Intent(Keys.ACTION_LOGIN)
} else {
Intent(Keys.ACTION_LOGOUT)
})
} | apache-2.0 | b2ec233dd2524f8d351731763bca5031 | 24.621622 | 102 | 0.725066 | 3.737673 | false | false | false | false |
mixitconf/mixit | src/main/kotlin/mixit/blog/repository/PostRepository.kt | 1 | 2756 | package mixit.blog.repository
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import mixit.blog.model.Post
import mixit.talk.model.Language
import org.slf4j.LoggerFactory
import org.springframework.core.io.ClassPathResource
import org.springframework.data.domain.Sort
import org.springframework.data.domain.Sort.Direction.DESC
import org.springframework.data.domain.Sort.Order
import org.springframework.data.mongodb.core.ReactiveMongoTemplate
import org.springframework.data.mongodb.core.count
import org.springframework.data.mongodb.core.find
import org.springframework.data.mongodb.core.findById
import org.springframework.data.mongodb.core.findOne
import org.springframework.data.mongodb.core.query.Criteria.where
import org.springframework.data.mongodb.core.query.Query
import org.springframework.data.mongodb.core.query.TextCriteria
import org.springframework.data.mongodb.core.query.TextQuery
import org.springframework.data.mongodb.core.query.isEqualTo
import org.springframework.data.mongodb.core.remove
import org.springframework.stereotype.Repository
import reactor.core.publisher.Flux
@Repository
class PostRepository(
private val template: ReactiveMongoTemplate,
private val objectMapper: ObjectMapper
) {
private val logger = LoggerFactory.getLogger(this.javaClass)
fun initData() {
if (count().block() == 0L) {
val blogResource = ClassPathResource("data/blog.json")
val posts: List<Post> = objectMapper.readValue(blogResource.inputStream)
posts.forEach { save(it).block() }
logger.info("Blog posts data initialization complete")
}
}
fun count() = template.count<Post>()
fun findOne(id: String) = template.findById<Post>(id)
fun findBySlug(slug: String, lang: Language) =
template.findOne<Post>(Query(where("slug.$lang").isEqualTo(slug)))
fun findAll(lang: Language? = null): Flux<Post> {
val query = Query()
query.with(Sort.by(Order(DESC, "addedAt")))
// query.fields().exclude("content")
if (lang != null) {
query.addCriteria(where("title.$lang").exists(true))
}
return template.find<Post>(query).doOnComplete { logger.info("Load all posts") }
}
fun findFullText(criteria: List<String>): Flux<Post> {
val textCriteria = TextCriteria()
criteria.forEach { textCriteria.matching(it) }
val query = TextQuery(textCriteria).sortByScore()
return template.find(query)
}
fun deleteAll() = template.remove<Post>(Query())
fun deleteOne(id: String) = template.remove<Post>(Query(where("_id").isEqualTo(id)))
fun save(article: Post) = template.save(article)
}
| apache-2.0 | d7c1ccf34e60fedbb94b8314d064998a | 36.753425 | 88 | 0.731858 | 4.089021 | false | false | false | false |
pdvrieze/ProcessManager | PE-common/src/jvmMain/kotlin/nl/adaptivity/messaging/DarwinMessenger.kt | 1 | 25004 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.messaging
import net.devrieze.util.InputStreamOutputStream
import nl.adaptivity.util.activation.SourceDataSource
import nl.adaptivity.ws.soap.SoapHelper
import nl.adaptivity.ws.soap.SoapMessageHandler
import javax.xml.bind.JAXB
import javax.xml.namespace.QName
import javax.xml.transform.Source
import javax.xml.transform.stream.StreamSource
import java.io.*
import java.net.*
import java.util.ArrayList
import java.util.concurrent.*
import java.util.logging.Level
import java.util.logging.Logger
/**
* Messenger to use in the darwin project.
*
* @author Paul de Vrieze
*/
class DarwinMessenger
/**
* Create a new messenger. As the class is a singleton, this is only invoked
* (indirectly) through [.register]
*/
private constructor() : IMessenger {
private val executor: ExecutorService
private var services: ConcurrentMap<QName, ConcurrentMap<String, EndpointDescriptor>>
private val notifier: MessageCompletionNotifier<*>
private var mLocalUrl: URI? = null
/**
* Helper thread that performs (in a single tread) all notifications of
* messaging completions. The notification can not be done on the sending
* thread (deadlocks as that thread would be waiting for itself) and the
* calling tread is unknown.
*
* @author Paul de Vrieze
*/
private inner class MessageCompletionNotifier<T> : Thread(NOTIFIERTHREADNAME) {
/**
* Queue containing the notifications still to be sent. This is internally
* synchronized so doesn't need to be manually synchronized.
*/
private val mPendingNotifications: BlockingQueue<MessageTask<T>>
@Volatile
private var mFinished = false
/**
* Create a new notifier.
*/
init {
this.isDaemon = true // This is just a helper thread, don't block cleanup.
mPendingNotifications = LinkedBlockingQueue(CONCURRENTCAPACITY)
}
/**
* Simple message pump.
*/
override fun run() {
while (!mFinished) {
try {
val future = mPendingNotifications.poll(NOTIFICATIONPOLLTIMEOUTMS, TimeUnit.MILLISECONDS)
if (future != null) {
notififyCompletion(future)
}
} catch (e: InterruptedException) {
// Ignore the interruption. Just continue
}
}
}
/**
* Allow for shutting down the thread. As mFinished is volatile, this should
* not need further synchronization.
*/
fun shutdown() {
mFinished = true
interrupt()
}
/**
* Add a notification to the message queue.
*
* @param future The future whose completion should be communicated.
*/
fun addNotification(future: MessageTask<T>) {
// mPendingNotifications is threadsafe!
mPendingNotifications.add(future)
}
/**
* Helper method to notify of future completion.
*
* @param future The future to notify completion of.
*/
private fun notififyCompletion(future: MessageTask<T>) {
future.completionListener?.onMessageCompletion(future)
}
}
/**
* Future that encapsulates a future that represents the sending of a message.
* This is a message that
*
* @author Paul de Vrieze
* @param T
*/
internal inner class MessageTask<T> : RunnableFuture<T> {
/** The uri to use for sending the message. */
private var destURL: URI? = null
/** The message to send. */
private var message: ISendableMessage? = null
/** The listener to notify of completion. */
var completionListener: CompletionListener<T>? = null
/** The result value. */
private var result: T? = null
/** The cancellation state. */
private var cancelled = false
/** The response code given by the response. */
private var responseCode: Int = 0
/** The exception in this future. */
private var error: Exception? = null
/** Set when the message sending is actually active. The processing of the future has started. */
private var started = false
/** The return type of the future. */
private val returnType: Class<T>?
/**
* Create a new task.
* @param destURL The url to invoke
* @param message The message to send.
* @param completionListener The listener to notify. This may be `null`.
* @param returnType The return type of the message. Needed for unmarshalling.
*/
constructor(
destURL: URI,
message: ISendableMessage,
completionListener: CompletionListener<T>,
returnType: Class<T>
) {
this.destURL = destURL
this.message = message
this.completionListener = completionListener
this.returnType = returnType
}
/**
* Simple constructor that creates a future encapsulating the exception
*
* @param e The exception to encapsulate.
*/
constructor(e: Exception) {
error = e
returnType = null
}
/**
* Create a future that just contains the value without computation/ waiting
* possible. The result value. This is for returning synchronous values as
* future.
*
* @param result The result value of the future.
*/
constructor(result: T?) {
if (result == null) {
@Suppress("UNCHECKED_CAST")
this.result = NULL as T
} else {
this.result = result
}
returnType = null
}
override fun run() {
val cancelled: Boolean
synchronized(this) {
started = true
cancelled = this.cancelled
}
try {
if (!cancelled) {
val result = sendMessage()
synchronized(this) {
if (result == null) {
// Use separate value to allow for suppressing of warning.
@Suppress("UNCHECKED_CAST")
val v = NULL as T
this.result = v
} else {
this.result = result
}
}
}
} catch (e: MessagingException) {
Logger.getLogger(DarwinMessenger::class.java.name).log(Level.WARNING, "Error sending message", e)
throw e
} catch (e: Exception) {
Logger.getLogger(DarwinMessenger::class.java.name).log(Level.WARNING, "Error sending message", e)
synchronized(this) {
error = e
}
} finally {
notifyCompletionListener(this)
}
}
/**
* This method performs the actual sending of the message.
* @return The return value of the message.
* @throws IOException
* @throws ProtocolException
*/
@Throws(IOException::class)
private fun sendMessage(): T? {
val destination: URL
try {
destination = destURL!!.toURL()
} catch (e: MalformedURLException) {
throw MessagingException(e)
}
val connection = destination.openConnection()
if (connection is HttpURLConnection) {
val message = message!!
val hasPayload = message.bodySource != null
connection.setDoOutput(hasPayload)
var method: String? = message.method
if (method == null) {
method = if (hasPayload) "POST" else "GET"
}
connection.requestMethod = method
var contenttypeset = false
for (header in message.headers) {
connection.addRequestProperty(header.name, header.value)
contenttypeset = contenttypeset or ("Content-Type" == header.name)
}
if (hasPayload && !contenttypeset) { // Set the content type from the source if not yet set.
val contentType = message.contentType
if (contentType != null && contentType.length > 0) {
connection.addRequestProperty("Content-Type", contentType)
}
}
try {
if (hasPayload) {
connection.setRequestProperty("content-type", message.contentType + "; charset=UTF-8")
connection.outputStream.use { out ->
val writer = OutputStreamWriter(out, "UTF-8")
message.bodySource.writeTo(writer)
writer.close()
}
}
connection.connect()
} catch (e: ConnectException) {
throw MessagingException("Error connecting to $destination", e)
}
try {
responseCode = connection.responseCode
if (responseCode < 200 || responseCode >= 400) {
val baos = ByteArrayOutputStream()
InputStreamOutputStream.writeToOutputStream(connection.errorStream, baos)
val errorMessage =
("Error in sending message with $method to ($destination) [$responseCode]:\n${String(
baos.toByteArray()
)}")
Logger.getLogger(DarwinMessenger::class.java.name).info(errorMessage)
throw HttpResponseException(connection.responseCode, errorMessage)
}
if (returnType!!.isAssignableFrom(SourceDataSource::class.java)) {
val baos = ByteArrayOutputStream()
InputStreamOutputStream.writeToOutputStream(connection.inputStream, baos)
return returnType.cast(
SourceDataSource(
connection.contentType, StreamSource(
ByteArrayInputStream(baos.toByteArray())
)
)
)
} else {
return JAXB.unmarshal(connection.inputStream, returnType)
}
} finally {
connection.disconnect()
}
} else {
throw UnsupportedOperationException("No support yet for non-http connections")
}
}
/**
* Cancel the performance of this task. Currently will never actually honour
* the parameter and will never interrupt after the sending started.
*/
@Synchronized
override fun cancel(mayInterruptIfRunning: Boolean): Boolean {
if (cancelled) {
return true
}
if (!started) {
cancelled = true
return true
}
return false
}
@Synchronized
override fun isCancelled(): Boolean {
return cancelled
}
@Synchronized
override fun isDone(): Boolean {
return cancelled || result != null || error != null
}
@Synchronized
@Throws(InterruptedException::class, ExecutionException::class)
override fun get(): T? {
if (cancelled) {
throw CancellationException()
}
if (error != null) {
throw ExecutionException(error)
}
if (result === NULL) {
return null
}
if (result != null) {
return result
}
wait()
// wait for the result
return result
}
/**
* {@inheritDoc} Note that there may be some inaccuracies in the waiting
* time especially if the waiting started before the message delivery
* started, but the timeout finished while the result was not yet in.
*/
@Synchronized
@Throws(InterruptedException::class, ExecutionException::class, TimeoutException::class)
override fun get(timeout: Long, unit: TimeUnit): T? {
if (cancelled) {
throw CancellationException()
}
if (error != null) {
throw ExecutionException(error)
}
if (result === NULL) {
return null
}
if (result != null) {
return result
}
if (timeout == 0L) {
throw TimeoutException()
}
try {
if (unit === TimeUnit.NANOSECONDS) {
wait(unit.toMillis(timeout), (unit.toNanos(timeout) % 1000000).toInt())
} else {
wait(unit.toMillis(timeout))
}
} catch (e: InterruptedException) {
return if (isDone) {
get(0, TimeUnit.MILLISECONDS)// Don't wait, even if somehow the state is wrong.
} else {
throw e
}
}
throw TimeoutException()
}
}
/**
* Let the class loader do the nasty synchronization for us, but still
* initialise ondemand.
*/
private object MessengerHolder {
internal val _GlobalMessenger = DarwinMessenger()
}
init {
executor = ThreadPoolExecutor(
INITIAL_WORK_THREADS, MAXIMUM_WORK_THREADS, WORKER_KEEPALIVE_MS.toLong(),
TimeUnit.MILLISECONDS, ArrayBlockingQueue(CONCURRENTCAPACITY, true)
)
notifier = MessageCompletionNotifier<Any?>()
services = ConcurrentHashMap()
notifier.start()
val localUrl = System.getProperty("nl.adaptivity.messaging.localurl")
if (localUrl == null) {
val msg = StringBuilder()
msg.append(
"DarwinMessenger\n" + "------------------------------------------------\n" + " WARNING\n"
+ "------------------------------------------------\n" + " Please set the nl.adaptivity.messaging.localurl property in\n"
+ " catalina.properties (or a method appropriate for a non-tomcat\n"
+ " container) to the base url used to contact the messenger by\n"
+ " other components of the system. The public base url can be set as:\n"
+ " nl.adaptivity.messaging.baseurl, this should be accessible by\n" + " all clients of the system.\n"
+ "================================================"
)
Logger.getAnonymousLogger().warning(msg.toString())
} else {
try {
mLocalUrl = URI.create(localUrl)
} catch (e: IllegalArgumentException) {
Logger.getAnonymousLogger().log(Level.SEVERE, "The given local url is not a valid uri.", e)
}
}
}
override fun registerEndpoint(service: QName, endPoint: String, target: URI): EndpointDescriptor {
val endpoint = EndpointDescriptorImpl(service, endPoint, target)
registerEndpoint(endpoint)
return endpoint
}
@Synchronized
override fun registerEndpoint(endpoint: EndpointDescriptor) {
// Note that even though it's a concurrent map we still need to synchronize to
// prevent race conditions with multiple registrations.
var service: ConcurrentMap<String, EndpointDescriptor>? = services[endpoint.serviceName]
if (service == null) {
service = ConcurrentHashMap()
services[endpoint.serviceName] = service
}
if (service.containsKey(endpoint.endpointName)) {
service.remove(endpoint.endpointName)
}
service[endpoint.endpointName] = endpoint
}
override fun getRegisteredEndpoints(): List<EndpointDescriptor> {
val result = ArrayList<EndpointDescriptor>()
synchronized(services) {
for (service in services.values) {
for (endpoint in service.values) {
result.add(endpoint)
}
}
}
return result
}
override fun unregisterEndpoint(endpoint: EndpointDescriptor): Boolean {
synchronized(services) {
val service = services[endpoint.serviceName] ?: return false
val result = service.remove(endpoint.endpointName)
if (service.isEmpty()) {
services.remove(endpoint.serviceName)
}
return result != null
}
}
/**
*
*
* {@inheritDoc} The implementation will look up the endpoint registered for
* the destination of the message. Only when none has been registered will it
* attempt to use the url for the message.
*
*
*
* For registered endpoints if they implement [DirectEndpoint] the
* message will be directly delivered to the endpoind through the
* [ deliverMessage][DirectEndpoint.deliverMessage] method. Otherwhise if the endpoint implements
* [Endpoint] the system will use reflection to directly invoke the
* appropriate soap methods on the endpoint.
*
*/
override fun <T> sendMessage(
message: ISendableMessage,
completionListener: CompletionListener<T>,
returnType: Class<T>,
returnContext: Array<Class<*>>
): Future<T>? {
var registeredEndpoint = getEndpoint(message.destination)
if (registeredEndpoint is DirectEndpoint) {
return registeredEndpoint.deliverMessage(message, completionListener, returnType)
}
if (registeredEndpoint is Endpoint) { // Direct delivery when we don't just have a descriptor.
if ("application/soap+xml" == message.contentType) {
val handler = SoapMessageHandler.newInstance(registeredEndpoint)
val resultSource: Source
try {
resultSource = handler.processMessage(message.bodyReader, message.attachments)
val resultfuture: MessageTask<T>
if (returnType.isAssignableFrom(SourceDataSource::class.java)) {
resultfuture = MessageTask(
returnType.cast(SourceDataSource("application/soap+xml", resultSource))
)
} else {
val resultval = SoapHelper.processResponse(returnType, returnContext, null!!, resultSource)
resultfuture = MessageTask(resultval)
}
// resultfuture = new MessageTask<T>(JAXB.unmarshal(resultSource, pReturnType));
completionListener?.onMessageCompletion(resultfuture)
return resultfuture
} catch (e: Exception) {
return MessageTask(e)
}
}
}
if (registeredEndpoint == null) {
registeredEndpoint = message.destination
}
val destURL: URI
if (mLocalUrl == null) {
destURL = registeredEndpoint!!.endpointLocation!!
} else {
val endpointLocation = registeredEndpoint!!.endpointLocation ?: return MessageTask(
NullPointerException("No endpoint location specified, and the service could not be found")
)
destURL = mLocalUrl!!.resolve(endpointLocation)
}
val messageTask = MessageTask<T>(destURL, message, completionListener, returnType)
executor.execute(messageTask)
return messageTask
}
/**
* Shut down the messenger. This will also unregister the messenger with the registry.
*/
override fun shutdown() {
MessagingRegistry.registerMessenger(null) // Unregister this messenger
notifier.shutdown()
executor.shutdown()
services = ConcurrentHashMap()
}
/**
* Method used internally (private is slower though) to notify completion of
* tasks. This is part of the messenger as the messenger maintains a notifier
* thread. As there is only one notifier thread, the handling of notifications
* is expected to be fast.
*
* @param future The Task whose completion to notify of.
*/
internal fun <T> notifyCompletionListener(future: MessageTask<T>) {
(notifier as MessageCompletionNotifier<T>).addNotification(future)
}
/**
* Get the endpoint registered with the given service and endpoint name.
* @param serviceName The name of the service.
* @param endpointName The name of the endpoint in the service.
* @return
*/
fun getEndpoint(serviceName: QName, endpointName: String): EndpointDescriptor? {
val service = services!![serviceName] ?: return null
return service[endpointName]
}
/**
* Get the endpoint registered for the given endpoint descriptor. This
* @param endpoint The
* @return
*/
fun getEndpoint(endpoint: EndpointDescriptor): EndpointDescriptor? {
val service = services!![endpoint.serviceName] ?: return null
return service[endpoint.endpointName]
}
companion object {
/**
* How big should the worker thread pool be initially.
*/
private val INITIAL_WORK_THREADS = 1
/**
* How many worker threads are there concurrently? Note that extra work will
* not block, it will just be added to a waiting queue.
*/
private val MAXIMUM_WORK_THREADS = 20
/**
* How long to keep idle worker threads busy (in miliseconds).
*/
private val WORKER_KEEPALIVE_MS = 60000
/**
* How many queued messages should be allowed. This is also the limit of
* pending notifications.
*/
private val CONCURRENTCAPACITY = 2048 // Allow 2048 pending messages
/** The name of the notification tread. */
private val NOTIFIERTHREADNAME = DarwinMessenger::class.java.name + " - Completion Notifier"
/**
* How long should the notification thread wait when polling messages. This
* should ensure that every 30 seconds it checks whether it's finished.
*/
private val NOTIFICATIONPOLLTIMEOUTMS = 30000L // Timeout polling for next message every 30 seconds
/**
* Marker object for null results.
*/
private val NULL = Any()
/**
* Get the singleton instance. This also updates the base URL.
*
* @return The singleton instance.
*/
fun register() {
MessagingRegistry.registerMessenger(MessengerHolder._GlobalMessenger)
}
}
}
private inline fun DarwinMessenger.wait() {
(this as java.lang.Object).wait()
}
private inline fun DarwinMessenger.wait(timeout: Long) {
(this as java.lang.Object).wait(timeout)
}
private inline fun DarwinMessenger.wait(timeout: Long, nanos: Int) {
(this as java.lang.Object).wait(timeout, nanos)
}
| lgpl-3.0 | e7a6f6f1f3e237ea4f4a78c45ab7d8d4 | 34.925287 | 142 | 0.551232 | 5.491764 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/AListQuestAnswerFragment.kt | 1 | 1524 | package de.westnordost.streetcomplete.quests
import android.os.Bundle
import android.view.View
import android.view.View.generateViewId
import android.widget.RadioButton
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.databinding.QuestGenericRadioListBinding
abstract class AListQuestAnswerFragment<T> : AbstractQuestFormAnswerFragment<T>() {
final override val contentLayoutResId = R.layout.quest_generic_radio_list
private val binding by contentViewBinding(QuestGenericRadioListBinding::bind)
override val defaultExpanded = false
protected abstract val items: List<TextItem<T>>
private val radioButtonIds = HashMap<Int, TextItem<T>>()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
for (item in items) {
val viewId = generateViewId()
radioButtonIds[viewId] = item
val radioButton = RadioButton(view.context)
radioButton.setText(item.titleId)
radioButton.id = viewId
binding.radioButtonGroup.addView(radioButton)
}
binding.radioButtonGroup.setOnCheckedChangeListener { _, _ -> checkIsFormComplete() }
}
override fun onClickOk() {
applyAnswer(radioButtonIds.getValue(binding.radioButtonGroup.checkedRadioButtonId).value)
}
override fun isFormComplete() = binding.radioButtonGroup.checkedRadioButtonId != -1
}
data class TextItem<T>(val value: T, val titleId: Int)
| gpl-3.0 | d58720f6d18ecdf11af9d849f69cf87c | 34.44186 | 97 | 0.738845 | 4.980392 | false | false | false | false |
wleroux/fracturedskies | src/main/kotlin/com/fracturedskies/engine/math/Math.kt | 1 | 1515 | package com.fracturedskies.engine.math
import org.lwjgl.stb.STBPerlin
fun <T: Comparable<T>> clamp(value: T, range: ClosedRange<T>) = when {
value < range.start -> range.start
value > range.endInclusive -> range.endInclusive
else -> value
}
fun map(value: Float, original: ClosedRange<Float>, target: ClosedRange<Float>): Float {
val alpha = (value - original.start) / (original.endInclusive - original.start)
return lerp(alpha, target)
}
fun lerp(alpha: Float, target: ClosedRange<Float>): Float =
target.start + clamp(alpha, 0f..1f) * (target.endInclusive - target.start)
fun lerp(alpha: Float, target: IntRange): Int = target.start + (clamp(alpha, 0f..1f) * (target.endInclusive - target.start)).toInt()
fun lerp(alpha: Float, start: Color4, end: Color4) =
Color4(
lerp(alpha, start.red until end.red),
lerp(alpha, start.green until end.green),
lerp(alpha, start.blue until end.blue),
lerp(alpha, start.alpha until end.alpha)
)
/**
* Perlin Noise
*/
fun noise3(x: Float, y: Float, z: Float, x_wrap: Int = 0, y_wrap: Int = 0, z_wrap: Int = 0): Float {
return STBPerlin.stb_perlin_noise3(x, y, z, x_wrap, y_wrap, z_wrap)
}
/**
* Fractional Brownian Motion using Perlin Noise
*/
fun fbm_noise3(x: Float, y: Float, z: Float, lacunarity: Float = 2.0f, gain: Float = 0.5f, octaves: Int = 6, x_wrap: Int = 0, y_wrap: Int = 0, z_wrap: Int = 0): Float {
return STBPerlin.stb_perlin_fbm_noise3(x, y, z, lacunarity, gain, octaves, x_wrap, y_wrap, z_wrap)
}
| unlicense | edfb7fc114bb1deee5a65bd716b0bb0f | 37.846154 | 168 | 0.670627 | 2.958984 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/sidewalk/AddSidewalkForm.kt | 1 | 7216 | package de.westnordost.streetcomplete.quests.sidewalk
import android.os.Bundle
import android.view.View
import androidx.annotation.AnyThread
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isGone
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.osm.geometry.ElementPolylinesGeometry
import de.westnordost.streetcomplete.databinding.QuestStreetSidePuzzleWithLastAnswerButtonBinding
import de.westnordost.streetcomplete.quests.AbstractQuestFormAnswerFragment
import de.westnordost.streetcomplete.quests.AnswerItem
import de.westnordost.streetcomplete.quests.StreetSideRotater
import de.westnordost.streetcomplete.util.normalizeDegrees
import de.westnordost.streetcomplete.view.ResImage
import de.westnordost.streetcomplete.view.image_select.Item
import de.westnordost.streetcomplete.view.image_select.ImageListPickerDialog
import kotlin.math.absoluteValue
class AddSidewalkForm : AbstractQuestFormAnswerFragment<SidewalkAnswer>() {
override val contentLayoutResId = R.layout.quest_street_side_puzzle_with_last_answer_button
private val binding by contentViewBinding(QuestStreetSidePuzzleWithLastAnswerButtonBinding::bind)
override val otherAnswers = listOf(
AnswerItem(R.string.quest_sidewalk_separately_mapped) { confirmSeparatelyMappedSidewalk() }
)
override val contentPadding = false
private var streetSideRotater: StreetSideRotater? = null
private var leftSide: Sidewalk? = null
private var rightSide: Sidewalk? = null
// just a shortcut
private val isLeftHandTraffic get() = countryInfo.isLeftHandTraffic
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
savedInstanceState?.getString(SIDEWALK_RIGHT)?.let { rightSide = Sidewalk.valueOf(it) }
savedInstanceState?.getString(SIDEWALK_LEFT)?.let { leftSide = Sidewalk.valueOf(it) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.puzzleView.onClickSideListener = { isRight -> showSidewalkSelectionDialog(isRight) }
streetSideRotater = StreetSideRotater(
binding.puzzleView,
binding.littleCompass.root,
elementGeometry as ElementPolylinesGeometry
)
val defaultResId =
if (isLeftHandTraffic) R.drawable.ic_sidewalk_unknown_l
else R.drawable.ic_sidewalk_unknown
binding.puzzleView.setLeftSideImage(ResImage(leftSide?.iconResId ?: defaultResId))
binding.puzzleView.setRightSideImage(ResImage(rightSide?.iconResId ?: defaultResId))
if ((leftSide == null || rightSide == null) && !HAS_SHOWN_TAP_HINT) {
if (leftSide == null) binding.puzzleView.showLeftSideTapHint()
if (rightSide == null) binding.puzzleView.showRightSideTapHint()
HAS_SHOWN_TAP_HINT = true
}
updateLastAnswerButtonVisibility()
lastSelection?.let {
binding.lastAnswerButton.leftSideImageView.setImageResource(it.left.dialogIconResId)
binding.lastAnswerButton.rightSideImageView.setImageResource(it.right.dialogIconResId)
}
binding.lastAnswerButton.root.setOnClickListener { applyLastSelection() }
checkIsFormComplete()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
rightSide?.let { outState.putString(SIDEWALK_RIGHT, it.name) }
leftSide?.let { outState.putString(SIDEWALK_LEFT, it.name) }
}
@AnyThread override fun onMapOrientation(rotation: Float, tilt: Float) {
streetSideRotater?.onMapOrientation(rotation, tilt)
}
override fun onClickOk() {
val leftSide = leftSide
val rightSide = rightSide
val answer = SidewalkSides(
left = leftSide == Sidewalk.YES,
right = rightSide == Sidewalk.YES
)
applyAnswer(answer)
if (leftSide != null && rightSide != null) {
lastSelection =
if (isRoadDisplayedUpsideDown())
LastSidewalkSelection(rightSide, leftSide)
else
LastSidewalkSelection(leftSide, rightSide)
}
}
private fun confirmSeparatelyMappedSidewalk() {
AlertDialog.Builder(requireContext())
.setTitle(R.string.quest_generic_confirmation_title)
.setPositiveButton(R.string.quest_generic_confirmation_yes) { _, _ -> applyAnswer(SeparatelyMapped) }
.setNegativeButton(R.string.quest_generic_confirmation_no, null)
.show()
}
override fun isFormComplete() = leftSide != null && rightSide != null
override fun isRejectingClose() = leftSide != null || rightSide != null
private fun showSidewalkSelectionDialog(isRight: Boolean) {
val ctx = context ?: return
val items = Sidewalk.values().map { it.asItem() }
ImageListPickerDialog(ctx, items, R.layout.labeled_icon_button_cell, 2) {
onSelectedSide(it.value!!, isRight)
}.show()
}
private fun applyLastSelection() {
val lastSelection = lastSelection ?: return
if (isRoadDisplayedUpsideDown()) {
onSelectedSide(lastSelection.right, false)
onSelectedSide(lastSelection.left, true)
} else {
onSelectedSide(lastSelection.left, false)
onSelectedSide(lastSelection.right, true)
}
}
private fun isRoadDisplayedUpsideDown(): Boolean {
val roadDisplayRotation = binding.puzzleView.streetRotation
return roadDisplayRotation.normalizeDegrees(-180f).absoluteValue > 90f
}
private fun updateLastAnswerButtonVisibility() {
binding.lastAnswerButton.root.isGone =
lastSelection == null || leftSide != null || rightSide != null
}
private fun onSelectedSide(sidewalk: Sidewalk, isRight: Boolean) {
if (isRight) {
binding.puzzleView.replaceRightSideImage(ResImage(sidewalk.iconResId))
binding.puzzleView.setRightSideText(null)
rightSide = sidewalk
} else {
binding.puzzleView.replaceLeftSideImage(ResImage(sidewalk.iconResId))
binding.puzzleView.setLeftSideText(null)
leftSide = sidewalk
}
updateLastAnswerButtonVisibility()
checkIsFormComplete()
}
companion object {
private const val SIDEWALK_LEFT = "sidewalk_left"
private const val SIDEWALK_RIGHT = "sidewalk_right"
private var HAS_SHOWN_TAP_HINT = false
private var lastSelection: LastSidewalkSelection? = null
}
}
private enum class Sidewalk(val dialogIconResId: Int, val iconResId: Int, val titleResId: Int) {
NO(R.drawable.ic_sidewalk_no, R.drawable.ic_sidewalk_puzzle_no, R.string.quest_sidewalk_value_no),
YES(R.drawable.ic_sidewalk_yes, R.drawable.ic_sidewalk_puzzle_yes, R.string.quest_sidewalk_value_yes);
fun asItem() = Item(this, dialogIconResId, titleResId)
}
private data class LastSidewalkSelection(
val left: Sidewalk,
val right: Sidewalk
)
| gpl-3.0 | e27e0f94bc7a2f590b22253c7233af32 | 37.179894 | 117 | 0.696924 | 4.885579 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/viewModel/WalletViewModel.kt | 1 | 2293 | /*
* Copyright (c) 2017. Toshi Inc
*
* 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.toshi.viewModel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.toshi.R
import com.toshi.crypto.HDWallet
import com.toshi.util.SingleLiveEvent
import com.toshi.util.logging.LogUtil
import com.toshi.view.BaseApplication
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subscriptions.CompositeSubscription
class WalletViewModel : ViewModel() {
private val toshiManager by lazy { BaseApplication.get().toshiManager }
private val subscriptions by lazy { CompositeSubscription() }
val walletAddress by lazy { MutableLiveData<String>() }
val error by lazy { SingleLiveEvent<Int>() }
init {
initObservers()
}
private fun initObservers() {
val sub = toshiManager.getWallet()
.subscribe(
{ if (it != null) initAddressObserver(it) },
{ LogUtil.exception("Could not get wallet", it) }
)
subscriptions.add(sub)
}
private fun initAddressObserver(wallet: HDWallet) {
val sub = wallet.getPaymentAddressObservable()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ walletAddress.value = it },
{ error.value = R.string.wallet_address_error }
)
subscriptions.add(sub)
}
override fun onCleared() {
super.onCleared()
subscriptions.clear()
}
} | gpl-3.0 | 8dee23df55e85e0d5f4dc5fa410a8a1c | 33.238806 | 76 | 0.657654 | 4.604418 | false | false | false | false |
pdvrieze/ProcessManager | PEUserMessageHandler/src/main/kotlin/nl/adaptivity/process/userMessageHandler/server/UserTaskMap.kt | 1 | 9130 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.userMessageHandler.server
import io.github.pdvrieze.kotlinsql.ddl.Column
import io.github.pdvrieze.kotlinsql.ddl.Table
import io.github.pdvrieze.kotlinsql.dml.Insert
import io.github.pdvrieze.kotlinsql.dml.WhereClause
import io.github.pdvrieze.kotlinsql.dml.impl._ListSelect
import io.github.pdvrieze.kotlinsql.dml.impl._UpdateBuilder
import io.github.pdvrieze.kotlinsql.dml.impl._Where
import io.github.pdvrieze.kotlinsql.monadic.actions.*
import io.github.pdvrieze.kotlinsql.monadic.impl.SelectResultSetRow
import net.devrieze.util.DBTransactionFactory
import net.devrieze.util.Handle
import net.devrieze.util.HandleNotFoundException
import net.devrieze.util.db.AbstractElementFactory
import net.devrieze.util.db.DBHandleMap
import net.devrieze.util.db.MonadicDBTransaction
import net.devrieze.util.security.SYSTEMPRINCIPAL
import nl.adaptivity.messaging.MessagingException
import nl.adaptivity.process.client.ServletProcessEngineClient
import nl.adaptivity.process.engine.processModel.XmlProcessNodeInstance
import nl.adaptivity.xmlutil.serialization.XML
import org.w3.soapEnvelope.Envelope
import uk.ac.bournemouth.ac.db.darwin.usertasks.UserTaskDB
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
class UserTaskMap(connectionProvider: DBTransactionFactory<MonadicDBTransaction<UserTaskDB>, UserTaskDB>) :
DBHandleMap<XmlTask, XmlTask, MonadicDBTransaction<UserTaskDB>, UserTaskDB>(connectionProvider, UserTaskFactory()),
IMutableUserTaskMap<MonadicDBTransaction<UserTaskDB>> {
private class UserTaskFactory :
AbstractElementFactory<XmlTask, XmlTask, MonadicDBTransaction<UserTaskDB>, UserTaskDB>() {
override val table: Table
get() {
return UserTaskDB.usertasks
}
override val createColumns: List<Column<*, *, *>>
get() {
return listOf(u.taskhandle, u.remotehandle)
}
override val keyColumn: Column<Handle<XmlTask>, *, *>
get() = u.taskhandle
// XXX This needs some serious overhaul
override fun createBuilder(
transaction: MonadicDBTransaction<UserTaskDB>,
row: SelectResultSetRow<_ListSelect>
): DBAction<UserTaskDB, XmlTask> {
fun handleException(e: Exception): Nothing {
var f: Throwable = e
while (f.cause != null && (f.cause is ExecutionException || f.cause is MessagingException)) {
f = f.cause!!
}
val cause = f.cause
when {
cause is HandleNotFoundException -> throw cause
cause is RuntimeException -> throw cause
f is ExecutionException ||
f is MessagingException -> throw f
else -> throw e
}
}
val handle = row.value(u.taskhandle, 1)!!
val remoteHandle = row.value(u.remotehandle, 2)!! as Handle<Unit>
val instanceFuture = ServletProcessEngineClient
.getProcessNodeInstance(
remoteHandle.handleValue,
SYSTEMPRINCIPAL,
null,
XmlTask::class.java,
Envelope::class.java
)
return transaction.value {
val instance: XmlProcessNodeInstance?
try {
instance = instanceFuture.get(TASK_LOOKUP_TIMEOUT_MILIS.toLong(), TimeUnit.MILLISECONDS)
} catch (e: ExecutionException) {
handleException(e)
} catch (e: MessagingException) {
handleException(e)
}
instance?.body?.let { body ->
val env = XML.decodeFromReader<Envelope<XmlTask>>(body.getXmlReader())
env.body.child.apply {
setHandleValue(handle.handleValue)
this.remoteHandle = remoteHandle
state = instance.state
}
}
XmlTask(handle.handleValue)
}
}
override fun createFromBuilder(
transaction: MonadicDBTransaction<UserTaskDB>,
setAccess: DBSetAccess<XmlTask>,
builder: XmlTask
): DBAction<UserTaskDB, XmlTask> {
return with(transaction) {
SELECT(nd.name, nd.data)
.WHERE { nd.taskhandle eq builder.handle }
.mapSingleOrNull { name, data ->
if (name!=null) builder[name]?.let { it.value = data }
builder
}.map { it!! }
}
}
override fun getPrimaryKeyCondition(where: _Where, instance: XmlTask): WhereClause =
getHandleCondition(where, instance.handle)
override fun getHandleCondition(where: _Where, handle: Handle<XmlTask>): WhereClause {
return with (where) { u.taskhandle eq handle }
}
override fun asInstance(obj: Any) = obj as? XmlTask
override fun insertStatement(transaction: MonadicDBTransaction<UserTaskDB>): ValuelessInsertAction<UserTaskDB, Insert> {
return transaction.INSERT(u.remotehandle)
}
override fun insertValues(
transaction: MonadicDBTransaction<UserTaskDB>,
insert: InsertActionCommon<UserTaskDB, Insert>,
value: XmlTask
): InsertAction<UserTaskDB, Insert> {
return insert.listVALUES(value.remoteHandle)
}
override fun store(update: _UpdateBuilder, value: XmlTask) {
update.run { SET(u.remotehandle, value.remoteHandle) }
}
override fun postStore(
transaction: MonadicDBTransaction<UserTaskDB>,
handle: Handle<XmlTask>,
oldValue: XmlTask?,
newValue: XmlTask
): DBAction<UserTaskDB, Boolean> {
val values = sequence {
for (item in newValue.items) {
val itemName = item.name
if (itemName != null && item.type != "label") {
oldValue?.getItem(itemName)?.let { oldItem ->
if (!(oldItem.value == null && item.value == null)) {
yield(item)
}
}
}
}
}
val insert = transaction.INSERT_OR_UPDATE(nd.taskhandle, nd.name, nd.data)
.VALUES(values) { item ->
VALUES(handle, item.name, item.value)
}
return insert.map { it.sum() > 0 }
}
override fun preClear(transaction: MonadicDBTransaction<UserTaskDB>): DBAction<UserTaskDB, Any> {
return transaction.DELETE_FROM(nd)
}
override fun preRemove(
transaction: MonadicDBTransaction<UserTaskDB>,
handle: Handle<XmlTask>
): DBAction<UserTaskDB, Boolean> {
return transaction.DELETE_FROM(nd).WHERE { nd.taskhandle eq handle }.map { it > 0 }
}
override fun preRemove(
transaction: MonadicDBTransaction<UserTaskDB>,
element: XmlTask
): DBAction<UserTaskDB, Boolean> {
return preRemove(transaction, element.handle)
}
override fun preRemove(
transaction: MonadicDBTransaction<UserTaskDB>,
columns: List<Column<*, *, *>>,
values: List<Any?>
): DBAction<UserTaskDB, Boolean> {
val handle = u.taskhandle.value(columns, values)
return preRemove(transaction, handle)
}
companion object {
private val TASK_LOOKUP_TIMEOUT_MILIS = 5
}
}
override fun containsRemoteHandle(
transaction: MonadicDBTransaction<UserTaskDB>,
remoteHandle: Handle<*>
): Handle<XmlTask>? {
return with(transaction) {
SELECT(u.taskhandle)
.WHERE { u.remotehandle eq remoteHandle }
.mapSeq { it.singleOrNull() }
.evaluateNow()
}
}
companion object {
val u = UserTaskDB.usertasks
val nd = UserTaskDB.nodedata
}
}
| lgpl-3.0 | 632929bd256cec90ff91eb67ef357a40 | 37.041667 | 128 | 0.596386 | 4.940476 | false | false | false | false |
sybila/CTL-Parser | src/main/java/com/github/sybila/huctl/DirFormula.kt | 1 | 4145 | package com.github.sybila.huctl
import com.github.sybila.Binary
import com.github.sybila.TreeNode
import com.github.sybila.Unary
/**
* Formulas that are used to describe the direction of the temporal path.
*
* They support basic boolean logic, direction propositions ("var+", "var-", etc.) and
* a special "loop" predicate, which indicates a self-loop transition.
*
* Note that each formula is either [Binary], [Unary] or an atomic proposition.
*/
sealed class DirFormula(
internal val string: String
) : TreeNode<DirFormula> {
/**
* Logical tautology - any path will match this restriction.
*/
object True : DirFormula("true") {
override fun toString(): String = string
}
/**
* Logical contradiction - no path will match this restriction.
*/
object False : DirFormula("false") {
override fun toString(): String = string
}
/**
* Special loop proposition - only a self-loop path matches this restriction.
*/
object Loop : DirFormula("loop"){
override fun toString(): String = string
}
/**
* General direction proposition. Contains a variable [name] and a requested [direction]
* (increase/up or decrease/down).
*/
data class Proposition(
/** The name of the variable in which the direction should hold. */
val name: String,
/** The direction in which the path should be moving (up/down). */
val direction: Direction
) : DirFormula("$name$direction") {
override fun toString(): String = string
}
/**
* A general purpose proposition that can contain any string value.
*/
data class Text(
/** The text value of this proposition. */
val value: String
) : DirFormula("\"$value\"") {
override fun toString(): String = string
}
// Used for alias resolution
internal data class Reference(val name: String) : DirFormula(name) {
override fun toString(): String = string
}
/**
* Logical negation. A path will match this restriction if it does not match the [inner] restriction.
*/
data class Not(override val inner: DirFormula) : DirFormula("!$inner"), Unary<Not, DirFormula> {
override fun toString(): String = string
}
/**
* Logical conjunction. A path will match this restriction only if it matches both [left] and [right]
* restrictions.
*/
data class And(
override val left: DirFormula, override val right: DirFormula
) : DirFormula("($left && $right)"), Binary<And, DirFormula> {
override fun toString(): String = string
}
/**
* Logical disjunction. A path will match this restriction only if it matches any of the [left] and [right]
* restrictions.
*/
data class Or(
override val left: DirFormula, override val right: DirFormula
) : DirFormula("($left || $right)"), Binary<Or, DirFormula> {
override fun toString(): String = string
}
/**
* Logical implication. A path will match this restriction only if does not match the [left] restriction
* or matches both [left] and [right] restriction.
*/
data class Implies(
override val left: DirFormula, override val right: DirFormula
) : DirFormula("($left -> $right)"), Binary<Implies, DirFormula> {
override fun toString(): String = string
}
/**
* Logical equivalence. A path will match this restriction either when it matches both [left] and [right]
* restriction or none of them.
*/
data class Equals(
override val left: DirFormula, override val right: DirFormula
) : DirFormula("($left <-> $right)"), Binary<Equals, DirFormula> {
override fun toString(): String = string
}
/**
* Return string which uniquely represents this formula and can be parsed to create an equivalent object.
*/
override fun toString(): String = string
/**
* DirFormula is also the node in the tree, so `node == this`
*/
override val node: DirFormula
get() = this
} | gpl-3.0 | 2fc269d91681b5f6340639f09440fb1c | 31.904762 | 111 | 0.628951 | 4.544956 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | example/src/main/java/org/wordpress/android/fluxc/example/OrderListAdapter.kt | 2 | 6021 | package org.wordpress.android.fluxc.example
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import org.wordpress.android.fluxc.example.WCOrderListItemUIType.LoadingItem
import org.wordpress.android.fluxc.example.WCOrderListItemUIType.SectionHeader
import org.wordpress.android.fluxc.example.WCOrderListItemUIType.WCOrderListUIItem
import org.wordpress.android.util.DateTimeUtils
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
private const val VIEW_TYPE_ORDER_ITEM = 0
private const val VIEW_TYPE_LOADING = 1
private const val VIEW_TYPE_SECTION_HEADER = 2
class OrderListAdapter : PagedListAdapter<WCOrderListItemUIType, ViewHolder>(OrderListDiffItemCallback) {
override fun getItemViewType(position: Int): Int {
return when (getItem(position)) {
is WCOrderListUIItem -> VIEW_TYPE_ORDER_ITEM
is LoadingItem -> VIEW_TYPE_LOADING
is SectionHeader -> VIEW_TYPE_SECTION_HEADER
null -> VIEW_TYPE_LOADING // Placeholder by paged list
}
}
@Suppress("UseCheckOrError")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return when (viewType) {
VIEW_TYPE_ORDER_ITEM -> WCOrderItemUIViewHolder(R.layout.list_item_woo_order, parent)
VIEW_TYPE_LOADING -> {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item_skeleton, parent, false)
LoadingViewHolder(view)
}
VIEW_TYPE_SECTION_HEADER -> SectionHeaderViewHolder(R.layout.list_item_section_header, parent)
else -> {
// Fail fast if a new view type is added so we can handle it
throw IllegalStateException("The view type '$viewType' needs to be handled")
}
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item = getItem(position)
if (holder is WCOrderItemUIViewHolder) {
assert(item is WCOrderListUIItem) {
"If we are presenting WCOrderItemUIViewHolder, the item has to be of type WCOrderListUIItem " +
"for position: $position"
}
holder.onBind((item as WCOrderListUIItem))
} else if (holder is SectionHeaderViewHolder) {
assert(item is SectionHeader) {
"If we are presenting SectionHeaderViewHolder, the item has to be of type SectionHeader " +
"for position: $position"
}
holder.onBind((item as SectionHeader))
}
}
}
/**
* 1. It looks like all the items are loading when only some of them are shown which triggers load more very early
* 2. Whenever the data changes it looks like the whole UI is refreshed regardless of if the item is changed or not
*/
private val OrderListDiffItemCallback = object : DiffUtil.ItemCallback<WCOrderListItemUIType>() {
override fun areItemsTheSame(oldItem: WCOrderListItemUIType, newItem: WCOrderListItemUIType): Boolean {
return when {
oldItem is SectionHeader && newItem is SectionHeader -> oldItem.title == newItem.title
oldItem is LoadingItem && newItem is LoadingItem -> oldItem.orderId == newItem.orderId
oldItem is WCOrderListUIItem && newItem is WCOrderListUIItem -> oldItem.orderId == newItem.orderId
oldItem is LoadingItem && newItem is WCOrderListUIItem -> oldItem.orderId == newItem.orderId
else -> false
}
}
override fun areContentsTheSame(oldItem: WCOrderListItemUIType, newItem: WCOrderListItemUIType): Boolean {
return when {
oldItem is SectionHeader && newItem is SectionHeader -> oldItem.title == newItem.title
oldItem is LoadingItem && newItem is LoadingItem -> oldItem.orderId == newItem.orderId
// AS is lying, it's not actually smart casting, so we have to do it :sigh:
oldItem is WCOrderListUIItem && newItem is WCOrderListUIItem -> oldItem == newItem
else -> false
}
}
}
private class WCOrderItemUIViewHolder(
@LayoutRes layout: Int,
parentView: ViewGroup
) : RecyclerView.ViewHolder(LayoutInflater.from(parentView.context).inflate(layout, parentView, false)) {
private val utcDateFormatter by lazy {
SimpleDateFormat("M/d/yy HH:mm:ss", Locale.ROOT).apply { timeZone = TimeZone.getTimeZone("UTC") }
}
private val orderNumberTv: TextView = itemView.findViewById(R.id.woo_order_number)
private val orderNameTv: TextView = itemView.findViewById(R.id.woo_order_name)
private val orderStatusTv: TextView = itemView.findViewById(R.id.woo_order_status)
private val orderTotalTv: TextView = itemView.findViewById(R.id.woo_order_total)
private val orderDateTv: TextView = itemView.findViewById(R.id.woo_order_date)
fun onBind(orderUIItem: WCOrderListUIItem) {
orderNumberTv.text = orderUIItem.orderNumber
orderNameTv.text = orderUIItem.orderName
orderStatusTv.text = orderUIItem.status
orderTotalTv.text = orderUIItem.orderTotal
val dateObj = DateTimeUtils.dateUTCFromIso8601(orderUIItem.dateCreated)
orderDateTv.text = utcDateFormatter.format(dateObj)
}
}
private class LoadingViewHolder(view: View) : RecyclerView.ViewHolder(view)
private class SectionHeaderViewHolder(
@LayoutRes layout: Int,
parentView: ViewGroup
) : RecyclerView.ViewHolder(LayoutInflater.from(parentView.context).inflate(layout, parentView, false)) {
private val titleTv: TextView = itemView.findViewById(R.id.section_header_title)
fun onBind(header: SectionHeader) {
titleTv.text = header.title.name
}
}
| gpl-2.0 | 84da2448075f05a84156314495fce991 | 46.409449 | 115 | 0.706527 | 4.52027 | false | false | false | false |
android/topeka | quiz/src/main/java/com/google/samples/apps/topeka/widget/quiz/MultiSelectQuizView.kt | 2 | 3072 | /*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.widget.quiz
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.AbsListView
import android.widget.AdapterView
import android.widget.ListView
import com.google.samples.apps.topeka.adapter.OptionsQuizAdapter
import com.google.samples.apps.topeka.helper.AnswerHelper
import com.google.samples.apps.topeka.model.Category
import com.google.samples.apps.topeka.model.quiz.MultiSelectQuiz
@SuppressLint("ViewConstructor")
class MultiSelectQuizView(
context: Context,
category: Category,
quiz: MultiSelectQuiz
) : AbsQuizView<MultiSelectQuiz>(context, category, quiz) {
private var listView: ListView? = null
override fun createQuizContentView(): View {
return ListView(context).apply {
listView = this
adapter = OptionsQuizAdapter(quiz.options,
android.R.layout.simple_list_item_multiple_choice)
choiceMode = AbsListView.CHOICE_MODE_MULTIPLE
itemsCanFocus = false
onItemClickListener = AdapterView.OnItemClickListener { _, _, _, _ ->
allowAnswer()
}
}
}
override val isAnswerCorrect: Boolean
get() {
val checkedItemPositions = listView?.checkedItemPositions
val answer = quiz.answer
return if (checkedItemPositions != null)
AnswerHelper.isAnswerCorrect(checkedItemPositions, answer)
else false
}
override var userInput: Bundle
get() = Bundle().apply { putBooleanArray(KEY_ANSWER, bundleableAnswer) }
set(savedInput) {
val answers = savedInput.getBooleanArray(KEY_ANSWER) ?: return
answers.indices.forEach { listView?.setItemChecked(it, answers[it]) }
}
private val bundleableAnswer: BooleanArray?
get() {
val checkedItemPositions = listView?.checkedItemPositions ?: return null
val answerSize = checkedItemPositions.size()
if (answerSize == 0) {
return null
}
val optionsSize = quiz.options.size
val bundleableAnswer = BooleanArray(optionsSize)
(0 until answerSize).forEach {
bundleableAnswer[checkedItemPositions.keyAt(it)] = checkedItemPositions.valueAt(it)
}
return bundleableAnswer
}
}
| apache-2.0 | 1bc95fd8ba5510ece9b3b3eb182d1c24 | 35.571429 | 99 | 0.674154 | 4.807512 | false | false | false | false |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/ui/code/RepositoryCodeFragment.kt | 5 | 10905 | /*
* Copyright (c) 2015 PocketHub
*
* 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.github.pockethub.android.ui.code
import android.app.Activity.RESULT_OK
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.text.bold
import androidx.core.text.buildSpannedString
import androidx.core.text.color
import androidx.recyclerview.widget.LinearLayoutManager
import com.github.pockethub.android.Intents.EXTRA_REPOSITORY
import com.github.pockethub.android.R
import com.github.pockethub.android.RequestCodes.REF_UPDATE
import com.github.pockethub.android.core.code.FullTree
import com.github.pockethub.android.core.code.FullTree.Folder
import com.github.pockethub.android.core.code.RefreshTreeTask
import com.github.pockethub.android.core.ref.RefUtils
import com.github.pockethub.android.rx.AutoDisposeUtils
import com.github.pockethub.android.ui.base.BaseActivity
import com.github.pockethub.android.ui.DialogResultListener
import com.github.pockethub.android.ui.base.BaseFragment
import com.github.pockethub.android.ui.item.code.BlobItem
import com.github.pockethub.android.ui.item.code.FolderItem
import com.github.pockethub.android.ui.item.code.PathHeaderItem
import com.github.pockethub.android.ui.ref.BranchFileViewActivity
import com.github.pockethub.android.ui.ref.RefDialog
import com.github.pockethub.android.ui.ref.RefDialogFragment
import com.github.pockethub.android.util.ToastUtils
import com.github.pockethub.android.util.android.text.clickable
import com.meisolsson.githubsdk.model.Repository
import com.meisolsson.githubsdk.model.git.GitReference
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.Item
import com.xwray.groupie.OnItemClickListener
import com.xwray.groupie.Section
import com.xwray.groupie.ViewHolder
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.fragment_repo_code.*
import kotlinx.android.synthetic.main.ref_footer.*
import java.util.LinkedList
/**
* Fragment to display a repository's source code tree
*/
class RepositoryCodeFragment : BaseFragment(), OnItemClickListener, DialogResultListener {
private val adapter = GroupAdapter<ViewHolder>()
private val mainSection = Section()
private var tree: FullTree? = null
private var folder: Folder? = null
private var repository: Repository? = null
private var dialog: RefDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
adapter.add(mainSection)
adapter.setOnItemClickListener(this)
repository = activity!!.intent.getParcelableExtra(EXTRA_REPOSITORY)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
if (tree == null || folder == null) {
refreshTree(null)
} else {
setFolder(tree, folder!!)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_refresh, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.m_refresh -> {
if (tree != null) {
val ref = GitReference.builder()
.ref(tree!!.reference.ref())
.build()
refreshTree(ref)
} else {
refreshTree(null)
}
true
}
else -> super.onOptionsItemSelected(item)
}
}
private fun showLoading(loading: Boolean) {
if (loading) {
pb_loading.visibility = View.VISIBLE
list.visibility = View.GONE
rl_branch.visibility = View.GONE
} else {
pb_loading.visibility = View.GONE
list.visibility = View.VISIBLE
rl_branch.visibility = View.VISIBLE
}
}
private fun refreshTree(reference: GitReference?) {
showLoading(true)
RefreshTreeTask(activity, repository, reference)
.refresh()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.`as`(AutoDisposeUtils.bindToLifecycle(this))
.subscribe({ fullTree ->
if (folder == null || folder!!.isRoot) {
setFolder(fullTree, fullTree.root)
} else {
// Look for current folder in new tree or else reset to root
var current: Folder = folder!!
val stack = LinkedList<Folder>()
while (!current.isRoot) {
stack.addFirst(current)
current = current.parent
}
var refreshed: Folder? = fullTree.root
while (!stack.isEmpty()) {
refreshed = refreshed!!.folders[stack.removeFirst().name]
if (refreshed == null) {
break
}
}
if (refreshed != null) {
setFolder(fullTree, refreshed)
} else {
setFolder(fullTree, fullTree.root)
}
}
}, { e ->
Log.d(TAG, "Exception loading tree", e)
showLoading(false)
ToastUtils.show(activity, R.string.error_code_load)
})
}
private fun switchBranches() {
if (tree == null) {
return
}
if (dialog == null) {
dialog = RefDialog(activity as BaseActivity?, REF_UPDATE, repository)
}
dialog!!.show(tree!!.reference)
}
override fun onDialogResult(requestCode: Int, resultCode: Int, arguments: Bundle) {
if (RESULT_OK != resultCode) {
return
}
when (requestCode) {
REF_UPDATE -> refreshTree(RefDialogFragment.getSelected(arguments))
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_repo_code, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
list.layoutManager = LinearLayoutManager(activity)
list.adapter = adapter
rl_branch.setOnClickListener { _ -> switchBranches() }
mainSection.setHeader(PathHeaderItem(""))
}
/**
* Back up the currently viewed folder to its parent
*
* @return true if directory changed, false otherwise
*/
fun onBackPressed(): Boolean {
return if (folder != null && !folder!!.isRoot) {
setFolder(tree, folder!!.parent)
true
} else {
false
}
}
private fun setFolder(tree: FullTree?, folder: Folder) {
this.folder = folder
this.tree = tree
showLoading(false)
tv_branch.text = tree!!.branch
if (RefUtils.isTag(tree.reference)) {
tv_branch_icon.setText(R.string.icon_tag)
} else {
tv_branch_icon.setText(R.string.icon_fork)
}
if (folder.entry != null) {
val textLightColor = resources.getColor(R.color.text_light)
val segments = folder.entry.path()!!.split("/")
val text = buildSpannedString {
bold {
clickable(onClick = {
setFolder(tree, tree.root)
}) {
append(repository!!.name()!!)
}
}
append(' ')
color(textLightColor) {
append('/')
}
append(' ')
for (i in 0 until segments.size - 1) {
clickable(onClick = {
var clicked: Folder? = folder
for (i1 in i until segments.size - 1) {
clicked = clicked!!.parent
if (clicked == null) {
return@clickable
}
}
setFolder(tree, clicked!!)
}) {
append(segments[i])
}
append(' ')
color(textLightColor) {
append('/')
}
append(' ')
}
bold {
append(segments[segments.size - 1])
}
append(' ')
color(textLightColor) {
append('/')
}
append(' ')
}
mainSection.setHeader(PathHeaderItem(text))
} else {
mainSection.removeHeader()
}
val items: List<Item<*>> =
folder.folders.values.map { FolderItem(it) } +
folder.files.values.map { BlobItem(activity!!, it) }
mainSection.update(items)
}
override fun onItemClick(item: Item<*>, view: View) {
if (tree == null) {
return
}
if (item is BlobItem) {
val entry = item.file
startActivity(BranchFileViewActivity.createIntent(
repository!!,
tree!!.branch,
entry.entry.path()!!,
entry.entry.sha()!!
))
} else if (item is FolderItem) {
val folder = item.folder
setFolder(tree, folder)
}
}
companion object {
private const val TAG = "RepositoryCodeFragment"
}
}
| apache-2.0 | e3137907b4c2a88ff149af24764dcc18 | 33.184953 | 90 | 0.566896 | 4.977179 | false | false | false | false |
debop/debop4k | debop4k-core/src/test/kotlin/debop4k/core/collections/permutations/ScanTest.kt | 1 | 1671 | /*
* Copyright (c) 2016. KESTI co, ltd
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package debop4k.core.collections.permutations
import debop4k.core.collections.permutations.samples.primes
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ScanTest : AbstractPermutationTest() {
@Test fun testInitialElementWithEmptySeq() {
val scanned: Permutation<Int> = emptyIntPermutation.scan(0) { acc, c -> acc + c }
assertThat(scanned).isEqualTo(permutationOf(0))
}
@Test fun testScannedFixedSeq() {
val fixed = permutationOf(1, 2, 3, 4)
val scanned = fixed.scan(0) { acc, c -> acc + c }
assertThat(scanned).isEqualTo(permutationOf(0, 1, 3, 6, 10))
}
@Test fun testScannedFixedSeqOfStrings() {
val fixed = continually("*").take(5)
val scanned = fixed.scan("") { acc, c -> acc + c }
assertThat(scanned).isEqualTo(permutationOf("", "*", "**", "***", "****", "*****"))
}
@Test fun testScanInfiniteSeq() {
val primes = primes()
val scanned = primes.scan(1) { acc, c -> acc * c }
assertThat(scanned.take(4)).isEqualTo(permutationOf(1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 5))
}
} | apache-2.0 | 0f2379dafe7c5e4ef96dc024f30d3cdd | 32.44 | 92 | 0.680431 | 3.680617 | false | true | false | false |
ageery/kwicket | kwicket-wicket-bootstrap-extensions/src/main/kotlin/org.kwicket.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime/KDatetimePickerWithIcon.kt | 1 | 3441 | package org.kwicket.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime.DatetimePickerConfig
import de.agilecoders.wicket.extensions.markup.html.bootstrap.form.datetime.DatetimePickerWithIcon
import org.apache.wicket.behavior.Behavior
import org.apache.wicket.extensions.markup.html.form.DateTextField
import org.apache.wicket.model.IModel
import org.kwicket.component.init
import org.kwicket.model.toDateModel
import java.sql.Date
import java.time.LocalDate
class KDatetimePickerWithIcon(
id: String,
model: IModel<LocalDate?>,
outputMarkupId: Boolean? = null,
outputMarkupPlaceholderTag: Boolean? = null,
visible: Boolean? = null,
enabled: Boolean? = null,
escapeModelStrings: Boolean? = null,
renderBodyOnly: Boolean? = null,
//val label: IModel<String>? = null,
//val required: Boolean? = null,
behaviors: List<Behavior>? = null,
format: String? = null,
useCurrent: Boolean? = null,
calendarWeeks: Boolean? = null,
stepping: Int? = null,
minDate: LocalDate? = null,
maxDate: LocalDate? = null,
defaultDate: LocalDate? = null,
viewMode: DatetimePickerConfig.ViewModeType? = null,
locale: String? = null,
showTodayButton: Boolean? = null,
showClose: Boolean? = null,
collapse: Boolean? = null,
sideBySide: Boolean? = null,
useStrict: Boolean? = null,
val newInput: ((DateTextField) -> DateTextField)? = null
) : DatetimePickerWithIcon(id, toDateModel(model), null) {
init {
init(
outputMarkupId = outputMarkupId,
outputMarkupPlaceholderTag = outputMarkupPlaceholderTag,
visible = visible,
enabled = enabled,
escapeModelStrings = escapeModelStrings,
renderBodyOnly = renderBodyOnly,
behaviors = behaviors
)
with(
DatetimePickerConfig().apply {
format?.let { withFormat(it) }
useCurrent?.let { useCurrent(it) }
calendarWeeks?.let { useCalendarWeeks(it) }
stepping?.let { withMinuteStepping(it) }
minDate?.let { withMinDate(Date.valueOf(it)) }
maxDate?.let { withMaxDate(Date.valueOf(it)) }
defaultDate?.let { withDefaultDate(Date.valueOf(it)) }
viewMode?.let { useView(it) }
locale?.let { useLocale(it) }
showTodayButton?.let { setShowToday(it) }
showClose?.let { setShowClose(it) }
collapse?.let { setCollapse(it) }
sideBySide?.let { useSideBySide(it) }
useStrict?.let { useStrictParsing(it) }
}
)
}
var input: DateTextField? = null
override fun newInput(wicketId: String, dateFormat: String): DateTextField =
super.newInput(wicketId, dateFormat)
.let { newInput?.invoke(it) ?: it }
.also { input = it }
// override fun newInput(wicketId: String?, dateFormat: String?): DateTextField? {
// if (newInput == null) super.newInput(wicketId, dateFormat)
// else newInput(wicketId, dateFormat, super.newInput(wicketId, dateFormat))
// input = super.newInput(wicketId, dateFormat)
// input?.init(
// label = label,
// required = required
// )
// return input
// }
} | apache-2.0 | 0fb91099130d2b5e6c2ff1ac26862cd2 | 37.674157 | 98 | 0.632084 | 4.216912 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/Moshi.kt | 1 | 2195 | package com.pr0gramm.app
import com.squareup.moshi.*
val MoshiInstance: Moshi = run {
removeClassJsonAdapter()
Moshi.Builder()
.adapter(InstantAdapter.nullSafe())
.adapter(Base64ByteArrayAdapter)
.adapter(BooleanAdapter)
.build()
}
inline fun <reified T : Any> Moshi.Builder.adapter(adapter: JsonAdapter<T>): Moshi.Builder {
T::class.javaPrimitiveType?.let { add(it, adapter) }
return add(T::class.java, adapter)
}
private object InstantAdapter : JsonAdapter<Instant>() {
override fun fromJson(reader: JsonReader): Instant {
return Instant.ofEpochSeconds(reader.nextLong())
}
override fun toJson(writer: JsonWriter, value: Instant?) {
if (value != null) {
writer.value(value.epochSeconds)
} else {
writer.nullValue()
}
}
}
private object Base64ByteArrayAdapter : JsonAdapter<ByteArray>() {
override fun fromJson(reader: JsonReader): ByteArray? {
if (reader.peek() == JsonReader.Token.NULL) {
return null
} else {
return reader.nextString().decodeBase64()
}
}
override fun toJson(writer: JsonWriter, value: ByteArray?) {
if (value == null) {
writer.nullValue()
} else {
writer.value(value.encodeBase64())
}
}
}
private object BooleanAdapter : JsonAdapter<Boolean>() {
override fun fromJson(reader: JsonReader): Boolean {
return when (reader.peek()) {
JsonReader.Token.NULL -> false
JsonReader.Token.BOOLEAN -> reader.nextBoolean()
JsonReader.Token.NUMBER -> reader.nextLong() != 0L
JsonReader.Token.STRING -> isTruthValue(reader.nextString())
else -> throw JsonDataException("tried to read boolean, but got ${reader.peek()}")
}
}
private fun isTruthValue(value: String?): Boolean {
return "true".equals(value, ignoreCase = true) || value == "1"
}
override fun toJson(writer: JsonWriter, value: Boolean?) {
if (value == null) {
writer.nullValue()
} else {
writer.value(value)
}
}
}
| mit | 36639a9fc69659b082b5b0d8225508af | 28.662162 | 94 | 0.601822 | 4.407631 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/ui/fragments/InboxFragment.kt | 1 | 5191 | package com.pr0gramm.app.ui.fragments
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.pr0gramm.app.Instant
import com.pr0gramm.app.R
import com.pr0gramm.app.api.pr0gramm.Message
import com.pr0gramm.app.databinding.FragmentInboxBinding
import com.pr0gramm.app.feed.FeedType
import com.pr0gramm.app.services.InboxService
import com.pr0gramm.app.services.ThemeHelper
import com.pr0gramm.app.services.UriHelper
import com.pr0gramm.app.ui.*
import com.pr0gramm.app.ui.base.BaseFragment
import com.pr0gramm.app.ui.base.bindViews
import com.pr0gramm.app.ui.fragments.conversation.StringValue
import com.pr0gramm.app.util.di.instance
import com.pr0gramm.app.util.observeChange
import java.util.concurrent.TimeUnit
/**
*/
abstract class InboxFragment(name: String) : BaseFragment(name, R.layout.fragment_inbox) {
protected val inboxService: InboxService by instance()
private val views by bindViews(FragmentInboxBinding::bind)
private var loadStartedTimestamp = Instant(0)
private lateinit var adapter: MessageAdapter
private lateinit var pagination: Pagination<Message>
private var state by observeChange(State()) { updateAdapterValues() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val (adapter, pagination) = getContentAdapter()
this.adapter = adapter
this.pagination = pagination
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
views.messages.itemAnimator = null
views.messages.layoutManager = LinearLayoutManager(activity)
views.messages.adapter = adapter
views.messages.addItemDecoration(MarginDividerItemDecoration(requireContext(), marginLeftDp = 72))
views.refresh.setOnRefreshListener { reloadInboxContent() }
views.refresh.setColorSchemeResources(ThemeHelper.accentColor)
pagination.updates.observe(viewLifecycleOwner) { (state, newValues) ->
handleStateUpdate(state, newValues)
}
}
override fun onResume() {
super.onResume()
// reload if re-started after one minute
if (loadStartedTimestamp.plus(1, TimeUnit.MINUTES).isBefore(Instant.now())) {
loadStartedTimestamp = Instant.now()
reloadInboxContent()
}
}
private fun reloadInboxContent() {
views.refresh.isRefreshing = false
// re-set state and re-start pagination
state = State()
pagination.initialize()
}
abstract fun getContentAdapter(): Pair<MessageAdapter, Pagination<Message>>
private fun handleStateUpdate(state: Pagination.State<Message>, newValues: List<Message>) {
this.state = this.state.copy(
messages = (this.state.messages + newValues).distinctBy { msg -> msg.id },
tailState = state.tailState)
}
private fun updateAdapterValues() {
val context = context ?: return
// build values for the recycler view
val values = state.messages.toMutableList<Any>()
// add the divider above the first read message, but only
// if we have at least one unread message
val dividerIndex = values.indexOfFirst { it is Message && it.read }
if (dividerIndex > 0) {
val divider = StringValue(context.getString(R.string.inbox_type_unread))
values.add(dividerIndex, divider)
}
// add common state values
addEndStateToValues(context, values, state.tailState, ifEmptyValue = MessageAdapter.EmptyValue)
adapter.submitList(values)
}
protected val actionListener: MessageActionListener = object : MessageActionListener {
override fun onAnswerToPrivateMessage(message: Message) {
ConversationActivity.start(context ?: return, message.name, skipInbox = true)
}
override fun onAnswerToCommentClicked(comment: Message) {
startActivity(WriteMessageActivity.answerToComment(context ?: return, comment))
}
override fun onNewPrivateMessage(userId: Long, name: String) {
startActivity(WriteMessageActivity.intent(context ?: return, userId, name))
}
override fun onCommentClicked(comment: Message) {
val uri = UriHelper.of(context ?: return).post(FeedType.NEW, comment.itemId, comment.id)
open(uri, comment.creationTime)
}
private fun open(uri: Uri, notificationTime: Instant? = null) {
val intent = Intent(Intent.ACTION_VIEW, uri, context, MainActivity::class.java)
intent.putExtra("MainActivity.NOTIFICATION_TIME", notificationTime)
startActivity(intent)
}
override fun onUserClicked(userId: Int, username: String) {
open(UriHelper.of(context ?: return).uploads(username))
}
}
data class State(
val messages: List<Message> = listOf(),
val tailState: Pagination.EndState<Message> = Pagination.EndState(hasMore = true))
}
| mit | 7547dda5601435668f2d14522adbf83a | 36.078571 | 106 | 0.696012 | 4.561511 | false | false | false | false |
Finnerale/FileBase | src/main/kotlin/de/leopoldluley/filebase/controller/DataCtrl.kt | 1 | 6103 | package de.leopoldluley.filebase.controller
import de.leopoldluley.filebase.Extensions.containsOneOf
import de.leopoldluley.filebase.Utils
import de.leopoldluley.filebase.Utils.joinTags
import de.leopoldluley.filebase.Utils.splitTags
import de.leopoldluley.filebase.models.Entry
import de.leopoldluley.filebase.models.FileType
import de.leopoldluley.filebase.models.EntryMeta
import tornadofx.*
import java.nio.file.Files
import java.nio.file.Path
import java.time.Duration
import java.time.Instant
import java.time.temporal.TemporalAmount
class DataCtrl : Controller() {
private val baseCtrl: BaseCtrl by inject()
private val fileCtrl: FileCtrl by inject()
private val settingsCtrl: SettingsCtrl by inject()
val tags = mutableListOf<String>().observable()
val entries = mutableListOf<Entry >().observable()
val addQueue = mutableListOf<Path >().observable()
val history = mutableListOf<Entry >().observable()
private val metaData = mutableMapOf<Int, EntryMeta>()
init {
val history = settingsCtrl.history
for (it in history) {
val entry = baseCtrl.queryEntry(it)
if (entry == null) {
settingsCtrl.historyProperty.remove(it)
} else {
this.history.add(entry)
}
}
entries.addAll(this.history)
}
fun getMetaData(entry: Entry): EntryMeta {
if (metaData.containsKey(entry.id) && metaData[entry.id]!!.timestamp.isBefore(Instant.now().minus(Duration.ofSeconds(60*3)))) {
metaData.remove(entry.id)
}
if (!metaData.containsKey(entry.id)) {
val file = fileCtrl.getPathFor(entry)
val datetime = Files.getLastModifiedTime(file).toInstant()
val filesize = Files.size(file)
metaData[entry.id] = EntryMeta(filesize, datetime, Instant.now())
}
return metaData[entry.id]!!
}
fun pushToHistory(entry: Entry) {
if (history.contains(entry)) {
history.remove(entry)
settingsCtrl.historyProperty.remove(entry.id)
}
history.add(0, entry)
if (history.size > settingsCtrl.historyLength) {
history.remove(settingsCtrl.historyLength, history.size)
}
settingsCtrl.historyProperty.add(0, entry.id)
if (settingsCtrl.history.size > settingsCtrl.historyLength) {
settingsCtrl.historyProperty.remove(settingsCtrl.historyLength, settingsCtrl.history.size)
}
}
fun queryTags() {
tags.clear()
tags.addAll(getTags())
}
fun queryEntries(name: String, tags: String, type: FileType) {
entries.clear()
entries.addAll(query(name, tags, type))
}
fun createEntry(struct: Entry, move: Boolean): Boolean {
val filename = fileCtrl.createFileOf(struct, move)
if (filename != null) {
val tags = splitTags(struct.tags.toLowerCase().trim())
val entry = Entry()
entry.name = struct.name.trim()
entry.tags = joinTags(tags)
entry.file = filename
entry.type = struct.type
entry.note = struct.note
if (baseCtrl.insertEntry(entry)) {
addTags(tags)
} else {
fileCtrl.deleteFileOf(struct)
}
return true
}
return false
}
fun updateEntry(entry: Entry): Boolean {
entry.tags = joinTags(splitTags(entry.tags))
if (baseCtrl.updateEntry(entry)) {
entries.find { it.id == entry.id }?.apply {
name = entry.name
tags = entry.tags
type = entry.type
note = entry.note
}
addTags(splitTags(entry.tags))
return true
}
return false
}
fun deleteEntry(entry: Entry) = baseCtrl.deleteEntry(entry) && fileCtrl.deleteFileOf(entry) && entries.remove(entry)
fun query(name: String = "", search: String = "", type: FileType = FileType.NONE): List<Entry> =
if (search.isBlank() && name.isBlank() && type == FileType.NONE) {
baseCtrl.queryAllEntries()
} else {
val tags = Utils.splitTags(search)
baseCtrl.queryEntries(name, tags, type)
}
fun getTags(): List<String> {
return baseCtrl.queryAllTags()
}
fun addTags(tags: List<String>) {
tags.forEach {
if(baseCtrl.insertTag(it) && !this.tags.contains(it)) {
this.tags.add(it)
}
}
}
fun deleteTag(name: String): Boolean {
if(baseCtrl.deleteTag(name)) {
val tagged = baseCtrl.queryEntries(tags = listOf(name))
tagged.forEach {
it.tags = joinTags(splitTags(it.tags).filter { it != name })
baseCtrl.updateEntry(it)
}
tags.remove(name)
entries.forEach {
it.tags = joinTags(splitTags(it.tags.replace(name, "")))
}
return true
}
return false
}
fun updateTag(old: String, new: String): Boolean {
if(baseCtrl.updateTag(old, new)) {
val tagged = baseCtrl.queryEntries(tags = listOf(old))
tagged.forEach {
it.tags = joinTags(splitTags(it.tags).map { if (it == old) new else it })
baseCtrl.updateEntry(it)
}
tags.replaceAll { if (it == old) new else it }
entries.forEach {
it.tags = joinTags(splitTags(it.tags.replace(old, new)))
}
return true
}
return false
}
fun checkFileName(name: String, unique: Boolean = true): Boolean {
if (name.containsOneOf('\'', '/', '\\')) return false
if (unique) {
query(name).forEach {
if (it.name == name)
return false
}
}
return fileCtrl.testFileName(name)
}
fun checkTagName(name: String): Boolean {
return !name.contains('\'')
}
} | mit | 0925670ac5e8e5cb7b28416473cce40b | 31.126316 | 135 | 0.580862 | 4.217692 | false | false | false | false |
lfkdsk/JustDB | src/utils/parsertools/combinators/tree/Leaf.kt | 1 | 1134 | package utils.parsertools.combinators.tree
import utils.parsertools.ast.AstLeaf
import utils.parsertools.ast.AstNode
import utils.parsertools.ast.Token
import utils.parsertools.combinators.Element
import utils.parsertools.exception.ParseException
import utils.parsertools.lex.Lexer
/**
* Created by liufengkai on 2017/4/24.
*
* @author ice1000
* @author lfkdsk
*/
open class Leaf(val tokens: List<String>) : Element {
override fun parse(lexer: Lexer, nodes: MutableList<AstNode>) {
val token = lexer.nextToken()
if (token.isIdentifier()) {
tokens.filter { it == token.text }
.forEach {
find(nodes, token)
return
}
}
if (tokens.count() > 0) {
throw ParseException(tokens[0] + " expected. ", token)
} else {
throw ParseException("", token)
}
}
/**
* 添加终结符
* @param list list
* *
* @param token 终结符对应token
*/
protected open fun find(list: MutableList<AstNode>, token: Token) {
list.add(AstLeaf(token))
}
override fun match(lexer: Lexer): Boolean {
val token = lexer[0]
return token.isIdentifier() && tokens.any { it == token.text }
}
} | apache-2.0 | 70d8e0a9bdccd4768c18dbcc48e51ef5 | 20.037736 | 68 | 0.681329 | 3.365559 | false | false | false | false |
DSolyom/ViolinDS | ViolinDS/app/src/main/java/ds/violin/v1/model/entity/ContinuousList.kt | 1 | 6812 | /*
Copyright 2016 Dániel Sólyom
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 ds.violin.v1.model.entity
import ds.violin.v1.datasource.base.DataLoading
import ds.violin.v1.model.modeling.*
import ds.violin.v1.util.common.JSONArrayWrapper
import java.io.Serializable
interface ContinuousListDataLoading : DataLoading {
fun setupLoadFor(list: ContinuousListing<*, *>, offset: Int, pageSize: Int) {
loadingParams["offset"] = offset
loadingParams["page_size"] = pageSize
}
}
interface ContinuousListing<LIST, MODEL_TYPE> : SelfLoadableListModeling<LIST, MODEL_TYPE> {
/** should be at least 3 times higher than elements can be on screen at once - no checks! */
var pageSize: Int
var offset: Int
/** should be at least 4 times of [pageSize] - no checks! */
var maxSizeInMemory: Int?
/** =null - presumed size of the list - the max item count if set to anything than null */
var presumedSize: Int?
/** =true, #Private */
var firstLoad: Boolean
/** =true, #Private */
var loadingForward: Boolean
/** =0, #ProtectedGet, #PrivateSet - size change of last load (@see [loadNext] [loadPrevious] */
var sizeChange: Int
/** =0, #ProtectedGet, #PrivateSet - offset change of last load (@see [loadNext] [loadPrevious] */
var offsetChange: Int
fun initLoader() {
if (dataLoader !is ContinuousListDataLoading) {
throw IllegalArgumentException("dataLoader must implement ContinuousListDataLoading")
}
(dataLoader as ContinuousListDataLoading).setupLoadFor(
this, offset, pageSize
)
}
fun get(position: Int, completion: (entity: SelfLoadable, error: Throwable?) -> Unit): MODEL_TYPE? {
when {
position + 1 > size - pageSize / 3 -> loadNext(completion)
position - 1 < pageSize / 3 -> loadPrevious(completion)
}
return get(position)
}
override fun invalidate() {
firstLoad = true
super.invalidate()
}
override fun load(completion: (entity: SelfLoadable, error: Throwable?) -> Unit): Boolean {
if (firstLoad) {
initLoader()
firstLoad = false
}
return super.load(completion)
}
fun loadNext(completion: (entity: SelfLoadable, error: Throwable?) -> Unit): Boolean {
if (!valid || !hasNext() || dataLoader.loading) {
// list is not valid or already at the end
return false
}
loadingForward = true
(dataLoader as ContinuousListDataLoading).setupLoadFor(
this, offset + size, pageSize
)
/** only invalid [SelfLoadable] can be loaded */
valid = false
val loading = load(completion)
valid = true
return loading
}
fun hasNext(): Boolean {
return (presumedSize == null || offset + size < presumedSize!!)
}
fun loadPrevious(completion: (entity: SelfLoadable, error: Throwable?) -> Unit): Boolean {
if (!valid || offset == 0 || dataLoader.loading) {
// list is not valid or already at start
return false
}
loadingForward = false
val nextOffset = when {
offset > pageSize -> offset - pageSize
else -> 0
}
val nextPageSize = when {
nextOffset > 0 -> pageSize
else -> offset
}
(dataLoader as ContinuousListDataLoading).setupLoadFor(
this, nextOffset, nextPageSize
)
/** only invalid [SelfLoadable] can be loaded */
valid = false
val loading = load(completion)
valid = true
return loading
}
}
interface ContinuousMutableListing<L, T> : ContinuousListing<L, T> {
override fun onDataLoaded(result: Any?, error: Throwable?,
completion: (entity: SelfLoadable, error: Throwable?) -> Unit) {
if (!valid && error == null) {
/** list got invalidated - need to clear before adding the results */
clear()
}
if (size == 0 || error != null) {
// first load or at least doesn't matter
super.onDataLoaded(result, error, completion)
if (size < pageSize) {
// also loaded last ones
presumedSize = size
}
return
}
// got only new parts here
var newParts: L
try {
newParts = when (result) {
is ListModeling<*, *> -> result.values as L
else -> result as L
}
} catch(e: Throwable) {
valid = false
completion(this, e)
return
}
val oldSize = size
when (loadingForward) {
true -> {
// add new modelings
addAll(newParts)
if (size - oldSize < pageSize) {
// newParts's size = size - oldSize
// loaded last ones
presumedSize = offset + size
}
// need to remove from top?
offsetChange = when {
maxSizeInMemory == null -> 0
size > maxSizeInMemory!! -> pageSize * 2
else -> 0
}
if (offsetChange > 0) {
// remove {@var offsetChange} elements from the top of the list
remove(0, offsetChange)
// and modify offset
offset += offsetChange
}
}
false -> {
// add new modelings
addAll(0, newParts)
val newPartsSize = size - oldSize
offsetChange = -newPartsSize
offset += offsetChange
// remove from bottom of the list if needed
val toRemove = when {
maxSizeInMemory != null -> (size - maxSizeInMemory!!) * 2
else -> 0
}
if (toRemove > 0) {
remove(size - toRemove, toRemove)
}
}
}
sizeChange = size - oldSize
completion(this, error)
}
}
| apache-2.0 | 4cb1f4cb174b276c52c25e650c884707 | 28.102564 | 104 | 0.552717 | 4.78903 | false | false | false | false |
cloose/luftbild4p3d | src/main/kotlin/org/luftbild4p3d/p3d/ScenProcBatchProcess.kt | 1 | 1071 | package org.luftbild4p3d.p3d
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
import org.luftbild4p3d.app.WorkFolder
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
class ScenProcBatchProcess {
companion object {
fun run(osmFileName: String, workFolder: WorkFolder, subscriber: (String) -> Unit) {
val process = ProcessBuilder("D:\\Programme\\scenproc_latest_development_release_x64\\scenProc.exe", "autogen_script.spc", "/run", "$osmFileName").redirectErrorStream(true).directory(File(workFolder.name)).start()
val outputReader = BufferedReader(InputStreamReader(process.inputStream))
Observable.create<String> {
var line = outputReader.readLine()
while (line != null) {
it.onNext(line)
line = outputReader.readLine()
}
it.onComplete()
}.subscribeOn(Schedulers.single()).subscribe(subscriber)
process.waitFor()
}
}
} | gpl-3.0 | dfc82af200ec5ea4df107dbdf754edd8 | 33.580645 | 225 | 0.64986 | 4.318548 | false | false | false | false |
natanieljr/droidmate | project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/strategy/login/LoginWithGoogle.kt | 1 | 5318 | // DroidMate, an automated execution generator for Android apps.
// Copyright (C) 2012-2018. Saarland University
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Current Maintainers:
// Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland>
// Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland>
//
// Former Maintainers:
// Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de>
//
// web: www.droidmate.org
package org.droidmate.exploration.strategy.login
import org.droidmate.deviceInterface.exploration.ExplorationAction
import org.droidmate.exploration.ExplorationContext
import org.droidmate.explorationModel.interaction.Widget
import org.droidmate.exploration.actions.click
import org.droidmate.exploration.strategy.AExplorationStrategy
import org.droidmate.explorationModel.factory.AbstractModel
import org.droidmate.explorationModel.interaction.State
import java.lang.RuntimeException
@Suppress("unused")
class LoginWithGoogle : AExplorationStrategy() {
override fun getPriority(): Int {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private val DEFAULT_ACTION_DELAY = 1000
private val RES_ID_PACKAGE = "com.google.android.gms"
private val RES_ID_ACCOUNT = "$RES_ID_PACKAGE:uid/account_display_name"
private val RES_ID_ACCEPT = "$RES_ID_PACKAGE:uid/accept_button"
private var state = LoginState.Start
private fun canClickGoogle(widgets: List<Widget>): Boolean {
return (this.state == LoginState.Start) &&
widgets.any { it.text.toLowerCase() == "google" }
}
private fun clickGoogle(widgets: List<Widget>): ExplorationAction {
val widget = widgets.firstOrNull { it.text.toLowerCase() == "google" }
if (widget != null) {
this.state = LoginState.AccountDisplayed
return widget.click()
}
throw RuntimeException("The exploration shouldn' have reached this point.")
}
private fun canClickAccount(widgets: List<Widget>): Boolean {
return widgets.any { it.resourceId == RES_ID_ACCOUNT }
}
private fun clickAccount(widgets: List<Widget>): ExplorationAction {
val widget = widgets.firstOrNull { it.resourceId == RES_ID_ACCOUNT }
if (widget != null) {
this.state = LoginState.AccountSelected
return widget.click()
}
throw RuntimeException("The exploration shouldn' have reached this point.")
}
private fun canClickAccept(widgets: List<Widget>): Boolean {
return widgets.any { it.resourceId == RES_ID_ACCEPT }
}
private fun clickAccept(widgets: List<Widget>): ExplorationAction {
val widget = widgets.firstOrNull { it.resourceId == RES_ID_ACCEPT }
if (widget != null) {
this.state = LoginState.Done
return widget.click()
}
throw RuntimeException("The exploration shouldn' have reached this point.")
}
/*override fun mustPerformMoreActions(): Boolean {
return !eContext.getCurrentState().widgets
.any {
it.definedAsVisible &&
it.resourceId == RES_ID_ACCOUNT
}
}*/
// TODO
/*override fun getFitness(): StrategyPriority {
// Not the correct app, or already logged in
if (this.state == LoginState.Done)
return StrategyPriority.NONE
val widgets = eContext.getCurrentState().actionableWidgets
if (canClickGoogle(widgets) ||
canClickAccount(widgets) ||
canClickAccept(widgets))
return StrategyPriority.SPECIFIC_WIDGET
return StrategyPriority.NONE
}*/
private fun getWidgetAction(widgets: List<Widget>): ExplorationAction {
// Can click on login
return when {
canClickGoogle(widgets) -> clickGoogle(widgets)
canClickAccount(widgets) -> clickAccount(widgets)
canClickAccept(widgets) -> clickAccept(widgets)
else -> throw RuntimeException("Should not have reached this point. $widgets")
}
}
override suspend fun <M : AbstractModel<S, W>, S : State<W>, W : Widget> computeNextAction(eContext: ExplorationContext<M, S, W>): ExplorationAction {
return if (eContext.getCurrentState().isRequestRuntimePermissionDialogBox) {
val widget = eContext.getCurrentState().widgets.let { widgets ->
widgets.firstOrNull { it.resourceId == "com.android.packageinstaller:id/permission_allow_button" }
?: widgets.first { it.text.toUpperCase() == "ALLOW" }
}
widget.click()
} else {
val widgets = eContext.getCurrentState().widgets
getWidgetAction(widgets)
}
}
override fun equals(other: Any?): Boolean {
return other is LoginWithGoogle
}
override fun hashCode(): Int {
return this.RES_ID_PACKAGE.hashCode()
}
override fun toString(): String {
return javaClass.simpleName
}
companion object {
/**
* Creates a new exploration strategy instance to login using google
*/
fun build(): AExplorationStrategy {
return LoginWithGoogle()
}
}
} | gpl-3.0 | d90407dbd4a2376e0375203d4190150c | 31.631902 | 151 | 0.737683 | 3.910294 | false | false | false | false |
dafi/photoshelf | tumblr-ui-core/src/main/java/com/ternaryop/photoshelf/tumblr/ui/core/adapter/PhotoShelfPost.kt | 1 | 1305 | package com.ternaryop.photoshelf.tumblr.ui.core.adapter
import android.text.format.DateUtils.SECOND_IN_MILLIS
import com.ternaryop.tumblr.TumblrPhotoPost
import com.ternaryop.utils.date.APPEND_DATE_FOR_PAST_AND_PRESENT
import com.ternaryop.utils.date.formatPublishDaysAgo
/**
* The last published time can be in the future if the post is scheduled
*/
class PhotoShelfPost(photoPost: TumblrPhotoPost, var lastPublishedTimestamp: Long) : TumblrPhotoPost(photoPost) {
var groupId: Int = 0
val scheduleTimeType: ScheduleTime
get() = when {
lastPublishedTimestamp == java.lang.Long.MAX_VALUE -> ScheduleTime.POST_PUBLISH_NEVER
lastPublishedTimestamp > System.currentTimeMillis() -> ScheduleTime.POST_PUBLISH_FUTURE
else -> ScheduleTime.POST_PUBLISH_PAST
}
val lastPublishedTimestampAsString: String
get() {
val tt = if (scheduledPublishTime > 0) scheduledPublishTime * SECOND_IN_MILLIS else lastPublishedTimestamp
return tt.formatPublishDaysAgo(APPEND_DATE_FOR_PAST_AND_PRESENT)
}
enum class ScheduleTime {
POST_PUBLISH_NEVER,
POST_PUBLISH_FUTURE,
POST_PUBLISH_PAST
}
companion object {
private const val serialVersionUID = -6670033021694674250L
}
}
| mit | 9b8b5c885b7945c39adb1b8c10647226 | 35.25 | 118 | 0.714943 | 4.196141 | false | false | false | false |
cout970/Magneticraft | src/main/kotlin/com/cout970/magneticraft/api/internal/registries/machines/grinder/GrinderRecipe.kt | 2 | 1463 | package com.cout970.magneticraft.api.internal.registries.machines.grinder
import com.cout970.magneticraft.api.internal.ApiUtils
import com.cout970.magneticraft.api.registries.machines.grinder.IGrinderRecipe
import com.cout970.magneticraft.misc.inventory.isNotEmpty
import net.minecraft.item.ItemStack
import net.minecraftforge.oredict.OreDictionary
/**
* Created by cout970 on 22/08/2016.
*/
data class GrinderRecipe(
private val input: ItemStack,
private val primaryOutput: ItemStack,
private val secondaryOutput: ItemStack,
private val prob: Float,
private val ticks: Float,
private val oreDict: Boolean
) : IGrinderRecipe {
init {
require(input.isNotEmpty) { "Input MUST be a non-empty stack" }
}
override fun useOreDictionaryEquivalencies(): Boolean = oreDict
override fun getInput(): ItemStack = input.copy()
override fun getPrimaryOutput(): ItemStack = primaryOutput.copy()
override fun getSecondaryOutput(): ItemStack = secondaryOutput.copy()
override fun getProbability(): Float = prob
override fun getDuration(): Float = ticks
override fun matches(input: ItemStack): Boolean {
if (input.isEmpty) return false
if (ApiUtils.equalsIgnoreSize(input, this.input)) return true
if (oreDict) {
val ids = OreDictionary.getOreIDs(this.input)
return OreDictionary.getOreIDs(input).any { it in ids }
}
return false
}
} | gpl-2.0 | 355a2312aff06c1c641b23bdcd7c2b54 | 30.826087 | 78 | 0.720437 | 4.406627 | false | false | false | false |
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/impl/fragment/FragmentCenter.kt | 1 | 2867 | package com.xiaojinzi.component.impl.fragment
import com.xiaojinzi.component.Component.getApplication
import com.xiaojinzi.component.Component.requiredConfig
import com.xiaojinzi.component.ComponentUtil
import com.xiaojinzi.component.anno.support.CheckClassNameAnno
import com.xiaojinzi.component.fragment.IComponentCenterFragment
import com.xiaojinzi.component.fragment.IComponentHostFragment
import com.xiaojinzi.component.support.ASMUtil
import com.xiaojinzi.component.support.Utils
import java.util.*
/**
* 模块 Fragment 注册和卸载的总管
*
* @author xiaojinzi
*/
@CheckClassNameAnno
object FragmentCenter: IComponentCenterFragment {
private val moduleFragmentMap: MutableMap<String, IComponentHostFragment> = HashMap()
override fun register(hostFragment: IComponentHostFragment) {
Utils.checkNullPointer(hostFragment)
if (!moduleFragmentMap.containsKey(hostFragment.host)) {
moduleFragmentMap[hostFragment.host] = hostFragment
hostFragment.onCreate(getApplication())
}
}
override fun register(host: String) {
Utils.checkStringNullPointer(host, "host")
if (!moduleFragmentMap.containsKey(host)) {
val moduleService = findModuleService(host)
moduleService?.let { register(it) }
}
}
override fun unregister(hostFragment: IComponentHostFragment) {
Utils.checkNullPointer(hostFragment)
moduleFragmentMap.remove(hostFragment.host)
hostFragment.onDestroy()
}
override fun unregister(host: String) {
Utils.checkStringNullPointer(host, "host")
val moduleService = moduleFragmentMap[host]
moduleService?.let { unregister(it) }
}
fun findModuleService(host: String?): IComponentHostFragment? {
try {
return if (requiredConfig().isOptimizeInit) {
ASMUtil.findModuleFragmentAsmImpl(
ComponentUtil.transformHostForClass(host)
)
} else {
var clazz: Class<out IComponentHostFragment?>? = null
val className = ComponentUtil.genHostFragmentClassName(host)
clazz = Class.forName(className) as Class<out IComponentHostFragment>
clazz.newInstance()
}
} catch (ignore: Exception) {
// ignore
}
return null
}
fun check() {
val set: MutableSet<String> = HashSet()
for ((_, childRouter) in moduleFragmentMap) {
if (childRouter?.fragmentNameSet == null) {
continue
}
val childRouterSet = childRouter.fragmentNameSet
for (key in childRouterSet) {
check(!set.contains(key)) { "the name of Fragment is exist:'$key'" }
set.add(key)
}
}
}
} | apache-2.0 | 506b809b00366a2dd8b04371186a0ec8 | 33.289157 | 89 | 0.655185 | 4.813875 | false | false | false | false |
kesco/SlideBack-Xposed | app/src/main/kotlin/com/kesco/adk/rx/WorkThreadScheduler.kt | 1 | 3316 | package com.kesco.adk.rx
import android.os.Process
import rx.Scheduler
import rx.Subscription
import rx.functions.Action0
import rx.internal.schedulers.ScheduledAction
import rx.plugins.RxJavaPlugins
import rx.subscriptions.CompositeSubscription
import rx.subscriptions.MultipleAssignmentSubscription
import rx.subscriptions.Subscriptions
import java.util.concurrent.ConcurrentLinkedQueue
import java.util.concurrent.RejectedExecutionException
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
public class WorkThreadScheduler(val executor: ScheduledExecutorService) : Scheduler() {
override fun createWorker(): Scheduler.Worker = ThreadWorker(executor)
class ThreadWorker(val executor: ScheduledExecutorService) : Scheduler.Worker(), Runnable {
val tasks: CompositeSubscription = CompositeSubscription()
val queue: ConcurrentLinkedQueue<ScheduledAction> = ConcurrentLinkedQueue()
val count: AtomicInteger = AtomicInteger()
override fun unsubscribe() = tasks.unsubscribe()
override fun isUnsubscribed(): Boolean = tasks.isUnsubscribed()
override fun schedule(action: Action0): Subscription {
if (isUnsubscribed) {
return Subscriptions.unsubscribed()
}
val sa = ScheduledAction(action, tasks)
tasks.add(sa)
queue.offer(sa)
if (count.getAndIncrement() == 0) {
try {
executor.execute(this)
} catch(e: RejectedExecutionException) {
tasks.remove(sa)
count.decrementAndGet()
RxJavaPlugins.getInstance().getErrorHandler().handleError(e)
throw e
}
}
return sa
}
override fun schedule(action: Action0, delayTime: Long, unit: TimeUnit): Subscription {
if (delayTime <= 0) return schedule(action)
if (isUnsubscribed) return Subscriptions.unsubscribed()
val first = MultipleAssignmentSubscription()
val mas = MultipleAssignmentSubscription()
mas.set(first)
tasks.add(mas)
val removeMas = Subscriptions.create { tasks.remove(mas) }
val ea = ScheduledAction {
if (!mas.isUnsubscribed()) {
val s2 = schedule(action)
mas.set(s2)
(s2 as? ScheduledAction)?.add(removeMas)
}
}
first.set(ea);
try {
val f = executor.schedule(ea, delayTime, unit)
ea.add(f)
} catch (t: RejectedExecutionException) {
RxJavaPlugins.getInstance().getErrorHandler().handleError(t)
throw t
}
return removeMas;
}
override fun run() {
// TODO: 统一在线程池内设置线程优先级
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND)
do {
val sa = queue.poll()
if (!sa.isUnsubscribed()) {
sa.run()
}
} while (count.decrementAndGet() > 0)
}
}
}
| mit | 2cd965c8ba3827388a36a5e5dab19891 | 34.73913 | 95 | 0.601277 | 5.286174 | false | false | false | false |
U1F4F1/PowerBottomSheet | powerbottomsheet/src/main/java/com/u1f4f1/powerbottomsheet/coordinatorlayoutbehaviors/TabletAnchorPointBottomSheetBehavior.kt | 1 | 5369 | package com.u1f4f1.powerbottomsheet.coordinatorlayoutbehaviors
import android.content.Context
import android.os.Parcelable
import android.support.design.widget.CoordinatorLayout
import android.support.v4.view.ViewCompat
import android.util.AttributeSet
import android.view.View
import com.u1f4f1.powerbottomsheet.bottomsheet.BottomSheetState
import com.u1f4f1.powerbottomsheet.bottomsheet.SavedState
class TabletAnchorPointBottomSheetBehavior<V : View>(context: Context, attrs: AttributeSet?) : AnchorPointBottomSheetBehavior<V>(context, attrs) {
override fun onRestoreInstanceState(parent: CoordinatorLayout?, child: V?, state: Parcelable?) {
val ss = state as SavedState
// Intermediate states are restored as the anchored state, collapse state is ignored
if (ss.bottomSheetState == BottomSheetState.STATE_DRAGGING.id || ss.bottomSheetState == BottomSheetState.STATE_SETTLING.id || ss.bottomSheetState == BottomSheetState.STATE_COLLAPSED.id) {
this.state = BottomSheetState.STATE_ANCHOR_POINT
attemptToActivateBottomsheet(child!!)
} else {
this.state = BottomSheetState.fromInt(ss.bottomSheetState)
}
lastStableState = this.state
}
override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray, type: Int) {
attemptToActivateBottomsheet(child)
val scrollingChild = nestedScrollingChildRef!!.get()
if (target !== scrollingChild) {
return
}
val currentTop = child.top
val newTop = currentTop - dy
// Force stop at the anchor - do not collapse
if (lastStableState === BottomSheetState.STATE_ANCHOR_POINT && newTop > anchorPoint) {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, anchorPoint - currentTop)
dispatchOnSlide(child.top)
nestedScrolled = true
return
}
if (dy > 0) { // Upward
if (newTop < minOffset) {
consumed[1] = currentTop - minOffset
ViewCompat.offsetTopAndBottom(child, -consumed[1])
setStateInternal(BottomSheetState.STATE_EXPANDED)
} else {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, -dy)
setStateInternal(BottomSheetState.STATE_DRAGGING)
}
} else if (dy < 0) { // Downward
if (!target.canScrollVertically(-1)) {
if (newTop <= maxOffset || isHideable) {
consumed[1] = dy
ViewCompat.offsetTopAndBottom(child, -dy)
setStateInternal(BottomSheetState.STATE_DRAGGING)
} else {
consumed[1] = currentTop - maxOffset
ViewCompat.offsetTopAndBottom(child, -consumed[1])
setStateInternal(BottomSheetState.STATE_ANCHOR_POINT)
}
}
}
dispatchOnSlide(child.top)
lastNestedScrollDy = dy
nestedScrolled = true
}
/**
* Takes a [State] and returns the next stable state as the bottom sheet expands
* @param currentState the last stable state of the bottom sheet
* *
* @return the next stable state that the sheet should settle at
*/
override fun getNextStableState(currentState: BottomSheetState): BottomSheetState {
when (currentState) {
BottomSheetState.STATE_HIDDEN -> return BottomSheetState.STATE_ANCHOR_POINT
BottomSheetState.STATE_ANCHOR_POINT -> return BottomSheetState.STATE_EXPANDED
else -> return currentState
}
}
/**
* Takes a [State] and returns the next stable state as the bottom sheet contracts
* @param currentState the last stable state of the bottom sheet
* *
* @return the next stable state that the sheet should settle at
*/
override fun getPreviousStableState(currentState: BottomSheetState): BottomSheetState {
when (currentState) {
BottomSheetState.STATE_EXPANDED -> return BottomSheetState.STATE_ANCHOR_POINT
BottomSheetState.STATE_ANCHOR_POINT -> return BottomSheetState.STATE_HIDDEN
else -> return BottomSheetState.STATE_HIDDEN
}
}
/**
* Returns a measured y position that the top of the bottom sheet should settle at
* @param state the [State] that the sheet is going to settle at
* *
* @return the y position that the top of the sheet will be at once it is done settling
*/
override fun getTopForState(state: BottomSheetState): Int {
when (state) {
BottomSheetState.STATE_HIDDEN -> return parentHeight
BottomSheetState.STATE_COLLAPSED -> return maxOffset
BottomSheetState.STATE_ANCHOR_POINT -> return anchorPoint
BottomSheetState.STATE_EXPANDED -> return minOffset
else -> return 0
}
}
override fun setStateInternal(state: BottomSheetState) {
var s = state
// we never collapse this sheet
if (s == BottomSheetState.STATE_COLLAPSED) {
s = BottomSheetState.STATE_ANCHOR_POINT
lastStableState = BottomSheetState.STATE_ANCHOR_POINT
}
super.setStateInternal(s)
}
}
| mit | 9f2bbfb3b243bcff7e109b87c5b3ce8f | 39.674242 | 195 | 0.64742 | 4.867634 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/com/congwiny/basic/WhenAndRanges.kt | 1 | 1814 | package com.congwiny.basic
/**
* Created by congwiny on 2017/5/28.
*/
fun describe(obj: Any): String =
//这表达式好流弊啊
when (obj) {
1 -> "one"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a String"
else -> "Unknown"
}
fun main(args: Array<String>) {
println(describe(1))
println(describe("Hello"))
println(describe(1000L))
println(describe(2))
println(describe("other"))
testInOperator()
println()
//when和in的配合使用,判断集合内是否包含某实例
val items = setOf("apple", "banana", "kiwi")
when {
"orange" in items -> println("juicy")
"apple" in items -> println("apple is fine too")
}
}
//in 运算符
fun testInOperator() {
/**
* 使用in运算符来检测某个数字是否在指定区间内
*/
val x = 10
val y = 9
if (x in 1..y + 1) {
println("first in range")
}
//检测某个数字
var list = listOf("a", "b", "c")
if (-1 in 0..list.lastIndex) {
println("-1 is out of range")
}
//list.indices -> 0..size-1
if (list.size !in list.indices) {
println("list size is out of valid list indices range too")
}
//in 区间迭代
for (x in 1..5) {
print(x)
}
println()
//或数列迭代 step
for (x in 1..10 step 2) {
print(x)
}
println()
//递减 downTo
for (x in 9 downTo 0 step 3) {
print(x)
}
/**
* for (i in 1..100) { ... } // closed range: includes 100
* for (i in 1 until 100) { ... } // half-open range: does not include 100
* for (x in 2..10 step 2) { ... }
* for (x in 10 downTo 1) { ... }
* if (x in 1..10) { ... }
*/
}
| apache-2.0 | cb4d09ed798b7524a74740304b23aafa | 19.740741 | 78 | 0.494643 | 3.128492 | false | false | false | false |
chadrick-kwag/datalabeling_app | app/src/main/java/com/example/chadrick/datalabeling/CustomComponents/RectDrawImageView.kt | 1 | 4590 | package com.example.chadrick.datalabeling.CustomComponents
import android.content.Context
import android.graphics.*
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
import android.view.MotionEvent
import com.example.chadrick.datalabeling.Util
/**
* Created by chadrick on 18. 2. 12.
*/
class RectDrawImageView @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {
val paint: Paint = Paint()
val start = PointF()
val last = PointF()
var TouchEnabled = true
private var isMove = false
private var isDown = false
lateinit var drawBtnpressedcallback: () -> Boolean
lateinit var bitmap: Bitmap
lateinit var canvas: Canvas
lateinit var rectReadyCallback: (Rect) -> Unit
init {
paint.color = Color.rgb(255, 0, 0)
paint.strokeWidth = 5f
paint.style = Paint.Style.STROKE
setOnTouchListener local@ { view, motionEvent ->
// if touch is disabled, do nothing.
if (!TouchEnabled) {
return@local true
}
// what we need is get the x,y of event.
// set start, last and draw on the canvas
// but there is difference in the size of canvas and the IV's size
// since we are inside the IV itself, I think we can access the size of IV much better
// check if the drawBtn is pressed or not.
val isDrawBtnPressed: Boolean = drawBtnpressedcallback()
//
//
// if (drawBtnpressedcallback != null) {
// drawbtnpressed = drawBtnpressesdcallback()
// } else {
// drawbtnpressed = false
// }
// deal with the event only when drawbtn is pressed.
if (!isDrawBtnPressed && !isMove) {
return@local false
}
// prepare the adjusted x,y coordinates
val curr = PointF()
curr.set(motionEvent.x, motionEvent.y)
when (motionEvent.action) {
MotionEvent.ACTION_DOWN -> {
isDown = true
start.set(motionEvent.x, motionEvent.y)
last.set(start)
}
MotionEvent.ACTION_MOVE -> run {
if (!isMove) {
// Log.d(TAG,"maskIV, motion move event started");
}
isMove = true
// Log.d(TAG,"action move detected");
if (!isDrawBtnPressed) {
// probably fall in here when the user released the drawbtn
// while dragging the rectangle.
// we just want to quit the drawing of the rectangle
bitmap.eraseColor(Color.TRANSPARENT)
return@run
}
//remove the previous drawn rectangle
// Log.d(TAG,"maskIV erase in action_move");
bitmap.eraseColor(Color.TRANSPARENT)
last.set(curr.x, curr.y)
// draw rectangle based on start, last
val rect = Util.convertToRect(start, last)
canvas.drawRect(rect, paint)
}
MotionEvent.ACTION_UP -> {
isMove = false
isDown = false
// erase the rect draw in move case.
// bitmap.eraseColor(Color.TRANSPARENT);
last.set(curr.x, curr.y)
// draw the rectangle. and then ask the user if this rectangle is going to be saved or not.
val rect2 = Util.convertToRect(start, last)
rectReadyCallback(rect2)
canvas.drawRect(rect2, paint)
}
}
invalidate()
// indicate that touch event is still no handled. we need this event to go down
// to the lower level.
return@local true
}
}
fun passWH(width: Int, height: Int) {
bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
canvas = Canvas(bitmap)
this.setImageBitmap(bitmap)
}
fun eraseall() {
bitmap.eraseColor(Color.TRANSPARENT)
}
} | mit | c6876f18059ac6de7e3a9a840251f631 | 29.403974 | 111 | 0.520261 | 5.09434 | false | false | false | false |
kotlinz/kotlinz | src/main/kotlin/com/github/kotlinz/kotlinz/data/either/EitherApplicativeOps.kt | 1 | 1001 | package com.github.kotlinz.kotlinz.data.either
import com.github.kotlinz.kotlinz.K1
import com.github.kotlinz.kotlinz.curried
import com.github.kotlinz.kotlinz.type.applicative.ApplicativeOps
interface EitherApplicativeOps<S>: ApplicativeOps<K1<Either.T, S>>, EitherMonad<S> {
override fun <A, B> liftA(f: (A) -> B): (K1<K1<Either.T, S>, A>) -> Either<S, B> {
return { a -> Either.narrow(a) ap Either.pure(f) }
}
override fun <A, B, C> liftA2(f: (A, B) -> C): (K1<K1<Either.T, S>, A>, K1<K1<Either.T, S>, B>) -> Either<S, C> {
return { a1, a2 ->
val i1 = Either.narrow(a1)
val i2 = Either.narrow(a2)
i2 ap (i1 fmap f.curried())
}
}
override fun <A, B, C, D> liftA3(f: (A, B, C) -> D): (K1<K1<Either.T, S>, A>, K1<K1<Either.T, S>, B>, K1<K1<Either.T, S>, C>) -> Either<S, D> {
return { a1, a2, a3 ->
val i1 = Either.narrow(a1)
val i2 = Either.narrow(a2)
val i3 = Either.narrow(a3)
i3 ap (i2 ap (i1 fmap f.curried()))
}
}
}
| apache-2.0 | 49fff215644ce186c6736a219184f0a3 | 34.75 | 145 | 0.593407 | 2.447433 | false | false | false | false |
AndroidX/androidx | navigation/navigation-common/src/test/java/androidx/navigation/NavGraphTest.kt | 3 | 10538 | /*
* Copyright (C) 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 androidx.navigation
import androidx.annotation.IdRes
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NavGraphTest {
companion object {
@IdRes
private const val FIRST_DESTINATION_ID = 1
@IdRes
private const val SECOND_DESTINATION_ID = 2
}
private lateinit var provider: NavigatorProvider
private lateinit var noOpNavigator: NoOpNavigator
private lateinit var navGraphNavigator: NavGraphNavigator
@Before
fun setup() {
provider = NavigatorProvider().apply {
addNavigator(NoOpNavigator().also { noOpNavigator = it })
addNavigator(
NavGraphNavigator(this).also {
navGraphNavigator = it
}
)
}
}
private fun createFirstDestination() = noOpNavigator.createDestination().apply {
id = FIRST_DESTINATION_ID
}
private fun createSecondDestination() = noOpNavigator.createDestination().apply {
id = SECOND_DESTINATION_ID
}
private fun createGraphWithDestination(destination: NavDestination) =
navGraphNavigator.createDestination().apply {
addDestination(destination)
}
private fun createGraphWithDestinations(vararg destinations: NavDestination) =
navGraphNavigator.createDestination().apply {
addDestinations(*destinations)
}
@Test(expected = IllegalArgumentException::class)
fun addDestinationWithoutId() {
val graph = navGraphNavigator.createDestination()
val destination = noOpNavigator.createDestination()
graph.addDestination(destination)
}
@Test
fun addDestination() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
assertThat(destination.parent).isEqualTo(graph)
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isEqualTo(destination)
}
@Test
fun addDestinationWithSameId() {
val destination = createFirstDestination()
val graph = navGraphNavigator.createDestination().apply {
id = FIRST_DESTINATION_ID
}
try {
graph.addDestination(destination)
} catch (e: IllegalArgumentException) {
assertWithMessage("Adding destination with same id as its parent should fail")
.that(e).hasMessageThat().contains(
"Destination $destination cannot have the same id as graph $graph"
)
}
}
@Test
fun setStartDestinationWithSameId() {
val destination = createFirstDestination()
val graph = navGraphNavigator.createDestination().apply {
id = FIRST_DESTINATION_ID
}
try {
graph.setStartDestination(destination.id)
} catch (e: IllegalArgumentException) {
assertWithMessage("Setting a start destination with same id as its parent should fail")
.that(e).hasMessageThat().contains(
"Start destination " + destination.id +
" cannot use the same id as the graph $graph"
)
}
}
@Test
fun addDestinationsAsCollection() {
val graph = navGraphNavigator.createDestination()
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
graph.addDestinations(listOf(destination, secondDestination))
assertThat(destination.parent).isEqualTo(graph)
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isEqualTo(destination)
assertThat(secondDestination.parent).isEqualTo(graph)
assertThat(graph.findNode(SECOND_DESTINATION_ID)).isEqualTo(secondDestination)
}
@Test
fun addDestinationsAsVarArgs() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
assertThat(destination.parent).isEqualTo(graph)
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isEqualTo(destination)
assertThat(secondDestination.parent).isEqualTo(graph)
assertThat(graph.findNode(SECOND_DESTINATION_ID)).isEqualTo(secondDestination)
}
@Test
fun addReplacementDestination() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
val replacementDestination = noOpNavigator.createDestination()
replacementDestination.id = FIRST_DESTINATION_ID
graph.addDestination(replacementDestination)
assertThat(destination.parent).isNull()
assertThat(replacementDestination.parent).isEqualTo(graph)
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isEqualTo(replacementDestination)
}
@Test(expected = IllegalStateException::class)
fun addDestinationWithExistingParent() {
val destination = createFirstDestination()
createGraphWithDestination(destination)
val other = navGraphNavigator.createDestination()
other.addDestination(destination)
}
@Test
fun addAll() {
val destination = createFirstDestination()
val other = createGraphWithDestination(destination)
val graph = navGraphNavigator.createDestination()
graph.addAll(other)
assertThat(destination.parent).isEqualTo(graph)
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isEqualTo(destination)
assertThat(other.findNode(FIRST_DESTINATION_ID)).isNull()
}
@Test
fun removeDestination() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
graph.remove(destination)
assertThat(destination.parent).isNull()
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isNull()
}
@Test
operator fun iterator() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
assertThat(graph.iterator().asSequence().asIterable())
.containsExactly(destination, secondDestination)
}
@Test(expected = NoSuchElementException::class)
fun iteratorNoSuchElement() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
val iterator = graph.iterator()
iterator.next()
iterator.next()
}
@Test
fun iteratorRemove() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
val iterator = graph.iterator()
val value = iterator.next()
iterator.remove()
assertThat(value.parent).isNull()
assertThat(graph.findNode(value.id)).isNull()
}
@Test
fun iteratorDoubleRemove() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
val iterator = graph.iterator()
iterator.next()
iterator.remove()
val value = iterator.next()
iterator.remove()
assertThat(value.parent).isNull()
assertThat(graph.findNode(value.id)).isNull()
}
@Test(expected = IllegalStateException::class)
fun iteratorDoubleRemoveWithoutNext() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
val iterator = graph.iterator()
iterator.next()
iterator.remove()
iterator.remove()
}
@Test
fun clear() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
graph.clear()
assertThat(destination.parent).isNull()
assertThat(graph.findNode(FIRST_DESTINATION_ID)).isNull()
assertThat(secondDestination.parent).isNull()
assertThat(graph.findNode(SECOND_DESTINATION_ID)).isNull()
}
@Test
fun equalsNull() {
val destination = createFirstDestination()
val graph = createGraphWithDestination(destination)
assertThat(graph).isNotNull()
}
@Test
fun equals() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
val graph2 = createGraphWithDestinations(
createFirstDestination(),
createSecondDestination()
)
assertThat(graph2).isEqualTo(graph)
}
@Test
fun equalsDifferentSizes() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
val graph2 = createGraphWithDestination(createFirstDestination())
assertThat(graph2).isNotEqualTo(graph)
}
@Test
fun equalsDifferentStartDestination() {
val destination = createFirstDestination()
val secondDestination = createSecondDestination()
val graph = createGraphWithDestinations(destination, secondDestination)
graph.setStartDestination(FIRST_DESTINATION_ID)
val graph2 = createGraphWithDestination(createFirstDestination())
graph2.setStartDestination(SECOND_DESTINATION_ID)
assertThat(graph2).isNotEqualTo(graph)
}
}
| apache-2.0 | b2ee927538df668e85e625a11a6d69ed | 33.437908 | 99 | 0.681628 | 5.390281 | false | true | false | false |
exponent/exponent | packages/expo-camera/android/src/main/java/expo/modules/camera/utils/ImageDimensions.kt | 2 | 417 | package expo.modules.camera.utils
data class ImageDimensions @JvmOverloads constructor(private val mWidth: Int, private val mHeight: Int, val rotation: Int = 0, val facing: Int = -1) {
private val isLandscape: Boolean
get() = rotation % 180 == 90
val width: Int
get() = if (isLandscape) {
mHeight
} else mWidth
val height: Int
get() = if (isLandscape) {
mWidth
} else mHeight
}
| bsd-3-clause | b461205efaebfcdd2d9e0a1dfbb5fb36 | 28.785714 | 150 | 0.661871 | 3.971429 | false | false | false | false |
Tapchicoma/ultrasonic | ultrasonic/src/main/kotlin/org/moire/ultrasonic/service/ApiCallResponseChecker.kt | 1 | 2684 | package org.moire.ultrasonic.service
import java.io.IOException
import org.moire.ultrasonic.api.subsonic.SubsonicAPIClient
import org.moire.ultrasonic.api.subsonic.SubsonicAPIDefinition
import org.moire.ultrasonic.api.subsonic.response.SubsonicResponse
import org.moire.ultrasonic.data.ActiveServerProvider
import retrofit2.Response
import timber.log.Timber
/**
* This call wraps Subsonic API calls so their results can be checked for errors, API version, etc
*/
class ApiCallResponseChecker(
private val subsonicAPIClient: SubsonicAPIClient,
private val activeServerProvider: ActiveServerProvider
) {
/**
* Executes a Subsonic API call with response check
*/
@Throws(SubsonicRESTException::class, IOException::class)
fun <T : Response<out SubsonicResponse>> callWithResponseCheck(
call: (SubsonicAPIDefinition) -> T
): T {
// Check for API version when first contacting the server
if (activeServerProvider.getActiveServer().minimumApiVersion == null) {
try {
val response = subsonicAPIClient.api.ping().execute()
if (response?.body() != null) {
val restApiVersion = response.body()!!.version.restApiVersion
Timber.i("Server minimum API version set to %s", restApiVersion)
activeServerProvider.setMinimumApiVersion(restApiVersion)
}
} catch (ignored: Exception) {
// This Ping is only used to get the API Version, if it fails, that's no problem.
}
}
// This call will be now executed with the correct API Version, so it shouldn't fail
val result = call.invoke(subsonicAPIClient.api)
checkResponseSuccessful(result)
return result
}
/**
* Creates Exceptions from the results returned by the Subsonic API
*/
companion object {
@Throws(SubsonicRESTException::class, IOException::class)
fun checkResponseSuccessful(response: Response<out SubsonicResponse>) {
if (response.isSuccessful && response.body()!!.status === SubsonicResponse.Status.OK) {
return
}
if (!response.isSuccessful) {
throw IOException("Server error, code: " + response.code())
} else if (
response.body()!!.status === SubsonicResponse.Status.ERROR &&
response.body()!!.error != null
) {
throw SubsonicRESTException(response.body()!!.error!!)
} else {
throw IOException("Failed to perform request: " + response.code())
}
}
}
}
| gpl-3.0 | 980f2f18282d1f65c940c06abbbc8dc1 | 39.666667 | 99 | 0.636736 | 4.988848 | false | false | false | false |
foreverigor/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/ui/ticket/EventCard.kt | 1 | 2173 | package de.tum.`in`.tumcampusapp.component.ui.ticket
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.other.navigation.NavigationDestination
import de.tum.`in`.tumcampusapp.component.other.navigation.SystemActivity
import de.tum.`in`.tumcampusapp.component.ui.overview.CardManager
import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card
import de.tum.`in`.tumcampusapp.component.ui.overview.card.CardViewHolder
import de.tum.`in`.tumcampusapp.component.ui.ticket.activity.EventDetailsActivity
import de.tum.`in`.tumcampusapp.component.ui.ticket.adapter.EventsAdapter
import de.tum.`in`.tumcampusapp.component.ui.ticket.model.Event
class EventCard(context: Context) : Card(CardManager.CARD_EVENT, context, "card_event") {
var event: Event? = null
private val eventsController = EventsController(context)
override fun updateViewHolder(viewHolder: RecyclerView.ViewHolder) {
super.updateViewHolder(viewHolder)
val eventViewHolder = viewHolder as? EventsAdapter.EventViewHolder ?: return
val hasTicket = eventsController.isEventBooked(event)
eventViewHolder.bind(event, hasTicket)
}
override fun getNavigationDestination(): NavigationDestination? {
val bundle = Bundle().apply { putParcelable("event", event) }
return SystemActivity(EventDetailsActivity::class.java, bundle)
}
override fun shouldShow(prefs: SharedPreferences): Boolean {
return event?.dismissed == 0
}
override fun discard(editor: SharedPreferences.Editor) {
event?.let {
eventsController.setDismissed(it.id)
}
}
companion object {
@JvmStatic
fun inflateViewHolder(parent: ViewGroup): CardViewHolder {
val card = LayoutInflater.from(parent.context)
.inflate(R.layout.card_events_item, parent, false)
return EventsAdapter.EventViewHolder(card, true)
}
}
}
| gpl-3.0 | 1224b751269681efb6958d2752d15dbd | 36.465517 | 89 | 0.739991 | 4.398785 | false | false | false | false |
oldcwj/iPing | app/src/main/java/com/wpapper/iping/ui/dialogs/CompressAsDialog.kt | 1 | 2676 | package com.wpapper.iping.ui.dialogs
import android.support.v7.app.AlertDialog
import android.view.View
import android.view.WindowManager
import com.simplemobiletools.commons.extensions.*
import com.wpapper.iping.R
import com.wpapper.iping.ui.folder.SimpleActivity
import com.wpapper.iping.ui.utils.exts.config
import kotlinx.android.synthetic.main.dialog_compress_as.view.*
import java.io.File
class CompressAsDialog(val activity: SimpleActivity, val path: String, val callback: (destination: String) -> Unit) {
private val view = activity.layoutInflater.inflate(R.layout.dialog_compress_as, null)
init {
val file = File(path)
val filename = path.getFilenameFromPath()
val indexOfDot = if (filename.contains('.') && file.isFile) filename.lastIndexOf(".") else filename.length
val baseFilename = filename.substring(0, indexOfDot)
var realPath = file.parent.trimEnd('/')
view.apply {
file_name.setText(baseFilename)
file_path.text = activity.humanizePath(realPath)
file_path.setOnClickListener {
FilePickerDialog(activity, realPath, false, activity.config.shouldShowHidden, true) {
file_path.text = activity.humanizePath(it)
realPath = it
}
}
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, null)
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this, R.string.compress_as)
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(View.OnClickListener {
val name = view.file_name.value
when {
name.isEmpty() -> activity.toast(R.string.empty_name)
name.isAValidFilename() -> {
val newFile = File(realPath, "$name.zip")
if (newFile.exists()) {
activity.toast(R.string.name_taken)
return@OnClickListener
}
dismiss()
callback(newFile.absolutePath)
}
else -> activity.toast(R.string.invalid_name)
}
})
}
}
}
| gpl-3.0 | c58b3c0d5dc573993678f92a78374273 | 42.868852 | 117 | 0.545217 | 5.186047 | false | false | false | false |
androidx/androidx | compose/material3/material3/integration-tests/material3-demos/src/main/java/androidx/compose/material3/demos/ColorSchemeDemo.kt | 3 | 8611 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.compose.material3.demos
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.luminance
import androidx.compose.ui.unit.dp
@Composable
fun ColorSchemeDemo() {
val colorScheme = MaterialTheme.colorScheme
Row(
modifier = Modifier.padding(8.dp),
) {
Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
Text("Surfaces", style = MaterialTheme.typography.bodyLarge)
SurfaceColorSwatch(
surface = colorScheme.background,
surfaceText = "Background",
onSurface = colorScheme.onBackground,
onSurfaceText = "On Background"
)
Spacer(modifier = Modifier.height(16.dp))
SurfaceColorSwatch(
surface = colorScheme.surface,
surfaceText = "Surface",
onSurface = colorScheme.onSurface,
onSurfaceText = "On Surface"
)
Spacer(modifier = Modifier.height(16.dp))
SurfaceColorSwatch(
surface = colorScheme.surfaceVariant,
surfaceText = "Surface Variant",
onSurface = colorScheme.onSurfaceVariant,
onSurfaceText = "On Surface Variant"
)
Spacer(modifier = Modifier.height(16.dp))
DoubleTile(
leftTile = {
ColorTile(
text = "Inverse Surface",
color = colorScheme.inverseSurface,
)
},
rightTile = {
ColorTile(
text = "Inverse On Surface",
color = colorScheme.inverseOnSurface,
)
},
)
DoubleTile(
leftTile = {
ColorTile(
text = "Inverse Primary",
color = colorScheme.inversePrimary,
)
},
rightTile = {
ColorTile(
text = "Surface Tint",
color = colorScheme.surfaceTint,
)
},
)
Spacer(modifier = Modifier.height(16.dp))
}
Spacer(modifier = Modifier.width(24.dp))
Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) {
Text("Content", style = MaterialTheme.typography.bodyLarge)
ContentColorSwatch(
color = colorScheme.primary,
colorText = "Primary",
onColor = colorScheme.onPrimary,
onColorText = "On Primary",
colorContainer = colorScheme.primaryContainer,
colorContainerText = "Primary Container",
onColorContainer = colorScheme.onPrimaryContainer,
onColorContainerText = "On Primary Container")
Spacer(modifier = Modifier.height(16.dp))
ContentColorSwatch(
color = colorScheme.secondary,
colorText = "Secondary",
onColor = colorScheme.onSecondary,
onColorText = "On Secondary",
colorContainer = colorScheme.secondaryContainer,
colorContainerText = "Secondary Container",
onColorContainer = colorScheme.onSecondaryContainer,
onColorContainerText = "On Secondary Container")
Spacer(modifier = Modifier.height(16.dp))
ContentColorSwatch(
color = colorScheme.tertiary,
colorText = "Tertiary",
onColor = colorScheme.onTertiary,
onColorText = "On Tertiary",
colorContainer = colorScheme.tertiaryContainer,
colorContainerText = "Tertiary Container",
onColorContainer = colorScheme.onTertiaryContainer,
onColorContainerText = "On Tertiary Container")
Spacer(modifier = Modifier.height(16.dp))
ContentColorSwatch(
color = colorScheme.error,
colorText = "Error",
onColor = colorScheme.onError,
onColorText = "On Error",
colorContainer = colorScheme.errorContainer,
colorContainerText = "Error Container",
onColorContainer = colorScheme.onErrorContainer,
onColorContainerText = "On Error Container")
Spacer(modifier = Modifier.height(16.dp))
Text("Utility", style = MaterialTheme.typography.bodyLarge)
DoubleTile(
leftTile = {
ColorTile(
text = "Outline",
color = colorScheme.outline,
)
},
rightTile = {
ColorTile(
text = "Outline Variant",
color = colorScheme.outlineVariant,
)
}
)
}
}
}
@Composable
private fun SurfaceColorSwatch(
surface: Color,
surfaceText: String,
onSurface: Color,
onSurfaceText: String
) {
ColorTile(
text = surfaceText,
color = surface,
)
ColorTile(
text = onSurfaceText,
color = onSurface,
)
}
@Composable
private fun ContentColorSwatch(
color: Color,
colorText: String,
onColor: Color,
onColorText: String,
colorContainer: Color,
colorContainerText: String,
onColorContainer: Color,
onColorContainerText: String,
) {
DoubleTile(
leftTile = {
ColorTile(
text = colorText,
color = color
)
},
rightTile = {
ColorTile(
text = onColorText,
color = onColor,
)
},
)
DoubleTile(
leftTile = {
ColorTile(
text = colorContainerText,
color = colorContainer,
)
},
rightTile = {
ColorTile(
text = onColorContainerText,
color = onColorContainer,
)
},
)
}
@Composable
private fun DoubleTile(leftTile: @Composable () -> Unit, rightTile: @Composable () -> Unit) {
Row(modifier = Modifier.fillMaxWidth()) {
Box(modifier = Modifier.weight(1f)) { leftTile() }
Box(modifier = Modifier.weight(1f)) { rightTile() }
}
}
@Composable
private fun ColorTile(text: String, color: Color) {
var borderColor = Color.Transparent
if (color == Color.Black) {
borderColor = Color.White
} else if (color == Color.White) borderColor = Color.Black
Surface(
modifier = Modifier.height(48.dp).fillMaxWidth(),
color = color,
border = BorderStroke(1.dp, borderColor),
) {
Text(
text,
Modifier.padding(4.dp),
style =
MaterialTheme.typography.bodyMedium.copy(
if (color.luminance() < .25) Color.White else Color.Black
)
)
}
}
| apache-2.0 | c58b68fa9a656c56dd69bed40a63b69c | 33.862348 | 93 | 0.563814 | 5.260232 | false | false | false | false |
javatlacati/datastrructureskotlin | src/main/java/katlin/lists/linkedlists/singlelinkedlists/recursive/Node.kt | 1 | 1351 | package katlin.lists.linkedlists.singlelinkedlists.recursive
class Node(var item: Any?) {
var next: Node? = null
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is Node) return false
if (!other.canEqual(this as Any)) return false
val `this$item` = this.item
val `other$item` = other.item
if (if (`this$item` == null) `other$item` != null else `this$item` != `other$item`) return false
return true
}
override fun hashCode(): Int {
val PRIME = 59
var result = 1
val `$item` = this.item
result = result * PRIME + (`$item`?.hashCode() ?: 43)
return result
}
protected fun canEqual(other: Any): Boolean {
return other is Node
}
override fun toString(): String = "Node(item=${this.item})"
@Synchronized internal fun add(newNode: Node) {
if (next == null) {
next = newNode
} else {
next!!.add(newNode)
}
}
internal val strings: String
get() {
return if (next == null) toString() else toString() + next!!.strings
}
fun size(i: Int): Int {
if (next == null) {
return i
} else {
val i1 = i + 1
return next!!.size(i1)
}
}
} | gpl-3.0 | 76212f7ee67683ad043ff27377a05f6e | 25.509804 | 104 | 0.527757 | 3.997041 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/data/checker/CheckAudience.kt | 1 | 6472 | /*
* Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.data.checker
import android.database.Cursor
import android.provider.BaseColumns
import org.andstatus.app.account.MyAccount
import org.andstatus.app.data.DataUpdater
import org.andstatus.app.data.DbUtils
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.data.MyQuery
import org.andstatus.app.database.table.NoteTable
import org.andstatus.app.net.social.Actor
import org.andstatus.app.net.social.Audience
import org.andstatus.app.net.social.Note
import org.andstatus.app.net.social.Visibility
import org.andstatus.app.origin.Origin
import org.andstatus.app.origin.OriginType
import org.andstatus.app.util.I18n
import org.andstatus.app.util.MyHtml
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.RelativeTime
import java.util.function.Function
/**
* @author [email protected]
*/
internal class CheckAudience : DataChecker() {
override fun fixInternal(): Long {
return myContext.origins.collection().map { o: Origin -> fixOneOrigin(o, countOnly) }.sum().toLong()
}
private class FixSummary {
var rowsCount: Long = 0
var toFixCount = 0
}
private fun fixOneOrigin(origin: Origin, countOnly: Boolean): Int {
if (logger.isCancelled) return 0
val ma = myContext.accounts.getFirstPreferablySucceededForOrigin(origin)
if (ma.isEmpty) return 0
val dataUpdater = DataUpdater(ma)
val sql = "SELECT " + BaseColumns._ID + ", " +
NoteTable.INS_DATE + ", " +
NoteTable.VISIBILITY + ", " +
NoteTable.CONTENT + ", " +
NoteTable.ORIGIN_ID + ", " +
NoteTable.AUTHOR_ID + ", " +
NoteTable.IN_REPLY_TO_ACTOR_ID +
" FROM " + NoteTable.TABLE_NAME +
" WHERE " + NoteTable.ORIGIN_ID + "=" + origin.id +
" AND " + NoteTable.NOTE_STATUS + "=" + DownloadStatus.LOADED.save() +
" ORDER BY " + BaseColumns._ID + " DESC" +
if (includeLong) "" else " LIMIT 0, 500"
val summary = MyQuery.foldLeft(myContext, sql, FixSummary(),
{ fixSummary: FixSummary -> Function { cursor: Cursor -> foldOneNote(ma, dataUpdater, countOnly, fixSummary, cursor) } })
logger.logProgress(origin.name + ": " +
if (summary.toFixCount == 0) "No changes to Audience were needed. " + summary.rowsCount + " notes" else (if (countOnly) "Need to update " else "Updated") + " Audience for " + summary.toFixCount +
" of " + summary.rowsCount + " notes")
pauseToShowCount(this, summary.toFixCount)
return summary.toFixCount
}
private fun foldOneNote(ma: MyAccount, dataUpdater: DataUpdater, countOnly: Boolean, fixSummary: FixSummary, cursor: Cursor): FixSummary {
if (logger.isCancelled) return fixSummary
val origin = ma.origin
fixSummary.rowsCount++
val noteId = DbUtils.getLong(cursor, BaseColumns._ID)
val insDate = DbUtils.getLong(cursor, NoteTable.INS_DATE)
val storedVisibility: Visibility = Visibility.fromCursor(cursor)
val content = DbUtils.getString(cursor, NoteTable.CONTENT)
val author: Actor = Actor.load(myContext, DbUtils.getLong(cursor, NoteTable.AUTHOR_ID))
val inReplyToActor: Actor = Actor.load(myContext, DbUtils.getLong(cursor, NoteTable.IN_REPLY_TO_ACTOR_ID))
if (origin.originType === OriginType.GNUSOCIAL || origin.originType === OriginType.TWITTER) {
// See org.andstatus.app.note.NoteEditorData.recreateAudience
val audience = Audience(origin).withVisibility(storedVisibility)
audience.add(inReplyToActor)
audience.addActorsFromContent(content, author, inReplyToActor)
audience.lookupUsers()
val actorsToSave = audience.evaluateAndGetActorsToSave(author)
if (!countOnly) {
actorsToSave.stream().filter { a: Actor -> a.actorId == 0L }
.forEach { actor: Actor -> dataUpdater.updateObjActor(ma.actor.update(actor), 0) }
}
compareVisibility(fixSummary, countOnly, noteId, audience, storedVisibility)
if (audience.save(author, noteId, audience.visibility, countOnly)) {
fixSummary.toFixCount += 1
}
} else {
val audience: Audience = Audience.fromNoteId(origin, noteId, storedVisibility)
compareVisibility(fixSummary, countOnly, noteId, audience, storedVisibility)
}
logger.logProgressIfLongProcess {
"""${origin.name}: need to fix ${fixSummary.toFixCount} of ${fixSummary.rowsCount} audiences;
${RelativeTime.getDifference(myContext.context, insDate)}, ${I18n.trimTextAt(MyHtml.htmlToCompactPlainText(content), 120)}"""
}
return fixSummary
}
private fun compareVisibility(s: FixSummary, countOnly: Boolean, noteId: Long,
audience: Audience, storedVisibility: Visibility) {
if (storedVisibility == audience.visibility) return
s.toFixCount += 1
var msgLog = (s.toFixCount.toString() + ". Fix visibility for " + noteId + " " + storedVisibility
+ " -> " + audience.visibility)
if (s.toFixCount < 20) {
msgLog += "; " + Note.loadContentById(myContext, noteId)
}
MyLog.i(TAG, msgLog)
if (!countOnly) {
val sql = ("UPDATE " + NoteTable.TABLE_NAME
+ " SET "
+ NoteTable.VISIBILITY + "=" + audience.visibility.id
+ " WHERE " + BaseColumns._ID + "=" + noteId)
myContext.database?.execSQL(sql)
}
}
companion object {
private val TAG: String = CheckAudience::class.simpleName!!
}
}
| apache-2.0 | 26b32dda6594c728f42f56d2c4edd242 | 46.588235 | 211 | 0.646477 | 4.219035 | false | false | false | false |
Tvede-dk/CommonsenseAndroidKotlin | widgets/src/main/kotlin/com/commonsense/android/kotlin/views/input/selection/ToggleableView.kt | 1 | 4899 | package com.commonsense.android.kotlin.views.input.selection
import android.view.*
import android.widget.*
import com.commonsense.android.kotlin.base.*
/**
* The selection toggle callback type
*/
typealias SelectionToggleCallback<T> = (ToggleableView<T>, Boolean) -> Unit
/**
* the selection change callback type
*/
typealias SelectionChangeCallback<ViewType> = (ViewType, EmptyFunction) -> Unit
/**
* Required for marking things as "checked"
*/
interface CheckableStatus {
var checked: Boolean
}
/**
* Both containing a checked status but also the ability to set / clear a callback on checkChanged
*/
interface CheckableStatusCallback : CheckableStatus {
fun setOnCheckedChangedListener(callback: EmptyFunction)
fun clearOnSelectionChanged()
}
/**
* The ability to select and "deselect" a view, with a given value.
*/
interface ToggleableView<out T> : CheckableStatus {
/**
* The value this "view" represents (the checked state).
*/
val value: T
/**
* calls the given callback when the selection changes.
*/
fun setOnSelectionChanged(callback: SelectionToggleCallback<T>)
/**
* Removes any selection callbacks
*/
fun clearOnSelectionChanged()
/**
* Deselects the checked state
*/
fun deselect() {
checked = false
}
/**
* Selects the checked state
*/
fun select() {
checked = true
}
}
/**
* A functional wrapper over the ToggleableView, where the implementation is provided though functions.
*/
class ToggleableViewFunctional<out T, ViewType : View>(
override val value: T,
private val view: ViewType,
private val getSelection: Function1<ViewType, Boolean>,
private val setSelection: Function2<ViewType, Boolean, Unit>,
private val setOnChangedListener: SelectionChangeCallback<ViewType>,
private val clearOnChangedListener: FunctionUnit<ViewType>) : ToggleableView<T> {
override fun clearOnSelectionChanged() {
this.clearOnChangedListener(view)
}
override var checked: Boolean
get() = getSelection(view)
set(value) = setSelection(view, value)
override fun setOnSelectionChanged(callback: SelectionToggleCallback<T>) {
this.setOnChangedListener(view) {
callback(this, checked)
}
}
}
/**
* Wraps a view that is also a checkableStatus into a toggleable.
* Given the functional implementations.
*/
fun <T, ViewType> ViewType.asToggleable(
value: T,
setOnChangedListener: SelectionChangeCallback<ViewType>,
clearOnChangedListener: FunctionUnit<ViewType>)
: ToggleableViewFunctional<T, ViewType> where ViewType : View,
ViewType : CheckableStatus {
return ToggleableViewFunctional(
value,
this,
{ it.checked },
{ view, isChecked ->
view.checked = isChecked
},
setOnChangedListener,
clearOnChangedListener)
}
/**
* Wraps a view in a toggleable functional, thus making it possible to treat any view as a toggleable,
* given the provided selection mechanisms
*/
fun <T, ViewType : View> ViewType.asToggleable(
value: T,
getSelection: (ViewType) -> Boolean,
setSelection: (ViewType, Boolean) -> Unit,
setOnChangedListener: SelectionChangeCallback<ViewType>,
clearOnChangedListener: FunctionUnit<ViewType>): ToggleableView<T> {
return ToggleableViewFunctional(
value,
this,
getSelection,
setSelection,
setOnChangedListener,
clearOnChangedListener)
}
/**
* Creates a functional wrapper over the given view, with the given value, as toggleable.
* the viewType is capable of setting selection and clearing it.
*/
fun <T, ViewType> ViewType.asToggleable(value: T): ToggleableViewFunctional<T, ViewType>
where ViewType : View,
ViewType : CheckableStatusCallback {
return this.asToggleable(value,
CheckableStatusCallback::setOnCheckedChangedListener,
CheckableStatusCallback::clearOnSelectionChanged)
}
/**
* Converts a CompoundButton to a toggleable view.
* this then works for
* CheckBox, RadioButton, Switch, ToggleButton
* The value T is the selection value if this view is selected / marked.
*/
fun <T> CompoundButton.asToggleable(value: T): ToggleableView<T> {
return this.asToggleable(value,
android.widget.CompoundButton::isChecked,
android.widget.CompoundButton::setChecked,
{ compoundButton, function ->
compoundButton.setOnCheckedChangeListener { _, _ -> function() }
},
{ compoundButton ->
compoundButton.setOnCheckedChangeListener(null)
})
}
| mit | 753faad59ce1378e63c7357f0fe02d62 | 28.512048 | 103 | 0.661359 | 4.899 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/android/upnp/DeviceWrapper.kt | 1 | 7225 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.android.upnp
import android.os.Bundle
import net.mm2d.upnp.Device
import net.mm2d.upnp.Icon
/**
* 特定のDeviceTypeへのインターフェースを備えるDeviceWrapperの共通の親。
*
* Deviceはhas-a関係で保持するが、Wrapperと1対1である保証はなく、
* 複数のWrapperから一つのDeviceが参照される可能性もある。
* WrapperとしてDeviceへアクセスするためのアクセッサをここで定義し、
* 継承したクラスではその他の機能を実装する。
*
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
abstract class DeviceWrapper(
/**
* このクラスがwrapしているDeviceのインスタンスを返す。
*
* protectedであるが、内部実装を理解したサブクラスから参照される想定であり、
* 直接Deviceをサブクラス以外から参照しないこと。
* Deviceの各プロパティへは用意されたアクセッサを利用する。
*
* @return Device
*/
private val device: Device
) {
private val arguments = Bundle()
private var iconSearched: Boolean = false
private var icon: Icon? = null
/**
* Deviceの有効なIconを返す。
*
* MsControlPointにてダウンロードするIconを一つのみに限定しているため、
* Binaryデータがダウンロード済みのものがあればそれを返す。
*
* @return Iconインスタンス、ない場合はnullが返る。
*/
fun getIcon(): Icon? {
if (iconSearched) {
return icon
}
iconSearched = true
icon = searchIcon()
return icon
}
/**
* Locationに記述のIPアドレスを返す。
*
* 記述に異常がある場合は空文字が返る。
*
* @return IPアドレス
*/
val ipAddress: String
get() = device.ipAddress
/**
* UDNタグの値を返す。
*
* @return UDNタグの値
*/
val udn: String
get() = device.udn
/**
* friendlyNameタグの値を返す。
*
* @return friendlyNameタグの値
*/
val friendlyName: String
get() = device.friendlyName
/**
* manufacturerタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return manufacturerタグの値
*/
val manufacture: String?
get() = device.manufacture
/**
* manufacturerURLタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return manufacturerURLタグの値
*/
val manufactureUrl: String?
get() = device.manufactureUrl
/**
* modelNameタグの値を返す。
*
* @return modelNameタグの値
*/
val modelName: String
get() = device.modelName
/**
* modelURLタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return modelURLタグの値
*/
val modelUrl: String?
get() = device.modelUrl
/**
* modelDescriptionタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return modelDescriptionタグの値
*/
val modelDescription: String?
get() = device.modelDescription
/**
* modelNumberタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return modelNumberタグの値
*/
val modelNumber: String?
get() = device.modelNumber
/**
* serialNumberタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return serialNumberタグの値
*/
val serialNumber: String?
get() = device.serialNumber
/**
* presentationURLタグの値を返す。
*
* 値が存在しない場合nullが返る。
*
* @return presentationURLタグの値
*/
val presentationUrl: String?
get() = device.presentationUrl
/**
* SSDPパケットに記述されているLocationヘッダの値を返す。
*
* @return Locationヘッダの値
*/
val location: String
get() = device.location
private fun searchIcon(): Icon? {
val iconList = device.iconList
for (icon in iconList) {
if (icon.binary != null) {
return icon
}
}
return null
}
/**
* 任意の値を登録する。
*
* @param name データの名前
* @param value 格納する値
*/
fun putBooleanTag(name: String, value: Boolean) {
arguments.putBoolean(name, value)
}
/**
* 格納された任意の値を取り出す。
*
* @param name データの名前
* @param defaultValue 格納されていなかった場合のデフォルト値
* @return データの値
*/
fun getBooleanTag(name: String, defaultValue: Boolean): Boolean {
return arguments.getBoolean(name, defaultValue)
}
/**
* 任意の値を登録する。
*
* @param name データの名前
* @param value 格納する値
*/
fun putIntTag(name: String, value: Int) {
arguments.putInt(name, value)
}
/**
* 格納された任意の値を取り出す。
*
* @param name データの名前
* @param defaultValue 格納されていなかった場合のデフォルト値
* @return データの値
*/
fun getIntTag(name: String, defaultValue: Int): Int {
return arguments.getInt(name, defaultValue)
}
/**
* 任意の値を登録する。
*
* @param name データの名前
* @param value 格納する値
*/
fun putLongTag(name: String, value: Long) {
arguments.putLong(name, value)
}
/**
* 格納された任意の値を取り出す。
*
* @param name データの名前
* @param defaultValue 格納されていなかった場合のデフォルト値
* @return データの値
*/
fun getLongTag(name: String, defaultValue: Long): Long {
return arguments.getLong(name, defaultValue)
}
/**
* 任意の値を登録する。
*
* @param name データの名前
* @param value 格納する値
*/
fun putStringTag(name: String, value: String?) {
arguments.putString(name, value)
}
/**
* 格納された任意の値を取り出す。
*
* @param name データの名前
* @return データの値
*/
fun getStringTag(name: String): String? =
arguments.getString(name)
override fun equals(other: Any?): Boolean {
if (other === this) {
return true
}
if (other !is DeviceWrapper) {
return false
}
return device == other.device
}
override fun hashCode(): Int = device.hashCode()
override fun toString(): String = friendlyName
}
| mit | d6c00f08b110f3d3b467dca659185e21 | 19.396364 | 69 | 0.569264 | 3.170718 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/CollapsibleSectionView.kt | 1 | 5259 | package com.habitrpg.android.habitica.ui.views
import android.content.Context
import android.content.SharedPreferences
import android.util.AttributeSet
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import androidx.core.content.edit
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.databinding.ViewCollapsibleSectionBinding
import com.habitrpg.common.habitica.extensions.getThemeColor
import com.habitrpg.common.habitica.extensions.layoutInflater
class CollapsibleSectionView(context: Context, attrs: AttributeSet?) : LinearLayout(context, attrs) {
val infoIconView: ImageView
get() = binding.infoIconView
private val binding = ViewCollapsibleSectionBinding.inflate(context.layoutInflater, this)
private var preferences: SharedPreferences? = null
private val padding = context.resources?.getDimension(R.dimen.spacing_large)?.toInt() ?: 0
private val bottomPadding = context.resources?.getDimension(R.dimen.collapsible_section_padding)?.toInt() ?: 0
var title: CharSequence
get() {
return binding.titleTextView.text
}
set(value) {
binding.titleTextView.text = value
}
private var isCollapsed = false
set(value) {
field = value
if (value) {
hideViews()
} else {
showViews()
}
}
var caretColor: Int = 0
set(value) {
field = value
setCaretImage()
}
var identifier: String? = null
private fun showViews() {
updatePreferences()
setCaretImage()
(0 until childCount)
.map { getChildAt(it) }
.forEach { it.visibility = View.VISIBLE }
}
private fun hideViews() {
updatePreferences()
setCaretImage()
(0 until childCount)
.map { getChildAt(it) }
.filter { it != binding.sectionTitleView }
.forEach {
it.visibility = View.GONE
}
}
private fun updatePreferences() {
if (identifier == null) {
return
}
preferences?.edit { putBoolean(identifier, isCollapsed) }
}
private fun setCaretImage() {
binding.caretView.setImageBitmap(HabiticaIconsHelper.imageOfCaret(caretColor, isCollapsed))
}
private fun setChildMargins() {
(0 until childCount)
.map { getChildAt(it) }
.filter { it != binding.sectionTitleView }
.forEach {
val lp = it.layoutParams as? LayoutParams
lp?.setMargins(padding, 0, padding, bottomPadding)
it.layoutParams = lp
}
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
setChildMargins()
super.onLayout(changed, l, t, r, b)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var height = 0
measureChildWithMargins(binding.sectionTitleView, widthMeasureSpec, 0, heightMeasureSpec, height)
height += binding.sectionTitleView.measuredHeight
(1 until childCount)
.map { getChildAt(it) }
.forEach {
if (it.visibility != View.GONE) {
measureChildWithMargins(it, widthMeasureSpec, 0, heightMeasureSpec, height)
height += it.measuredHeight + bottomPadding
}
}
if (!isCollapsed) {
height += padding
}
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height)
}
init {
caretColor = ContextCompat.getColor(context, R.color.black_50_alpha)
orientation = VERTICAL
binding.sectionTitleView.setOnClickListener {
isCollapsed = !isCollapsed
}
val attributes = context.theme?.obtainStyledAttributes(
attrs,
R.styleable.CollapsibleSectionView,
0, 0
)
title = attributes?.getString(R.styleable.CollapsibleSectionView_title) ?: ""
identifier = attributes?.getString(R.styleable.CollapsibleSectionView_identifier)
val color = attributes?.getColor(R.styleable.CollapsibleSectionView_color, 0)
if (color != null && color != 0) {
caretColor = color
binding.titleTextView.setTextColor(color)
}
if (attributes?.getBoolean(R.styleable.CollapsibleSectionView_hasAdditionalInfo, false) == true) {
binding.infoIconView.setImageBitmap(HabiticaIconsHelper.imageOfInfoIcon(context.getThemeColor(R.attr.colorPrimaryOffset)))
} else {
binding.infoIconView.visibility = View.GONE
}
}
override fun onAttachedToWindow() {
super.onAttachedToWindow()
setCaretImage()
setChildMargins()
preferences = context.getSharedPreferences("collapsible_sections", 0)
if (identifier != null && preferences?.getBoolean(identifier, false) == true) {
isCollapsed = true
}
}
fun setCaretOffset(offset: Int) {
binding.caretView.setPadding(0, 0, offset, 0)
}
}
| gpl-3.0 | de7dde9fd94bd811df0b7625c53bdc08 | 33.149351 | 134 | 0.625594 | 4.924157 | false | false | false | false |
trife/Field-Book | app/src/main/java/com/fieldbook/tracker/utilities/BluetoothUtil.kt | 1 | 2446 | package com.fieldbook.tracker.utilities
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.appcompat.app.AlertDialog
import com.fieldbook.tracker.R
//Bluetooth Utility class for printing ZPL code and choosing bluetooth devices to print from.
class BluetoothUtil {
private var mBtName: String = String()
private val mBluetoothAdapter: BluetoothAdapter? by lazy {
BluetoothAdapter.getDefaultAdapter()
}
//operation that uses the provided context to prompt the user for a paired bluetooth device
private fun choose(ctx: Context, f: () -> Unit) {
if (mBtName.isBlank()) {
mBluetoothAdapter?.let {
val pairedDevices = it.bondedDevices
val map = HashMap<Int, BluetoothDevice>()
val input = RadioGroup(ctx)
pairedDevices.forEachIndexed { _, t ->
val button = RadioButton(ctx)
button.text = t.name
input.addView(button)
map[button.id] = t
}
val builder = AlertDialog.Builder(ctx).apply {
setTitle(context.getString(R.string.bluetooth_printer_choose_device_title))
setView(input)
setNegativeButton(android.R.string.cancel) { _, _ ->
}
setPositiveButton(android.R.string.ok) { _, _ ->
if (input.checkedRadioButtonId == -1) return@setPositiveButton
else {
mBtName = map[input.checkedRadioButtonId]?.name ?: ""
}
f()
}
}
builder.show()
}
} else f()
}
/**
* This function will first ask the user to select a printer.
* As long as the same object is used the user only needs to ask once.
* This sends a list of label commands, and only updates the printer message when the
* button is pressed.
*/
fun print(ctx: Context, size: String, labelCommand: List<String>) {
choose(ctx) {
if (labelCommand.isNotEmpty()) {
PrintThread(ctx, mBtName).print(size, labelCommand)
}
}
}
} | gpl-2.0 | da542798994d7298cef081bdc0308587 | 28.130952 | 95 | 0.566231 | 5.095833 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql | src/test/kotlin/examples/kotlin/mybatis3/canonical/PersonMapperExtensions.kt | 1 | 8147 | /*
* Copyright 2016-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
*
* 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 examples.kotlin.mybatis3.canonical
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.addressId
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.birthDate
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.employed
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.firstName
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.id
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.lastName
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.occupation
import examples.kotlin.mybatis3.canonical.PersonDynamicSqlSupport.person
import org.mybatis.dynamic.sql.BasicColumn
import org.mybatis.dynamic.sql.util.kotlin.CountCompleter
import org.mybatis.dynamic.sql.util.kotlin.DeleteCompleter
import org.mybatis.dynamic.sql.util.kotlin.GeneralInsertCompleter
import org.mybatis.dynamic.sql.util.kotlin.InsertSelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.KotlinUpdateBuilder
import org.mybatis.dynamic.sql.util.kotlin.SelectCompleter
import org.mybatis.dynamic.sql.util.kotlin.UpdateCompleter
import org.mybatis.dynamic.sql.util.kotlin.elements.`as`
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.count
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countDistinct
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.countFrom
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.deleteFrom
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insert
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertBatch
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertInto
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertMultiple
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.insertSelect
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectDistinct
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectList
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.selectOne
import org.mybatis.dynamic.sql.util.kotlin.mybatis3.update
fun PersonMapper.count(column: BasicColumn, completer: CountCompleter) =
count(this::count, column, person, completer)
fun PersonMapper.countDistinct(column: BasicColumn, completer: CountCompleter) =
countDistinct(this::count, column, person, completer)
fun PersonMapper.count(completer: CountCompleter) =
countFrom(this::count, person, completer)
fun PersonMapper.delete(completer: DeleteCompleter) =
deleteFrom(this::delete, person, completer)
fun PersonMapper.deleteByPrimaryKey(id_: Int) =
delete {
where { id isEqualTo id_ }
}
fun PersonMapper.insert(record: PersonRecord) =
insert(this::insert, record, person) {
map(id) toProperty "id"
map(firstName) toProperty "firstName"
map(lastName) toProperty "lastName"
map(birthDate) toProperty "birthDate"
map(employed) toProperty "employed"
map(occupation) toProperty "occupation"
map(addressId) toProperty "addressId"
}
fun PersonMapper.generalInsert(completer: GeneralInsertCompleter) =
insertInto(this::generalInsert, person, completer)
fun PersonMapper.insertSelect(completer: InsertSelectCompleter) =
insertSelect(this::insertSelect, person, completer)
fun PersonMapper.insertBatch(vararg records: PersonRecord): List<Int> =
insertBatch(records.toList())
fun PersonMapper.insertBatch(records: Collection<PersonRecord>): List<Int> =
insertBatch(this::insert, records, person) {
map(id) toProperty "id"
map(firstName) toProperty "firstName"
map(lastName) toProperty "lastName"
map(birthDate) toProperty "birthDate"
map(employed) toProperty "employed"
map(occupation) toProperty "occupation"
map(addressId) toProperty "addressId"
}
fun PersonMapper.insertMultiple(vararg records: PersonRecord) =
insertMultiple(records.toList())
fun PersonMapper.insertMultiple(records: Collection<PersonRecord>) =
insertMultiple(this::insertMultiple, records, person) {
map(id) toProperty "id"
map(firstName) toProperty "firstName"
map(lastName) toProperty "lastName"
map(birthDate) toProperty "birthDate"
map(employed) toProperty "employed"
map(occupation) toProperty "occupation"
map(addressId) toProperty "addressId"
}
fun PersonMapper.insertSelective(record: PersonRecord) =
insert(this::insert, record, person) {
map(id).toPropertyWhenPresent("id", record::id)
map(firstName).toPropertyWhenPresent("firstName", record::firstName)
map(lastName).toPropertyWhenPresent("lastName", record::lastName)
map(birthDate).toPropertyWhenPresent("birthDate", record::birthDate)
map(employed).toPropertyWhenPresent("employed", record::employed)
map(occupation).toPropertyWhenPresent("occupation", record::occupation)
map(addressId).toPropertyWhenPresent("addressId", record::addressId)
}
private val columnList = listOf(id `as` "A_ID", firstName, lastName, birthDate, employed, occupation, addressId)
fun PersonMapper.selectOne(completer: SelectCompleter) =
selectOne(this::selectOne, columnList, person, completer)
fun PersonMapper.select(completer: SelectCompleter) =
selectList(this::selectMany, columnList, person, completer)
fun PersonMapper.selectDistinct(completer: SelectCompleter) =
selectDistinct(this::selectMany, columnList, person, completer)
fun PersonMapper.selectByPrimaryKey(id_: Int) =
selectOne {
where { id isEqualTo id_ }
}
fun PersonMapper.update(completer: UpdateCompleter) =
update(this::update, person, completer)
fun KotlinUpdateBuilder.updateAllColumns(record: PersonRecord) =
apply {
set(id) equalToOrNull record::id
set(firstName) equalToOrNull record::firstName
set(lastName) equalToOrNull record::lastName
set(birthDate) equalToOrNull record::birthDate
set(employed) equalToOrNull record::employed
set(occupation) equalToOrNull record::occupation
set(addressId) equalToOrNull record::addressId
}
fun KotlinUpdateBuilder.updateSelectiveColumns(record: PersonRecord) =
apply {
set(id) equalToWhenPresent record::id
set(firstName) equalToWhenPresent record::firstName
set(lastName) equalToWhenPresent record::lastName
set(birthDate) equalToWhenPresent record::birthDate
set(employed) equalToWhenPresent record::employed
set(occupation) equalToWhenPresent record::occupation
set(addressId) equalToWhenPresent record::addressId
}
fun PersonMapper.updateByPrimaryKey(record: PersonRecord) =
update {
set(firstName) equalToOrNull record::firstName
set(lastName) equalToOrNull record::lastName
set(birthDate) equalToOrNull record::birthDate
set(employed) equalToOrNull record::employed
set(occupation) equalToOrNull record::occupation
set(addressId) equalToOrNull record::addressId
where { id isEqualTo record.id!! }
}
fun PersonMapper.updateByPrimaryKeySelective(record: PersonRecord) =
update {
set(firstName) equalToWhenPresent record::firstName
set(lastName) equalToWhenPresent record::lastName
set(birthDate) equalToWhenPresent record::birthDate
set(employed) equalToWhenPresent record::employed
set(occupation) equalToWhenPresent record::occupation
set(addressId) equalToWhenPresent record::addressId
where { id isEqualTo record.id!! }
}
| apache-2.0 | d4409e70b70115cee6d8f25892f81bf3 | 43.519126 | 112 | 0.76028 | 4.263213 | false | false | false | false |
rhdunn/xquery-intellij-plugin | src/plugin-marklogic/test/uk/co/reecedunn/intellij/plugin/marklogic/tests/xray/format/XRayJsonFormatTest.kt | 1 | 12441 | /*
* Copyright (C) 2021 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.marklogic.tests.xray.format
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.vfs.encoding.EncodingManager
import com.intellij.openapi.vfs.encoding.EncodingManagerImpl
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.xdebugger.impl.XDebuggerUtilImpl
import org.hamcrest.CoreMatchers.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import uk.co.reecedunn.intellij.plugin.core.extensions.registerServiceInstance
import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat
import uk.co.reecedunn.intellij.plugin.core.tests.editor.MockEditorFactoryEx
import uk.co.reecedunn.intellij.plugin.core.tests.testFramework.IdeaPlatformTestCase
import uk.co.reecedunn.intellij.plugin.core.vfs.ResourceVirtualFileSystem
import uk.co.reecedunn.intellij.plugin.core.vfs.decode
import uk.co.reecedunn.intellij.plugin.marklogic.xray.format.XRayTestFormat
import uk.co.reecedunn.intellij.plugin.processor.query.QueryError
import uk.co.reecedunn.intellij.plugin.processor.query.QueryResult
import uk.co.reecedunn.intellij.plugin.processor.test.TestResult
import uk.co.reecedunn.intellij.plugin.processor.test.TestStatistics
import uk.co.reecedunn.intellij.plugin.processor.test.TestSuites
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.XsDecimal
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.XsInteger
import java.math.BigDecimal
@DisplayName("XRay Unit Tests - JSON Output Format")
class XRayJsonFormatTest : IdeaPlatformTestCase() {
override val pluginId: PluginId = PluginId.getId("XRayJsonFormatTest")
private val res = ResourceVirtualFileSystem(this::class.java.classLoader)
private fun parse(resource: String): TestSuites {
val text = res.findFileByPath(resource)?.decode()!!
val value = QueryResult(0, text, "xs:string", QueryResult.APPLICATION_JSON)
return XRayTestFormat.format("json").parse(value)!!
}
override fun registerServicesAndExtensions() {
val app = ApplicationManager.getApplication()
app.registerServiceInstance(XDebuggerUtil::class.java, XDebuggerUtilImpl())
app.registerServiceInstance(EditorFactory::class.java, MockEditorFactoryEx())
app.registerServiceInstance(EncodingManager::class.java, EncodingManagerImpl())
}
@Nested
@DisplayName("test suites")
internal inner class Suites {
@Test
@DisplayName("empty")
fun empty() {
val tests = parse("xray/format/json/empty.json")
assertThat(tests.passed, `is`(0))
assertThat(tests.failed, `is`(0))
assertThat(tests.ignored, `is`(0))
assertThat(tests.errors, `is`(0))
assertThat(tests.total, `is`(0))
assertThat(tests.testSuites.count(), `is`(0))
}
@Test
@DisplayName("single suite")
fun single() {
val tests = parse("xray/format/json/single.json")
assertThat(tests.passed, `is`(1))
assertThat(tests.failed, `is`(0))
assertThat(tests.ignored, `is`(0))
assertThat(tests.errors, `is`(0))
assertThat(tests.total, `is`(1))
assertThat(tests.testSuites.count(), `is`(1))
}
@Test
@DisplayName("module exception")
fun moduleException() {
val tests = parse("xray/format/json/syntax-error.json")
assertThat(tests.passed, `is`(0))
assertThat(tests.failed, `is`(0))
assertThat(tests.ignored, `is`(0))
assertThat(tests.errors, `is`(1))
assertThat(tests.total, `is`(0))
assertThat(tests.testSuites.count(), `is`(1))
}
}
@Nested
@DisplayName("test suite")
internal inner class Suite {
@Test
@DisplayName("single test case")
fun single() {
val tests = parse("xray/format/json/single.json")
val suite = tests.testSuites.first()
assertThat(suite.name, `is`("/xray/test/default-fn-namespace.xqy"))
assertThat(suite.error, `is`(nullValue()))
assertThat(suite.testCases.count(), `is`(1))
val statistics = suite as TestStatistics
assertThat(statistics.passed, `is`(1))
assertThat(statistics.failed, `is`(0))
assertThat(statistics.ignored, `is`(0))
assertThat(statistics.errors, `is`(0))
assertThat(statistics.total, `is`(1))
}
@Test
@DisplayName("exception")
fun exception() {
val tests = parse("xray/format/json/syntax-error.json")
val suite = tests.testSuites.first()
assertThat(suite.name, `is`("/xray/test/syntax-error.xqy"))
assertThat(suite.testCases.count(), `is`(0))
val statistics = suite as TestStatistics
assertThat(statistics.passed, `is`(0))
assertThat(statistics.failed, `is`(0))
assertThat(statistics.ignored, `is`(0))
assertThat(statistics.errors, `is`(1))
assertThat(statistics.total, `is`(0))
val e = suite.error as QueryError
assertThat(e.standardCode, `is`("XPST0003"))
assertThat(e.vendorCode, `is`("XDMP-UNEXPECTED"))
assertThat(e.description, `is`("Unexpected token"))
}
}
@Nested
@DisplayName("test case")
internal inner class Case {
@Test
@DisplayName("passed test")
fun passed() {
val tests = parse("xray/format/json/test-cases.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(3)
assertThat(case.name, `is`("passing-test"))
assertThat(case.result, `is`(TestResult.Passed))
assertThat(case.duration?.months, `is`(XsInteger.ZERO))
assertThat(case.duration?.seconds, `is`(XsDecimal(BigDecimal("0.000044"))))
assertThat(case.asserts.count(), `is`(1))
assertThat(case.error, `is`(nullValue()))
}
@Test
@DisplayName("failed test")
fun failed() {
val tests = parse("xray/format/json/test-cases.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(1)
assertThat(case.name, `is`("failing-test"))
assertThat(case.result, `is`(TestResult.Failed))
assertThat(case.duration?.months, `is`(XsInteger.ZERO))
assertThat(case.duration?.seconds, `is`(XsDecimal(BigDecimal("0.0001045"))))
assertThat(case.asserts.count(), `is`(1))
assertThat(case.error, `is`(nullValue()))
}
@Test
@DisplayName("ignored test")
fun ignored() {
val tests = parse("xray/format/json/test-cases.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(2)
assertThat(case.name, `is`("ignored-test"))
assertThat(case.result, `is`(TestResult.Ignored))
assertThat(case.duration?.months, `is`(XsInteger.ZERO))
assertThat(case.duration?.seconds, `is`(XsDecimal(BigDecimal("0"))))
assertThat(case.asserts.count(), `is`(0))
assertThat(case.error, `is`(nullValue()))
}
@Test
@DisplayName("exception")
fun exception() {
val tests = parse("xray/format/json/test-cases.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(0)
assertThat(case.name, `is`("exception"))
assertThat(case.result, `is`(TestResult.Error))
assertThat(case.duration?.months, `is`(XsInteger.ZERO))
assertThat(case.duration?.seconds, `is`(XsDecimal(BigDecimal("0.0004989"))))
assertThat(case.asserts.count(), `is`(0))
val e = case.error as QueryError
assertThat(e.standardCode, `is`("FOER0000"))
assertThat(e.vendorCode, `is`(nullValue()))
assertThat(e.description, `is`("error"))
}
}
@Nested
@DisplayName("test assert")
internal inner class Assert {
@Test
@DisplayName("passed assertion")
fun passed() {
val tests = parse("xray/format/json/test-cases.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(3)
val assert = case.asserts.first()
assertThat(assert.result, `is`(TestResult.Passed))
assertThat(assert.type, `is`("equal"))
assertThat(assert.expected, `is`("1"))
assertThat(assert.actual, `is`("1"))
assertThat(assert.message, `is`(nullValue()))
}
@Test
@DisplayName("failed assertion")
fun failed() {
val tests = parse("xray/format/json/test-cases.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(1)
val assert = case.asserts.first()
assertThat(assert.result, `is`(TestResult.Failed))
assertThat(assert.type, `is`("equal"))
assertThat(assert.expected, `is`("2"))
assertThat(assert.actual, `is`("1"))
assertThat(assert.message, `is`(nullValue()))
}
@Test
@DisplayName("element() in expected and actual")
fun element() {
val tests = parse("xray/format/json/test-values.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(0)
val assert = case.asserts.first()
assertThat(assert.result, `is`(TestResult.Failed))
assertThat(assert.type, `is`("equal"))
assertThat(assert.expected, `is`("{\"b\":{\"lorem\":\"ipsum\"}}"))
assertThat(assert.actual, `is`("{\"a\":{\"lorem\":\"ipsum\"}}"))
assertThat(assert.message, `is`(nullValue()))
}
@Test
@DisplayName("empty-sequence() in expected and actual")
fun emptySequence() {
val tests = parse("xray/format/json/test-values.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(1)
var assert = case.asserts.elementAt(1)
assertThat(assert.result, `is`(TestResult.Failed))
assertThat(assert.type, `is`("equal"))
assertThat(assert.expected, `is`("1"))
assertThat(assert.actual, `is`(""))
assertThat(assert.message, `is`(nullValue()))
assert = case.asserts.elementAt(2)
assertThat(assert.result, `is`(TestResult.Failed))
assertThat(assert.type, `is`("equal"))
assertThat(assert.expected, `is`(""))
assertThat(assert.actual, `is`("2"))
assertThat(assert.message, `is`(nullValue()))
}
@Test
@DisplayName("mixed sequence in expected and actual")
fun mixedSequence() {
val tests = parse("xray/format/json/test-values.json")
val suite = tests.testSuites.first()
val case = suite.testCases.elementAt(2)
val assert = case.asserts.first()
assertThat(assert.result, `is`(TestResult.Failed))
assertThat(assert.type, `is`("equal"))
assertThat(assert.expected, `is`("{\"a\":\"\",\"d\":\"\",\"c\":\"\",\"_value\":\"6 8\"}"))
assertThat(assert.actual, `is`("{\"a\":\"\",\"b\":\"\",\"c\":\"\",\"_value\":\"3 4\"}"))
assertThat(assert.message, `is`(nullValue()))
}
}
}
| apache-2.0 | bc539610f31a1b15cde3ae4b40d83036 | 39.924342 | 102 | 0.615224 | 4.307825 | false | true | false | false |
jiaminglu/kotlin-native | backend.native/tests/runtime/memory/escape0.kt | 1 | 929 | //fun foo1(arg: String) : String = foo0(arg)
fun foo1(arg: Any) : Any = foo0(arg)
fun foo0(arg: Any) : Any = Any()
var global : Any = Any()
fun foo0_escape(arg: Any) : Any{
global = arg
return Any()
}
class Node(var previous: Node?)
fun zoo3() : Node {
var current = Node(null)
for (i in 1 .. 5) {
current = Node(current)
}
return current
}
fun zoo4(arg: Int) : Any {
var a = Any()
var b = Any()
var c = Any()
a = b
val x = 3
a = when {
x < arg -> b
else -> c
}
return a
}
fun zoo5(arg: Any) : Any{
foo1(arg)
return arg
}
fun zoo6(arg: Any) : Any {
return zoo7(arg, "foo", 11)
}
fun zoo7(arg1: Any, arg2: Any, selector: Int) : Any {
return if (selector < 2) arg1 else arg2;
}
fun main(args : Array<String>) {
//val z = zoo7(Any(), Any(), 1)
val x = zoo5(Any())
//println(bar(foo1(foo2("")), foo2(foo1(""))))
}
| apache-2.0 | 0b4c88ac2d6e554f7d18979a20eef8d1 | 16.528302 | 53 | 0.525296 | 2.639205 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/components/Texts.kt | 1 | 1755 | /* Copyright 2021 Braden Farmer
*
* 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.farmerbb.notepad.ui.components
import androidx.annotation.StringRes
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import com.farmerbb.notepad.R
@Composable
fun AppBarText(text: String) {
Text(
text = text,
color = Color.White,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
}
@Composable
fun DialogTitle(@StringRes id: Int) {
Text(
text = stringResource(id),
fontWeight = FontWeight.W500
)
}
@Composable
fun DialogText(@StringRes id: Int, vararg formatArgs: Any) {
Text(
text = stringResource(id, *formatArgs)
)
}
@Composable
fun DialogButton(onClick: () -> Unit, @StringRes id: Int) {
TextButton(onClick) {
Text(
text = stringResource(id).uppercase(),
color = colorResource(id = R.color.primary)
)
}
} | apache-2.0 | c28a241ea8ac97da065c198c5602f839 | 27.322581 | 75 | 0.71339 | 4.071926 | false | false | false | false |
divinespear/jpa-schema-gradle-plugin | src/functionalTest/kotlin/io/github/divinespear/plugin/test/functional/eclipselink/EclipselinkWithXmlKotlinSpec.kt | 1 | 3503 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.divinespear.plugin.test.functional.eclipselink
import io.github.divinespear.plugin.test.KotlinFunctionalSpec
import io.github.divinespear.plugin.test.helper.runEclipseTask
import io.kotest.core.test.TestType
import io.kotest.matchers.should
import io.kotest.matchers.string.contain
import org.apache.tools.ant.util.JavaEnvUtils
import java.io.File
class EclipselinkWithXmlKotlinSpec : KotlinFunctionalSpec() {
private fun script(version: String) =
"""
plugins {
id("io.github.divinespear.jpa-schema-generate")
}
repositories {
mavenCentral()
}
dependencies {
api("org.eclipse.persistence:org.eclipse.persistence.jpa:$version")
implementation("org.springframework.boot:spring-boot:1.5.10.RELEASE")
runtimeOnly("com.h2database:h2:1.4.191")
runtimeOnly(fileTree(projectDir.relativeTo(file("lib"))) { include("*.jar") })
}
generateSchema {
scriptAction = "drop-and-create"
targets {
create("h2script") {
databaseProductName = "H2"
databaseMajorVersion = 1
databaseMinorVersion = 4
createOutputFileName = "h2-create.sql"
dropOutputFileName = "h2-drop.sql"
}
create("h2database") {
databaseAction = "drop-and-create"
scriptAction = null
jdbcDriver = "org.h2.Driver"
jdbcUrl = "jdbc:h2:${'$'}{buildDir}/generated-schema/test"
jdbcUser = "sa"
}
}
}
""".trimIndent()
init {
beforeTest {
if (it.type === TestType.Test) {
// copy example resources for test
val mainResourcesDir = testProjectDir.resolve("src/main/resources").apply {
mkdirs()
}
val resourceJavaDir = File("src/functionalTest/resources/meta/eclipselink")
resourceJavaDir.copyRecursively(mainResourcesDir, true)
}
}
"task with persistence.xml" should {
"work on eclipselink 2.7" {
runEclipseTask(script("[2.7,2.8)")) {
it.output should contain("org.eclipse.persistence/org.eclipse.persistence.jpa/2.7.")
}
}
"work on eclipselink 2.6".config(enabledIf = {
!JavaEnvUtils.isAtLeastJavaVersion("12")
}) {
runEclipseTask(script("[2.6,2.7)")) {
it.output should contain("org.eclipse.persistence/org.eclipse.persistence.jpa/2.6.")
}
}
"work on eclipselink 2.5" {
runEclipseTask(script("[2.5,2.6)")) {
it.output should contain("org.eclipse.persistence/org.eclipse.persistence.jpa/2.5.")
}
}
}
}
}
| apache-2.0 | 7f1a494bb46c96050c2e44f117d6b514 | 32.682692 | 94 | 0.644019 | 4.101874 | false | true | false | false |
Mindera/skeletoid | base/src/main/java/com/mindera/skeletoid/activities/unfreeze/ScreenFreezeWatcher.kt | 1 | 3363 | package com.mindera.skeletoid.activities.unfreeze
import android.app.Activity
import android.app.Application
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import com.mindera.skeletoid.routing.unfreeze.OpenUnfreezeScreenCommand
//There is an issue in Android Pie that affects some devices (like the Pixel 1).
//These are the steps needed to reproduce it:
//- user is on Activity "A".
//- a translucent Activity "T" is open because of a user interaction.
//- user locks the screen on Activity "T". Then unlocks it.
//- user goes back to Activity "A".
//- Activity "A" view is now frozen. It still register user input but the screen does not update
//
//This is due to a corrupted state in the WindowManager. And this class works as an work-around
//to restore the "frozen" activity view to a normal working one.
//The recovering of the corrupted state is achieved by just opening a dumb activity that is automatically closed
//after interacting with itself - that is performing a click in its content view.
class ScreenFreezeWatcher(val application : Application, val activityInRisk: Activity) {
var isWatcherActive: Boolean = true
fun watch() {
//TODO do not forget to validate if this is still needed when a new version cames out
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.P) {
return
}
application.registerActivityLifecycleCallbacks(activityLifecycleCallback)
registerScreenOnReceiver()
}
fun unwatch() {
//TODO do not forget to validate if this is still needed when a new version cames out
if (Build.VERSION.SDK_INT != Build.VERSION_CODES.P) {
return
}
application.unregisterActivityLifecycleCallbacks(activityLifecycleCallback)
unregisterScreenOnReceiver()
}
private fun registerScreenOnReceiver() {
val intentFilter = IntentFilter(Intent.ACTION_SCREEN_ON)
activityInRisk.registerReceiver(screenOnReceiver, intentFilter)
}
private fun unregisterScreenOnReceiver() {
activityInRisk.unregisterReceiver(screenOnReceiver)
}
private val screenOnReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (isWatcherActive && intent?.action.equals(Intent.ACTION_SCREEN_ON)) {
OpenUnfreezeScreenCommand(activityInRisk).navigate()
}
}
}
private val activityLifecycleCallback = object : Application.ActivityLifecycleCallbacks {
override fun onActivityStarted(activity: Activity) {
if (activityInRisk == activity) {
isWatcherActive = true
}
}
override fun onActivityStopped(activity: Activity) {
if (activityInRisk == activity) {
isWatcherActive = false
}
}
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {}
override fun onActivityResumed(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
override fun onActivityDestroyed(activity: Activity) {}
}
} | mit | 14c9d802e545d790b7b7c8fddf7590b9 | 38.116279 | 112 | 0.704728 | 4.902332 | false | false | false | false |
apollostack/apollo-android | apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/file/OperationVariablesAdapterBuilder.kt | 1 | 1427 | package com.apollographql.apollo3.compiler.codegen.file
import com.apollographql.apollo3.compiler.codegen.CgContext
import com.apollographql.apollo3.compiler.codegen.CgFile
import com.apollographql.apollo3.compiler.codegen.CgFileBuilder
import com.apollographql.apollo3.compiler.codegen.adapter.inputAdapterTypeSpec
import com.apollographql.apollo3.compiler.codegen.helpers.toNamedType
import com.apollographql.apollo3.compiler.unified.ir.IrOperation
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.TypeSpec
class OperationVariablesAdapterBuilder(
val context: CgContext,
val operation: IrOperation
): CgFileBuilder {
val packageName = context.layout.operationAdapterPackageName(operation.filePath)
val simpleName = context.layout.operationVariablesAdapterName(operation)
override fun prepare() {
context.resolver.registerOperationVariablesAdapter(
operation.name,
ClassName(packageName, simpleName)
)
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = simpleName,
typeSpecs = listOf(typeSpec())
)
}
private fun typeSpec(): TypeSpec {
return operation.variables.map { it.toNamedType() }
.inputAdapterTypeSpec(
context = context,
adapterName = simpleName,
adaptedTypeName = context.resolver.resolveOperation(operation.name)
)
}
} | mit | e8236df67149aea5dfe211c297e53ceb | 33.829268 | 82 | 0.758935 | 4.573718 | false | false | false | false |
kvakil/venus | src/main/kotlin/venus/riscv/insts/dsl/impls/BTypeImplementation32.kt | 1 | 1149 | package venus.riscv.insts.dsl.impls
import venus.riscv.InstructionField
import venus.riscv.MachineCode
import venus.simulator.Simulator
class BTypeImplementation32(private val cond: (Int, Int) -> Boolean) : InstructionImplementation {
override operator fun invoke(mcode: MachineCode, sim: Simulator) {
val rs1: Int = mcode[InstructionField.RS1]
val rs2: Int = mcode[InstructionField.RS2]
val imm: Int = constructBranchImmediate(mcode)
val vrs1: Int = sim.getReg(rs1)
val vrs2: Int = sim.getReg(rs2)
if (cond(vrs1, vrs2))
sim.incrementPC(imm)
else
sim.incrementPC(mcode.length)
}
}
fun constructBranchImmediate(mcode: MachineCode): Int {
val imm_11 = mcode[InstructionField.IMM_11_B]
val imm_4_1 = mcode[InstructionField.IMM_4_1]
val imm_10_5 = mcode[InstructionField.IMM_10_5]
val imm_12 = mcode[InstructionField.IMM_12]
var imm = 0
imm = setBitslice(imm, imm_11, 11, 12)
imm = setBitslice(imm, imm_4_1, 1, 5)
imm = setBitslice(imm, imm_10_5, 5, 11)
imm = setBitslice(imm, imm_12, 12, 13)
return signExtend(imm, 13)
}
| mit | 196e3a168d6363de3bef3bcb38bf80a9 | 34.90625 | 98 | 0.671889 | 3.174033 | false | false | false | false |
Heiner1/AndroidAPS | medtronic/src/main/java/info/nightscout/androidaps/plugins/pump/medtronic/comm/history/cgms/MedtronicCGMSHistoryDecoder.kt | 1 | 10960 | package info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil
import info.nightscout.androidaps.plugins.pump.common.utils.DateTimeUtil
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.MedtronicHistoryDecoder
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.RecordDecodeStatus
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.cgms.CGMSHistoryEntryType.Companion.getByCode
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import okhttp3.internal.and
import org.joda.time.LocalDateTime
import java.util.*
/**
* This file was taken from GGC - GNU Gluco Control (ggc.sourceforge.net), application for diabetes
* management and modified/extended for AAPS.
*
*
* Author: Andy {[email protected]}
*/
class MedtronicCGMSHistoryDecoder constructor(
aapsLogger: AAPSLogger,
medtronicUtil: MedtronicUtil,
bitUtils: ByteUtil
) : MedtronicHistoryDecoder<CGMSHistoryEntry>(aapsLogger, medtronicUtil, bitUtils) {
override fun decodeRecord(record: CGMSHistoryEntry): RecordDecodeStatus? {
return try {
decodeRecordInternal(record)
} catch (ex: Exception) {
aapsLogger.error(LTag.PUMPCOMM, " Error decoding: type={}, ex={}", record.entryType.name, ex.message, ex)
RecordDecodeStatus.Error
}
}
fun decodeRecordInternal(entry: CGMSHistoryEntry): RecordDecodeStatus {
if (entry.dateTimeLength > 0) {
parseDate(entry)
}
when (entry.entryType) {
CGMSHistoryEntryType.SensorPacket -> decodeSensorPacket(entry)
CGMSHistoryEntryType.SensorError -> decodeSensorError(entry)
CGMSHistoryEntryType.SensorDataLow -> decodeDataHighLow(entry, 40)
CGMSHistoryEntryType.SensorDataHigh -> decodeDataHighLow(entry, 400)
CGMSHistoryEntryType.SensorTimestamp -> decodeSensorTimestamp(entry)
CGMSHistoryEntryType.SensorCal -> decodeSensorCal(entry)
CGMSHistoryEntryType.SensorCalFactor -> decodeSensorCalFactor(entry)
CGMSHistoryEntryType.SensorSync -> decodeSensorSync(entry)
CGMSHistoryEntryType.SensorStatus -> decodeSensorStatus(entry)
CGMSHistoryEntryType.CalBGForGH -> decodeCalBGForGH(entry)
CGMSHistoryEntryType.GlucoseSensorData -> decodeGlucoseSensorData(entry)
CGMSHistoryEntryType.BatteryChange,
CGMSHistoryEntryType.Something10,
CGMSHistoryEntryType.DateTimeChange -> {
}
CGMSHistoryEntryType.Something19,
CGMSHistoryEntryType.DataEnd,
CGMSHistoryEntryType.SensorWeakSignal -> {
}
CGMSHistoryEntryType.UnknownOpCode,
CGMSHistoryEntryType.None -> {
}
}
return RecordDecodeStatus.NotSupported
}
override fun postProcess() {}
override fun createRecords(dataClearInput: MutableList<Byte>): MutableList<CGMSHistoryEntry> {
dataClearInput.reverse()
val dataClear = dataClearInput //reverseList(dataClearInput, Byte::class.java)
prepareStatistics()
var counter = 0
val outList: MutableList<CGMSHistoryEntry> = mutableListOf()
// create CGMS entries (without dates)
do {
val opCode = getUnsignedInt(dataClear[counter])
counter++
var entryType: CGMSHistoryEntryType?
if (opCode == 0) {
// continue;
} else if (opCode > 0 && opCode < 20) {
entryType = getByCode(opCode)
if (entryType === CGMSHistoryEntryType.None) {
unknownOpCodes[opCode] = opCode
aapsLogger.warn(LTag.PUMPCOMM, "GlucoseHistoryEntry with unknown code: $opCode")
val pe = CGMSHistoryEntry()
pe.setEntryType(CGMSHistoryEntryType.None)
pe.opCode = opCode.toByte()
pe.setData(Arrays.asList(opCode.toByte()), false)
outList.add(pe)
} else {
// System.out.println("OpCode: " + opCode);
val listRawData: MutableList<Byte> = ArrayList()
listRawData.add(opCode.toByte())
for (j in 0 until entryType.totalLength - 1) {
listRawData.add(dataClear[counter])
counter++
}
val pe = CGMSHistoryEntry()
pe.setEntryType(entryType)
pe.opCode = opCode.toByte()
pe.setData(listRawData, false)
// System.out.println("Record: " + pe);
outList.add(pe)
}
} else {
val pe = CGMSHistoryEntry()
pe.setEntryType(CGMSHistoryEntryType.GlucoseSensorData)
pe.setData(Arrays.asList(opCode.toByte()), false)
outList.add(pe)
}
} while (counter < dataClear.size)
outList.reverse()
val reversedOutList = outList // reverseList(outList, CGMSHistoryEntry::class.java)
//var timeStamp: Long? = null
var dateTime: LocalDateTime? = null
var getIndex = 0
for (entry in reversedOutList) {
decodeRecord(entry)
if (entry.hasTimeStamp()) {
//timeStamp = entry.atechDateTime
dateTime = DateTimeUtil.toLocalDateTime(entry.atechDateTime)
getIndex = 0
} else if (entry.entryType == CGMSHistoryEntryType.GlucoseSensorData) {
getIndex++
if (dateTime != null) entry.setDateTime(dateTime, getIndex)
} else {
if (dateTime != null) entry.setDateTime(dateTime, getIndex)
}
aapsLogger.debug(LTag.PUMPCOMM, "Record: {}", entry)
}
return reversedOutList
}
// private fun <E> reverseList(dataClearInput: List<E>, clazz: Class<E>): List<E> {
// val outList: MutableList<E> = ArrayList()
// for (i in dataClearInput.size - 1 downTo 1) {
// outList.add(dataClearInput[i])
// }
// return outList
// }
private fun parseMinutes(one: Int): Int {
return one and "0111111".toInt(2)
}
private fun parseHours(one: Int): Int {
return one and 0x1F
}
private fun parseDay(one: Int): Int {
return one and 0x1F
}
private fun parseMonths(first_byte: Int, second_byte: Int): Int {
val first_two_bits = first_byte shr 6
val second_two_bits = second_byte shr 6
return (first_two_bits shl 2) + second_two_bits
}
private fun parseYear(year: Int): Int {
return (year and 0x0F) + 2000
}
private fun parseDate(entry: CGMSHistoryEntry): Long? {
if (!entry.entryType.hasDate()) return null
val data = entry.datetime
return if (entry.entryType.dateType === CGMSHistoryEntryType.DateType.MinuteSpecific) {
val atechDateTime = DateTimeUtil.toATechDate(parseYear(data[3].toInt()), parseMonths(data[0].toInt(), data[1].toInt()),
parseDay(data[2].toInt()), parseHours(data[0].toInt()), parseMinutes(data[1].toInt()), 0)
entry.atechDateTime = atechDateTime
atechDateTime
} else if (entry.entryType.dateType === CGMSHistoryEntryType.DateType.SecondSpecific) {
aapsLogger.warn(LTag.PUMPCOMM, "parseDate for SecondSpecific type is not implemented.")
throw RuntimeException()
// return null;
} else null
}
private fun decodeGlucoseSensorData(entry: CGMSHistoryEntry) {
val sgv = entry.getUnsignedRawDataByIndex(0) * 2
entry.addDecodedData("sgv", sgv)
}
private fun decodeCalBGForGH(entry: CGMSHistoryEntry) {
val amount: Int = entry.getRawDataByIndex(3) and 32 shl 3 or entry.getRawDataByIndexInt(5)
//
val originType: String
originType = when (entry.getRawDataByIndexInt(3) shr 5 and 3) {
0x00 -> "rf"
else -> "unknown"
}
entry.addDecodedData("amount", amount)
entry.addDecodedData("originType", originType)
}
private fun decodeSensorSync(entry: CGMSHistoryEntry) {
val syncType: String
syncType = when (entry.getRawDataByIndexInt(3) shr 5 and 3) {
0x01 -> "new"
0x02 -> "old"
else -> "find"
}
entry.addDecodedData("syncType", syncType)
}
private fun decodeSensorStatus(entry: CGMSHistoryEntry) {
val statusType: String
statusType = when (entry.getRawDataByIndexInt(3) shr 5 and 3) {
0x00 -> "off"
0x01 -> "on"
0x02 -> "lost"
else -> "unknown"
}
entry.addDecodedData("statusType", statusType)
}
private fun decodeSensorCalFactor(entry: CGMSHistoryEntry) {
val factor: Double = (entry.getRawDataByIndexInt(5) shl 8 or entry.getRawDataByIndexInt(6)) / 1000.0
entry.addDecodedData("factor", factor)
}
private fun decodeSensorCal(entry: CGMSHistoryEntry) {
val calibrationType: String
calibrationType = when (entry.getRawDataByIndexInt(1)) {
0x00 -> "meter_bg_now"
0x01 -> "waiting"
0x02 -> "cal_error"
else -> "unknown"
}
entry.addDecodedData("calibrationType", calibrationType)
}
private fun decodeSensorTimestamp(entry: CGMSHistoryEntry) {
val sensorTimestampType: String
sensorTimestampType = when (entry.getRawDataByIndex(3).toInt() shr 5 and 3) {
0x00 -> "LastRf"
0x01 -> "PageEnd"
0x02 -> "Gap"
else -> "Unknown"
}
entry.addDecodedData("sensorTimestampType", sensorTimestampType)
}
private fun decodeSensorPacket(entry: CGMSHistoryEntry) {
val packetType: String
packetType = when (entry.getRawDataByIndex(1)) {
0x02.toByte() -> "init"
else -> "unknown"
}
entry.addDecodedData("packetType", packetType)
}
private fun decodeSensorError(entry: CGMSHistoryEntry) {
val errorType: String
errorType = when (entry.getRawDataByIndexInt(1)) {
0x01 -> "end"
else -> "unknown"
}
entry.addDecodedData("errorType", errorType)
}
private fun decodeDataHighLow(entry: CGMSHistoryEntry, sgv: Int) {
entry.addDecodedData("sgv", sgv)
}
override fun runPostDecodeTasks() {
showStatistics()
}
} | agpl-3.0 | 1c7f0683904cf4afd9e64aa114018e06 | 38.428058 | 131 | 0.61177 | 4.342314 | false | false | false | false |
Heiner1/AndroidAPS | diaconn/src/main/java/info/nightscout/androidaps/diaconn/pumplog/LOG_INJECTION_1DAY_BASAL.kt | 1 | 1581 | package info.nightscout.androidaps.diaconn.pumplog
import java.nio.ByteBuffer
import java.nio.ByteOrder
/*
* 당일 주입 총량 (기저)
*/
class LOG_INJECTION_1DAY_BASAL private constructor(
val data: String,
val dttm: String,
typeAndKind: Byte,
// 당일 기저주입 총량 47.5=4750
val amount: Short,
val batteryRemain: Byte
) {
val type: Byte = PumplogUtil.getType(typeAndKind)
val kind: Byte = PumplogUtil.getKind(typeAndKind)
override fun toString(): String {
val sb = StringBuilder("LOG_INJECTION_1DAY_BASAL{")
sb.append("LOG_KIND=").append(LOG_KIND.toInt())
sb.append(", data='").append(data).append('\'')
sb.append(", dttm='").append(dttm).append('\'')
sb.append(", type=").append(type.toInt())
sb.append(", kind=").append(kind.toInt())
sb.append(", amount=").append(amount.toInt())
sb.append(", batteryRemain=").append(batteryRemain.toInt())
sb.append('}')
return sb.toString()
}
companion object {
const val LOG_KIND: Byte = 0x2E
fun parse(data: String): LOG_INJECTION_1DAY_BASAL {
val bytes = PumplogUtil.hexStringToByteArray(data)
val buffer = ByteBuffer.wrap(bytes)
buffer.order(ByteOrder.LITTLE_ENDIAN)
return LOG_INJECTION_1DAY_BASAL(
data,
PumplogUtil.getDttm(buffer),
PumplogUtil.getByte(buffer),
PumplogUtil.getShort(buffer),
PumplogUtil.getByte(buffer)
)
}
}
} | agpl-3.0 | b3a6f8be02dc3ae64006fa41b3451052 | 30.632653 | 67 | 0.598451 | 3.89196 | false | false | false | false |
Maccimo/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/dependency/analyzer/DependencyAnalyzerAction.kt | 2 | 1535 | // 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.openapi.externalSystem.dependency.analyzer
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.util.ExternalSystemBundle
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.registry.Registry
abstract class DependencyAnalyzerAction : DumbAwareAction() {
abstract fun getSystemId(e: AnActionEvent): ProjectSystemId?
abstract fun isEnabledAndVisible(e: AnActionEvent): Boolean
abstract fun setSelectedState(view: DependencyAnalyzerView, e: AnActionEvent)
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val systemId = getSystemId(e) ?: return
val dependencyAnalyzerManager = DependencyAnalyzerManager.getInstance(project)
val dependencyAnalyzerView = dependencyAnalyzerManager.getOrCreate(systemId)
setSelectedState(dependencyAnalyzerView, e)
}
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = Registry.`is`("external.system.dependency.analyzer") && isEnabledAndVisible(e)
}
init {
templatePresentation.icon = AllIcons.Actions.DependencyAnalyzer
templatePresentation.text = ExternalSystemBundle.message("external.system.dependency.analyzer.action.name")
}
}
| apache-2.0 | 6439d7cba5ded178780f8550ad7a71f0 | 42.857143 | 158 | 0.808469 | 4.873016 | false | false | false | false |
android/architecture-components-samples | WorkManagerSample/lib/src/main/java/com/example/background/Constants.kt | 1 | 1181 | /*
* 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 com.example.background
/**
* Defines a list of constants used for [androidx.work.Worker] names, inputs & outputs.
*/
object Constants {
// The name of the image manipulation work
const val IMAGE_MANIPULATION_WORK_NAME = "image_manipulation_work"
// Other keys
const val OUTPUT_PATH = "demo_filter_outputs"
const val BASE_URL = "https://api.imgur.com/3/"
const val KEY_IMAGE_URI = "KEY_IMAGE_URI"
const val TAG_OUTPUT = "OUTPUT"
// Provide your own clientId to test Imgur uploads.
const val IMGUR_CLIENT_ID = ""
}
| apache-2.0 | ff7ce96448cb3d5435df378370a8e207 | 31.805556 | 87 | 0.712108 | 3.936667 | false | false | false | false |
DiUS/pact-jvm | provider/src/main/kotlin/au/com/dius/pact/provider/ProviderInfo.kt | 1 | 5518 | package au.com.dius.pact.provider
import au.com.dius.pact.core.model.DefaultPactReader
import au.com.dius.pact.core.model.FileSource
import au.com.dius.pact.core.model.Interaction
import au.com.dius.pact.core.pactbroker.ConsumerVersionSelector
import au.com.dius.pact.core.pactbroker.PactBrokerClient
import au.com.dius.pact.core.support.Utils
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.map
import org.apache.commons.lang3.builder.HashCodeBuilder
import org.apache.commons.lang3.builder.ToStringBuilder
import java.io.File
import java.net.URL
/**
* Provider Info Config
*/
open class ProviderInfo @JvmOverloads constructor (
override var name: String = "provider",
override var protocol: String = "http",
override var host: Any? = "localhost",
override var port: Any? = 8080,
override var path: String = "/",
open var startProviderTask: Any? = null,
open var terminateProviderTask: Any? = null,
override var requestFilter: Any? = null,
override var stateChangeRequestFilter: Any? = null,
override var createClient: Any? = null,
override var insecure: Boolean = false,
override var trustStore: File? = null,
override var trustStorePassword: String? = "changeit",
override var stateChangeUrl: URL? = null,
override var stateChangeUsesBody: Boolean = true,
override var stateChangeTeardown: Boolean = false,
open var isDependencyForPactVerify: Boolean = true,
override var verificationType: PactVerification? = PactVerification.REQUEST_RESPONSE,
override var packagesToScan: List<String> = emptyList(),
open var consumers: MutableList<IConsumerInfo> = mutableListOf()
) : IProviderInfo {
override fun hashCode() = HashCodeBuilder()
.append(name).append(protocol).append(host).append(port).append(path).toHashCode()
override fun toString() = ToStringBuilder.reflectionToString(this)
open fun hasPactWith(consumer: String, closure: ConsumerInfo.() -> Unit): ConsumerInfo {
val consumerInfo = ConsumerInfo(consumer)
consumers.add(consumerInfo)
consumerInfo.closure()
return consumerInfo
}
open fun hasPactsWith(consumersGroupName: String, closure: ConsumersGroup.() -> Unit): List<IConsumerInfo> {
val consumersGroup = ConsumersGroup(consumersGroupName)
consumersGroup.closure()
return setupConsumerListFromPactFiles(consumersGroup)
}
@JvmOverloads
open fun hasPactsFromPactBroker(options: Map<String, Any> = mapOf(), pactBrokerUrl: String) =
hasPactsFromPactBrokerWithSelectors(options, pactBrokerUrl, emptyList())
@JvmOverloads
@Suppress("TooGenericExceptionThrown")
open fun hasPactsFromPactBrokerWithSelectors(
options: Map<String, Any> = mapOf(),
pactBrokerUrl: String,
selectors: List<ConsumerVersionSelector>
): List<ConsumerInfo> {
val enablePending = Utils.lookupInMap(options, "enablePending", Boolean::class.java, false)
if (enablePending && (!options.containsKey("providerTags") || options["providerTags"] !is List<*>)) {
throw RuntimeException("No providerTags: To use the pending pacts feature, you need to provide the list of " +
"provider names for the provider application version that will be published with the verification results")
}
val providerTags = if (enablePending) {
options["providerTags"] as List<String>
} else {
emptyList()
}
val includePactsSince = Utils.lookupInMap(options, "includeWipPactsSince", String::class.java, "")
val client = pactBrokerClient(pactBrokerUrl, options)
val consumersFromBroker = client.fetchConsumersWithSelectors(name, selectors, providerTags, enablePending,
includePactsSince)
.map { results -> results.map { ConsumerInfo.from(it) }
}
return when (consumersFromBroker) {
is Ok<List<ConsumerInfo>> -> {
val list = consumersFromBroker.value
consumers.addAll(list)
list
}
is Err<Exception> -> {
throw RuntimeException("Call to fetch pacts from Pact Broker failed with an exception",
consumersFromBroker.error)
}
}
}
open fun pactBrokerClient(pactBrokerUrl: String, options: Map<String, Any>) =
PactBrokerClient(pactBrokerUrl, options)
@Suppress("TooGenericExceptionThrown")
open fun setupConsumerListFromPactFiles(consumersGroup: ConsumersGroup): MutableList<IConsumerInfo> {
val pactFileDirectory = consumersGroup.pactFileLocation ?: return mutableListOf()
if (!pactFileDirectory.exists() || !pactFileDirectory.canRead()) {
throw RuntimeException("pactFileDirectory ${pactFileDirectory.absolutePath} does not exist or is not readable")
}
pactFileDirectory.walkBottomUp().forEach { file ->
if (file.isFile && consumersGroup.include.matches(file.name)) {
val name = DefaultPactReader.loadPact(file).consumer.name
consumers.add(ConsumerInfo(name,
consumersGroup.stateChange,
consumersGroup.stateChangeUsesBody,
emptyList(),
null,
FileSource<Interaction>(file)
))
}
}
return consumers
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ProviderInfo
if (name != other.name) return false
if (protocol != other.protocol) return false
if (host != other.host) return false
if (port != other.port) return false
if (path != other.path) return false
return true
}
}
| apache-2.0 | 76b51729299f683d982a3283a24e492a | 37.859155 | 117 | 0.728525 | 4.244615 | false | false | false | false |
benjamin-bader/thrifty | thrifty-kotlin-codegen/src/test/kotlin/com/microsoft/thrifty/kgen/KotlinCodeGeneratorTest.kt | 1 | 41625 | /*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.kgen
import com.microsoft.thrifty.schema.FieldNamingPolicy
import com.microsoft.thrifty.schema.Loader
import com.microsoft.thrifty.schema.Schema
import com.microsoft.thrifty.service.ServiceMethodCallback
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asTypeName
import io.kotest.matchers.should
import io.kotest.matchers.shouldBe
import io.kotest.matchers.shouldNot
import io.kotest.matchers.string.contain
import io.kotest.matchers.string.shouldContain
import io.kotest.matchers.string.shouldNotContain
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
import java.io.File
class KotlinCodeGeneratorTest {
@TempDir
lateinit var tempDir: File
@Test
fun `struct to data class`() {
val schema = load("""
namespace kt com.test
// This is an enum
enum MyEnum {
MEMBER_ONE, // trailing doc
MEMBER_TWO
// leading doc
MEMBER_THREE = 4
}
const i32 FooNum = 42
const string ConstStr = "wtf"
const list<string> ConstStringList = ["wtf", "mate"]
const map<string, list<string>> Weird = { "foo": ["a", "s", "d", "f"],
"bar": ["q", "w", "e", "r"] }
//const binary ConstBin = "DEADBEEF"
struct Test {
1: required string Foo (thrifty.redacted = "1");
2: required map<i64, string> Numbers (thrifty.obfuscated = "1");
3: optional string Bar;
5: optional set<list<double>> Bs = [[1.0], [2.0], [3.0], [4.0]];
6: MyEnum enumType;
7: set<i8> Bytes;
8: list<list<string>> listOfStrings
}
struct AnotherOne {
1: optional i32 NumBitTheDust = 900
}
""".trimIndent())
val files = KotlinCodeGenerator(FieldNamingPolicy.JAVA).generate(schema)
files.shouldCompile()
files.forEach { println("$it") }
}
@Test
fun `output styles work as advertised`() {
val thrift = """
namespace kt com.test
enum AnEnum {
ONE,
TWO
}
struct AStruct {
1: optional string ssn;
}
""".trimIndent()
val schema = load(thrift)
val gen = KotlinCodeGenerator()
// Default should be one file per namespace
gen.outputStyle shouldBe KotlinCodeGenerator.OutputStyle.FILE_PER_NAMESPACE
gen.generate(schema).size shouldBe 1
gen.outputStyle = KotlinCodeGenerator.OutputStyle.FILE_PER_TYPE
gen.generate(schema).size shouldBe 2
}
@Test
fun `file-per-type puts constants into a file named 'Constants'`() {
val thrift = """
namespace kt com.test
const i32 ONE = 1;
const i64 TWO = 2;
const string THREE = "three";
""".trimIndent()
val schema = load(thrift)
val gen = KotlinCodeGenerator().filePerType()
val specs = gen.generate(schema)
specs.shouldCompile()
specs.single().name shouldBe "Constants" // ".kt" suffix is appended when the file is written out
}
@Test
fun `empty structs get default equals, hashcode, and toString methods`() {
val thrift = """
namespace kt com.test
struct Empty {}
""".trimIndent()
val specs = generate(thrift)
specs.shouldCompile()
val struct = specs.single().members.single() as TypeSpec
println(specs.single())
struct.name shouldBe "Empty"
struct.modifiers.any { it == KModifier.DATA } shouldBe false
struct.funSpecs.any { it.name == "toString" } shouldBe true
struct.funSpecs.any { it.name == "hashCode" } shouldBe true
struct.funSpecs.any { it.name == "equals" } shouldBe true
}
@Test
fun `Non-empty structs are data classes`() {
val thrift = """
namespace kt com.test
struct NonEmpty {
1: required i32 Number
}
""".trimIndent()
val specs = generate(thrift)
specs.shouldCompile()
val struct = specs.single().members.single() as TypeSpec
struct.name shouldBe "NonEmpty"
struct.modifiers.any { it == KModifier.DATA } shouldBe true
struct.funSpecs.any { it.name == "toString" } shouldBe false
struct.funSpecs.any { it.name == "hashCode" } shouldBe false
struct.funSpecs.any { it.name == "equals" } shouldBe false
}
@Test
fun `exceptions with reserved field names get renamed fields`() {
val thrift = """
namespace kt com.test
exception Fail { 1: required list<i32> Message }
""".trimIndent()
val schema = load(thrift)
val specs = KotlinCodeGenerator(FieldNamingPolicy.JAVA).generate(schema)
specs.shouldCompile()
val xception = specs.single().members.single() as TypeSpec
xception.propertySpecs.single().name shouldBe "message_"
}
@Test
fun `union with error as field name should compile with builder`() {
val thrift = """
namespace kt com.test
union Fail { 1: string error }
""".trimIndent()
val specs = generate(thrift) {
withDataClassBuilders()
}
specs.shouldCompile()
}
@Test
fun services() {
val thrift = """
namespace kt test.services
struct Foo { 1: required string foo; }
struct Bar { 1: required string bar; }
exception X { 1: required string message; }
service Svc {
void doThingOne(1: Foo foo) throws (2: X xxxx)
Bar doThingTwo(1: Foo foo) throws (1: X x)
}
""".trimIndent()
val specs = generate(thrift)
specs.shouldCompile()
specs.forEach { println(it) }
}
@Test
fun server() {
val thrift = """
namespace kt test.services
struct Foo { 1: required string foo; }
struct Bar { 1: required string bar; }
exception X { 1: required string message; }
service Svc {
void doThingOne(1: Foo foo) throws (2: X xxxx)
Bar doThingTwo(1: Foo foo) throws (1: X x)
}
""".trimIndent()
val specs = generate(thrift) {
generateServer()
withDataClassBuilders()
}
specs.shouldCompile()
specs.forEach { println(it) }
}
@Test
fun `typedefs become typealiases`() {
val thrift = """
namespace kt test.typedefs
typedef map<i32, map<string, double>> FooMap;
struct HasMap {
1: optional FooMap theMap;
}
""".trimIndent()
val specs = generate(thrift)
specs.shouldCompile()
specs.forEach { println(it) }
}
@Test
fun `services that return typedefs`() {
val thrift = """
namespace kt test.typedefs
typedef i32 TheNumber;
service Foo {
TheNumber doIt()
}
""".trimIndent()
val file = generate(thrift).single()
file.shouldCompile()
val svc = file.members.first { it is TypeSpec && it.name == "Foo" } as TypeSpec
val method = svc.funSpecs.single()
method.name shouldBe "doIt"
method.parameters.single().type shouldBe ServiceMethodCallback::class
.asTypeName()
.parameterizedBy(ClassName("test.typedefs", "TheNumber"))
}
@Test
fun `constants that are typedefs`() {
val thrift = """
|namespace kt test.typedefs
|
|typedef map<i32, i32> Weights
|
|const Weights WEIGHTS = {1: 2}
""".trimMargin()
"${generate(thrift).single()}" shouldBe """
|package test.typedefs
|
|import kotlin.Int
|import kotlin.collections.Map
|
|public typealias Weights = Map<Int, Int>
|
|public val WEIGHTS: Weights = mapOf(1 to 2)
|
""".trimMargin()
}
@Test
fun `Parcelize annotations for structs and enums`() {
val thrift = """
|namespace kt test.parcelize
|
|struct Foo { 1: required i32 Number; 2: optional string Text }
|
|enum AnEnum { ONE; TWO; THREE }
|
|service Svc {
| Foo getFoo(1: AnEnum anEnum)
|}
""".trimMargin()
val file = generate(thrift) { parcelize() }.single()
val struct = file.members.single { it is TypeSpec && it.name == "Foo" } as TypeSpec
val anEnum = file.members.single { it is TypeSpec && it.name == "AnEnum" } as TypeSpec
val svc = file.members.single { it is TypeSpec && it.name == "SvcClient" } as TypeSpec
val parcelize = ClassName("kotlinx.android.parcel", "Parcelize")
struct.annotationSpecs.any { it.typeName == parcelize } shouldBe true
anEnum.annotationSpecs.any { it.typeName == parcelize } shouldBe true
svc.annotationSpecs.any { it.typeName == parcelize } shouldBe false
}
@Test
fun `Custom map-type constants`() {
val thrift = """
|namespace kt test.map_consts
|
|const map<i32, list<string>> Maps = {1: [], 2: ["foo"]}
""".trimMargin()
val text = generate(thrift) {
mapClassName("android.support.v4.util.ArrayMap")
emitFileComment(false)
}
.single()
.toString()
text shouldBe """
|package test.map_consts
|
|import android.support.v4.util.ArrayMap
|import kotlin.Int
|import kotlin.String
|import kotlin.collections.List
|import kotlin.collections.Map
|
|public val Maps: Map<Int, List<String>> = ArrayMap<Int, List<String>>(2).apply {
| put(1, emptyList())
| put(2, listOf("foo"))
| }
|
""".trimMargin()
}
@Test
fun `suspend-fun service clients`() {
val thrift = """
|namespace kt test.coro
|
|service Svc {
| i32 doSomething(1: i32 foo);
|}
""".trimMargin()
val file = generate(thrift) { coroutineServiceClients() }
file.shouldCompile()
file.single().toString() should contain("""
|public interface Svc {
| public suspend fun doSomething(foo: Int): Int
|}
|
|public class SvcClient(
| protocol: Protocol,
| listener: AsyncClientBase.Listener,
|) : AsyncClientBase(protocol, listener), Svc {
| public override suspend fun doSomething(foo: Int): Int = suspendCoroutine { cont ->
| this.enqueue(DoSomethingCall(foo, object : ServiceMethodCallback<Int> {
| public override fun onSuccess(result: Int): Unit {
| cont.resumeWith(Result.success(result))
| }
|
| public override fun onError(error: Throwable): Unit {
| cont.resumeWith(Result.failure(error))
| }
| }))
| }
|
""".trimMargin())
}
@Test
fun `omit service clients`() {
val thrift = """
|namespace kt test.omit_service_clients
|
|service Svc {
| i32 doSomething(1: i32 foo);
|}
""".trimMargin()
val file = generate(thrift) { omitServiceClients() }
file shouldBe emptyList()
}
@Test
fun `Emit @JvmName file-per-namespace annotations`() {
val thrift = """
|namespace kt test.consts
|
|const i32 FooNum = 42
""".trimMargin()
val file = generate(thrift) {
emitJvmName()
filePerNamespace()
emitFileComment(false)
}
.single()
file.shouldCompile()
file.toString() shouldBe """
|@file:JvmName("ThriftTypes")
|
|package test.consts
|
|import kotlin.Int
|import kotlin.jvm.JvmName
|
|public const val FooNum: Int = 42
|
""".trimMargin()
}
@Test
fun `Emit @JvmName file-per-type annotations`() {
val thrift = """
|namespace kt test.consts
|
|const i32 FooNum = 42
""".trimMargin()
val file = generate(thrift) {
emitJvmName()
filePerType()
emitFileComment(false)
}
.single()
file.shouldCompile()
file.toString() shouldBe """
|@file:JvmName("Constants")
|
|package test.consts
|
|import kotlin.Int
|import kotlin.jvm.JvmName
|
|public const val FooNum: Int = 42
|
""".trimMargin()
}
@Test
fun `union generate sealed`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift) { coroutineServiceClients() }
file.shouldCompile()
file.single().toString() should contain("""
|sealed class Union : Struct {
""".trimMargin())
}
@Test
fun `union properties as data`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift) { coroutineServiceClients() }
file.shouldCompile()
file.single().toString() should contain("""
|
| public data class Foo(
| public val `value`: Int,
| ) : Union() {
| public override fun toString(): String = "Union(Foo=${'$'}value)"
| }
|
| public data class Bar(
| public val `value`: Long,
| ) : Union() {
| public override fun toString(): String = "Union(Bar=${'$'}value)"
| }
|
| public data class Baz(
| public val `value`: String,
| ) : Union() {
| public override fun toString(): String = "Union(Baz=${'$'}value)"
| }
|
| public data class NotFoo(
| public val `value`: Int,
| ) : Union() {
| public override fun toString(): String = "Union(NotFoo=${'$'}value)"
| }
|
""".trimMargin())
}
@Test
fun `union has builder`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift) { withDataClassBuilders() }
file.shouldCompile()
file.single().toString() should contain("""
| public class Builder : StructBuilder<Union> {
| private var value_: Union? = null
|
| public constructor()
|
| public constructor(source: Union) : this() {
| this.value_ = source
| }
|
| public override fun build(): Union = value_ ?:
| error("Invalid union; at least one value is required")
|
| public override fun reset(): Unit {
| value_ = null
| }
|
| public fun Foo(`value`: Int) = apply { this.value_ = Union.Foo(value) }
|
| public fun Bar(`value`: Long) = apply { this.value_ = Union.Bar(value) }
|
| public fun Baz(`value`: String) = apply { this.value_ = Union.Baz(value) }
|
| public fun NotFoo(`value`: Int) = apply { this.value_ = Union.NotFoo(value) }
| }
""".trimMargin())
}
@Test
fun `union wont generate builder when disabled`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift)
file.shouldCompile()
file.single().toString() shouldNot contain("""
| class Builder
""".trimMargin())
}
@Test
fun `union wont generate struct when disabled`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift) //{ shouldImplementStruct() }
file.shouldCompile()
file.single().toString() shouldNot contain("""
| : Struct
""".trimMargin())
file.single().toString() shouldNot contain("""
| write
""".trimMargin())
}
@Test
fun `union generate read function`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift) { withDataClassBuilders() }
file.shouldCompile()
file.single().toString() should contain("""
| public override fun read(protocol: Protocol) = read(protocol, Builder())
|
| public override fun read(protocol: Protocol, builder: Builder): Union {
| protocol.readStructBegin()
| while (true) {
| val fieldMeta = protocol.readFieldBegin()
| if (fieldMeta.typeId == TType.STOP) {
| break
| }
| when (fieldMeta.fieldId.toInt()) {
| 1 -> {
| if (fieldMeta.typeId == TType.I32) {
| val Foo = protocol.readI32()
| builder.Foo(Foo)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| 2 -> {
| if (fieldMeta.typeId == TType.I64) {
| val Bar = protocol.readI64()
| builder.Bar(Bar)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| 3 -> {
| if (fieldMeta.typeId == TType.STRING) {
| val Baz = protocol.readString()
| builder.Baz(Baz)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| 4 -> {
| if (fieldMeta.typeId == TType.I32) {
| val NotFoo = protocol.readI32()
| builder.NotFoo(NotFoo)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| else -> ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| protocol.readFieldEnd()
| }
| protocol.readStructEnd()
| return builder.build()
| }
""".trimMargin())
}
@Test
fun `union generate read function without builder`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift)
file.shouldCompile()
file.single().toString() should contain("""
| public override fun read(protocol: Protocol): Union {
| protocol.readStructBegin()
| var result : Union? = null
| while (true) {
| val fieldMeta = protocol.readFieldBegin()
| if (fieldMeta.typeId == TType.STOP) {
| break
| }
| when (fieldMeta.fieldId.toInt()) {
| 1 -> {
| if (fieldMeta.typeId == TType.I32) {
| val Foo = protocol.readI32()
| result = Foo(Foo)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| 2 -> {
| if (fieldMeta.typeId == TType.I64) {
| val Bar = protocol.readI64()
| result = Bar(Bar)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| 3 -> {
| if (fieldMeta.typeId == TType.STRING) {
| val Baz = protocol.readString()
| result = Baz(Baz)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| 4 -> {
| if (fieldMeta.typeId == TType.I32) {
| val NotFoo = protocol.readI32()
| result = NotFoo(NotFoo)
| } else {
| ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| }
| else -> ProtocolUtil.skip(protocol, fieldMeta.typeId)
| }
| protocol.readFieldEnd()
| }
| protocol.readStructEnd()
| return result ?: error("unreadable")
| }
""".trimMargin())
}
@Test
fun `union generate Adapter with builder`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift) { withDataClassBuilders() }
file.shouldCompile()
file.single().toString() should contain("""
| private class UnionAdapter : Adapter<Union, Builder> {
""".trimMargin())
}
@Test
fun `union generate Adapter`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
| 1: i32 Foo;
| 2: i64 Bar;
| 3: string Baz;
| 4: i32 NotFoo;
|}
""".trimMargin()
val file = generate(thrift)
file.shouldCompile()
file.single().toString() should contain("""
| private class UnionAdapter : Adapter<Union> {
""".trimMargin())
}
@Test
fun `empty union generate non-sealed class`() {
val thrift = """
|namespace kt test.coro
|
|union Union {
|}
""".trimMargin()
val file = generate(thrift) { coroutineServiceClients() }
file.shouldCompile()
file.single().toString() should contain("""
|class Union() : Struct {
""".trimMargin())
}
@Test
fun `struct with union`() {
val thrift = """
|namespace kt test.coro
|
|struct Bonk {
| 1: string message;
| 2: i32 type;
|}
|
|union UnionStruct {
| 1: Bonk Struct
|}
""".trimMargin()
val file = generate(thrift) { withDataClassBuilders() }
file.shouldCompile()
file.single().toString() should contain("""
|public sealed class UnionStruct : Struct {
| public override fun write(protocol: Protocol): Unit {
| ADAPTER.write(protocol, this)
| }
|
| public data class Struct(
| public val `value`: Bonk,
| ) : UnionStruct() {
| public override fun toString(): String = "UnionStruct(Struct=${'$'}value)"
| }
|
| public class Builder : StructBuilder<UnionStruct> {
""".trimMargin())
}
@Test
fun `union with default value`() {
val thrift = """
namespace kt test.union
union HasDefault {
1: i8 b;
2: i16 short;
3: i32 int = 16;
4: i64 long;
}
""".trimIndent()
val file = generate(thrift)
file.shouldCompile()
file.single().toString() should contain("""
| @JvmField
| public val DEFAULT: HasDefault = Int(16)
""".trimMargin())
}
@Test
fun `builder has correct syntax`() {
val thrift = """
|namespace kt test.builder
|
|struct Bonk {
| 1: string message;
| 2: i32 type;
|}
""".trimMargin()
val file = generate(thrift) { withDataClassBuilders() }
file.shouldCompile()
file.single().toString() should contain("""
| public override fun build(): Bonk = Bonk(message = this.message, type = this.type)
""".trimMargin())
}
@Test
fun `enum fail on unknown value`() {
val thrift = """
|namespace kt test.struct
|
|enum TestEnum { FOO }
|
|struct HasEnum {
| 1: optional TestEnum field = TestEnum.FOO;
|}
""".trimMargin()
val expected = """
1 -> {
if (fieldMeta.typeId == TType.I32) {
val field_ = protocol.readI32().let {
TestEnum.findByValue(it) ?: throw
ThriftException(ThriftException.Kind.PROTOCOL_ERROR,
"Unexpected value for enum type TestEnum: ${'$'}it")
}
builder.field_(field_)
} else {
ProtocolUtil.skip(protocol, fieldMeta.typeId)
}
}"""
val file = generate(thrift) { withDataClassBuilders() }
file.shouldCompile()
file.single().toString() shouldContain expected
}
@Test
fun `enum don't fail on unknown value`() {
val thrift = """
|namespace kt test.struct
|
|enum TestEnum { FOO }
|
|struct HasEnum {
| 1: optional TestEnum field1 = TestEnum.FOO;
| 2: required TestEnum field2 = TestEnum.FOO;
|}
""".trimMargin()
val expected = """
1 -> {
if (fieldMeta.typeId == TType.I32) {
val field1 = protocol.readI32().let {
TestEnum.findByValue(it)
}
field1?.let {
builder.field1(it)
}
} else {
ProtocolUtil.skip(protocol, fieldMeta.typeId)
}
}
2 -> {
if (fieldMeta.typeId == TType.I32) {
val field2 = protocol.readI32().let {
TestEnum.findByValue(it) ?: throw
ThriftException(ThriftException.Kind.PROTOCOL_ERROR,
"Unexpected value for enum type TestEnum: ${'$'}it")
}
builder.field2(field2)
} else {
ProtocolUtil.skip(protocol, fieldMeta.typeId)
}
}"""
val file = generate(thrift) {
withDataClassBuilders()
failOnUnknownEnumValues(false)
}
file.shouldCompile()
file.single().toString() shouldContain expected
}
@Test
fun `enum don't fail on unknown value without builder`() {
val thrift = """
|namespace kt test.struct
|
|enum TestEnum { FOO }
|
|struct HasEnum {
| 1: optional TestEnum field1 = TestEnum.FOO;
| 2: required TestEnum field2 = TestEnum.FOO;
|}
""".trimMargin()
val expected = """
1 -> {
if (fieldMeta.typeId == TType.I32) {
val field1 = protocol.readI32().let {
TestEnum.findByValue(it)
}
field1?.let {
_local_field1 = it
}
} else {
ProtocolUtil.skip(protocol, fieldMeta.typeId)
}
}
2 -> {
if (fieldMeta.typeId == TType.I32) {
val field2 = protocol.readI32().let {
TestEnum.findByValue(it) ?: throw
ThriftException(ThriftException.Kind.PROTOCOL_ERROR,
"Unexpected value for enum type TestEnum: ${'$'}it")
}
_local_field2 = field2
} else {
ProtocolUtil.skip(protocol, fieldMeta.typeId)
}
}"""
val file = generate(thrift) { failOnUnknownEnumValues(false) }
file.shouldCompile()
file.single().toString() shouldContain expected
}
@Test
fun `struct built with required constructor`() {
val thrift = """
|namespace kt test.struct
|
|struct TestStruct {
| 1: required i64 field1;
| 2: optional bool field2;
|}
""".trimMargin()
val expected = """
public constructor(field1: Long) {
this.field1 = field1
this.field2 = null
}"""
val file = generate(thrift) {
withDataClassBuilders()
builderRequiredConstructor()
}
file.shouldCompile()
file.single().toString() shouldContain expected
}
@Test
fun `default constructor marked deprecated when required constructor enabled`() {
val thrift = """
|namespace kt test.struct
|
|struct TestStruct {
| 1: required i64 field1;
| 2: optional bool field2;
|}
""".trimMargin()
val expected = """
@Deprecated(
message = "Empty constructor deprecated, use required constructor instead",
replaceWith = ReplaceWith("Builder(field1)"),
)"""
val file = generate(thrift) {
withDataClassBuilders()
builderRequiredConstructor()
}
file.shouldCompile()
file.single().toString() shouldContain expected
}
@Test
fun `omit required constructor when no required parameters supplied`() {
val thrift = """
|namespace kt test.struct
|
|struct TestStruct {
| 1: optional i64 field1;
| 2: optional bool field2;
|}
""".trimMargin()
val notExpected = "@Deprecated("
val expected = """
public constructor() {
this.field1 = null
this.field2 = null
}"""
val file = generate(thrift) {
withDataClassBuilders()
builderRequiredConstructor()
}
file.shouldCompile()
file.single().toString() shouldContain expected
file.single().toString() shouldNotContain notExpected
}
@Test
fun `collection types do not use Java collections by default`() {
val thrift = """
|namespace kt test.lists
|
|const list<i32> FOO = [1, 2, 3];
|const map<i8, i8> BAR = { 1: 2 };
|const set<string> BAZ = ["foo", "bar", "baz"];
|
|struct HasCollections {
| 1: list<string> strs;
| 2: map<string, string> more_strs;
| 3: set<i16> shorts;
|}
|
|service HasListMethodArg {
| list<i8> sendThatList(1: list<i8> byteList);
|}
""".trimMargin()
for (file in generate(thrift)) {
val kt = file.toString()
kt shouldNotContain "java.util"
}
}
@Test
fun `does not import java Exception or IOException`() {
val thrift = """
|namespace kt test.exceptions
|
|exception Foo {
| 1: string message;
|}
""".trimMargin()
for (file in generate(thrift)) {
val kt = file.toString()
kt shouldNotContain "import java.Exception"
kt shouldNotContain "import java.io.IOException"
}
}
@Test
fun `uses default Throws instead of jvm Throws`() {
val thrift = """
|namespace kt test.throws
|
|service Frobbler {
| void frobble(1: string bizzle);
|}
""".trimMargin()
for (file in generate(thrift)) {
val kt = file.toString()
kt shouldContain "@Throws"
kt shouldNotContain "import kotlin.jvm.Throws"
}
}
@Test
fun `empty structs do not rely on javaClass for hashCode`() {
val thrift = """
|namespace kt test.empty
|
|struct Empty {}
""".trimMargin()
val file = generate(thrift).single()
val kt = file.toString()
kt shouldContain "hashCode(): Int = \"test.empty.Empty\".hashCode()"
kt shouldNotContain "javaClass"
}
@Test
fun `big enum generation`() {
val thrift = """
namespace kt test.enum
enum Foo {
FIRST_VALUE = 0,
SECOND_VALUE = 1,
THIRD_VALUE = 2
}
""".trimIndent()
val expected = """
|public enum class Foo {
| FIRST_VALUE,
| SECOND_VALUE,
| THIRD_VALUE,
| ;
|
| public val `value`: Int
| get() = `value`()
|
| public fun `value`(): Int = when (this) {
| FIRST_VALUE -> 0
| SECOND_VALUE -> 1
| THIRD_VALUE -> 2
| }
|
| public companion object {
| public fun findByValue(`value`: Int): Foo? = when (`value`) {
| 0 -> FIRST_VALUE
| 1 -> SECOND_VALUE
| 2 -> THIRD_VALUE
| else -> null
| }
| }
|}
""".trimMargin()
val notExpected = """
public enum class Foo(value: Int)
""".trimIndent()
val file = generate(thrift) {
emitBigEnums()
}
file.single().toString() shouldContain expected
file.single().toString() shouldNotContain notExpected
}
@Test
fun `struct-valued constant`() {
val thrift = """
|namespace kt test.struct
|
|struct Foo {
| 1: string text;
| 2: Bar bar;
| 3: Baz baz;
| 4: Quux quux;
|}
|
|struct Bar {
| 1: map<string, list<string>> keys;
|}
|
|enum Baz {
| ONE,
| TWO,
| THREE
|}
|
|struct Quux {
| 1: string s;
|}
|
|const Quux THE_QUUX = {
| "s": "s"
|}
|
|const Foo THE_FOO = {
| "text": "some text",
| "bar": {
| "keys": {
| "letters": ["a", "b", "c"],
| }
| },
| "baz": Baz.ONE,
| "quux": THE_QUUX
|}
""".trimMargin()
val expected = """
|public val THE_FOO: Foo = Foo(
| text = "some text",
| bar = Bar(
| keys = mapOf("letters" to listOf("a", "b", "c")),
| ),
| baz = test.struct.Baz.ONE,
| quux = test.struct.THE_QUUX,
| )
""".trimMargin()
val file = generate(thrift).single()
file.toString() shouldContain expected
file.shouldCompile()
}
@Test
fun `struct-valued constants with builders`() {
val thrift = """
|namespace kt test.struct
|
|struct Foo {
| 1: string text;
| 2: Bar bar;
| 3: Baz baz;
| 4: Quux quux;
|}
|
|struct Bar {
| 1: map<string, list<string>> keys;
|}
|
|enum Baz {
| ONE,
| TWO,
| THREE
|}
|
|struct Quux {
| 1: string s;
|}
|
|const Quux THE_QUUX = {
| "s": "s"
|}
|
|const Foo THE_FOO = {
| "text": "some text",
| "bar": {
| "keys": {
| "letters": ["a", "b", "c"],
| }
| },
| "baz": Baz.ONE,
| "quux": THE_QUUX
|}
""".trimMargin()
val expected = """
|public val THE_FOO: Foo = Foo.Builder().let {
| it.text("some text")
| it.bar(Bar.Builder().let {
| it.keys(mapOf("letters" to listOf("a", "b", "c")))
| it.build()
| })
| it.baz(test.struct.Baz.ONE)
| it.quux(test.struct.THE_QUUX)
| it.build()
| }
""".trimMargin()
val file = generate(thrift) { withDataClassBuilders() }.single()
file.toString() shouldContain expected
file.shouldCompile()
}
@Test
fun `Files should add generated comment`() {
val thrift = """
|namespace kt test.comment
|
|const i32 FooNum = 42
""".trimMargin()
val file = generate(thrift) { emitFileComment(true) }
.single()
file.shouldCompile()
val lines = file.toString().split("\n")
lines[0] shouldBe "// Automatically generated by the Thrifty compiler; do not edit!"
lines[1] shouldContain "\\/\\/ Generated on: [0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.\\S+".toRegex()
}
private fun generate(thrift: String, config: (KotlinCodeGenerator.() -> KotlinCodeGenerator)? = null): List<FileSpec> {
val configOrDefault = config ?: { emitFileComment(false) }
return KotlinCodeGenerator()
.run(configOrDefault)
.generate(load(thrift))
}
private fun load(thrift: String): Schema {
val file = File(tempDir, "test.thrift").also { it.writeText(thrift) }
val loader = Loader().apply { addThriftFile(file.toPath()) }
return loader.load()
}
}
| apache-2.0 | 7d9c258ed5bd6a182d6c66b8025577f7 | 29.097614 | 124 | 0.467171 | 4.599448 | false | true | false | false |
yunv/BJUTWiFi | app/src/main/kotlin/me/liuyun/bjutlgn/util/ThemeHelper.kt | 1 | 3524 | package me.liuyun.bjutlgn.util
import android.app.Activity
import android.app.ActivityManager.TaskDescription
import android.app.Application
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.TypedValue
import androidx.annotation.StyleRes
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import me.liuyun.bjutlgn.R
import me.liuyun.bjutlgn.ui.EasterEggActivity
import me.liuyun.bjutlgn.ui.StatusLockedActivity
import java.util.*
object ThemeHelper : Application.ActivityLifecycleCallbacks {
private val activityList = ArrayList<Activity>()
@StyleRes
var currentStyle: Int = 0
private set
fun init(application: Application, @StyleRes styleRes: Int) {
application.registerActivityLifecycleCallbacks(this)
this.currentStyle = styleRes
}
@StyleRes
fun getTheme(context: Context): Int {
val prefs = PreferenceManager.getDefaultSharedPreferences(context)
val theme = prefs.getInt("theme", R.style.ThemeBlue)
if (theme !in ThemeRes.values().map { it.style }) {
prefs.edit { putInt("theme", R.style.ThemeBlue) }
return R.style.ThemeBlue
}
return theme
}
fun setTheme(activity: Activity, @StyleRes styleRes: Int) {
currentStyle = styleRes
PreferenceManager.getDefaultSharedPreferences(activity).edit { putInt("theme", currentStyle) }
activityList.filter { it !== activity }.forEach { it.recreate() }
val intent = Intent(activity, activity.javaClass)
activity.startActivity(intent)
activity.overridePendingTransition(R.anim.alpha_in, R.anim.alpha_out)
activity.finish()
}
fun getThemePrimaryColor(context: Context): Int {
val value = TypedValue()
context.theme.resolveAttribute(R.attr.colorPrimary, value, true)
return value.data
}
fun getThemeAccentColor(context: Context): Int {
val value = TypedValue()
context.theme.resolveAttribute(R.attr.colorAccent, value, true)
return value.data
}
fun getThemeSecondaryColor(context: Context): Int {
val value = TypedValue()
context.theme.resolveAttribute(android.R.attr.colorSecondary, value, true)
return value.data
}
private fun setTaskDescription(activity: Activity) {
val taskDescription = TaskDescription(activity.getString(R.string.app_name),
R.mipmap.ic_launcher, getThemePrimaryColor(activity))
activity.setTaskDescription(taskDescription)
}
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
activityList.add(activity)
when (activity.javaClass.simpleName) {
StatusLockedActivity::class.java.simpleName -> activity.setTheme(R.style.AppTheme_Dialog)
EasterEggActivity::class.java.simpleName -> activity.setTheme(android.R.style.Theme_Wallpaper_NoTitleBar)
else -> activity.setTheme(currentStyle)
}
setTaskDescription(activity)
}
override fun onActivityStarted(activity: Activity) = Unit
override fun onActivityResumed(activity: Activity) = Unit
override fun onActivityPaused(activity: Activity) = Unit
override fun onActivityStopped(activity: Activity) = Unit
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit
override fun onActivityDestroyed(activity: Activity) {
activityList.remove(activity)
}
}
| mit | c2abcabcccb5b89206b8b3a40897aae6 | 36.489362 | 117 | 0.712259 | 4.618611 | false | false | false | false |
Major-/Vicis | legacy/src/main/kotlin/rs/emulate/legacy/widget/WidgetBuilder.kt | 1 | 1313 | package rs.emulate.legacy.widget
import rs.emulate.legacy.widget.script.LegacyClientScript
import rs.emulate.legacy.widget.type.Option
/**
* A builder for a [Widget].
*/
class WidgetBuilder {
/**
* The alpha of the Widget.
*/
private var alpha: Int = 0
/**
* The content type of the Widget.
*/
private var content: Int = 0
/**
* The WidgetGroup of the Widget.
*/
private var group: WidgetGroup? = null
/**
* The height of the Widget, in pixels.
*/
private var height: Int = 0
/**
* The hover id of the Widget.
*/
private var hover: Int? = null
/**
* The hover text of this Widget.
*/
private var hoverText: String? = null
/**
* The id of the Widget.
*/
private var id: Int = 0
/**
* The Option of this Widget.
*/
private var option: Option? = null
/**
* The WidgetOption of the Widget.
*/
private var optionType: WidgetOption? = null
/**
* The parent of the Widget.
*/
private var parent: Int? = null
/**
* The [LegacyClientScript]s of the Widget.
*/
private var scripts: List<LegacyClientScript>? = null
/**
* The width of this Widget, in pixels.
*/
private var width: Int = 0
}
| isc | b81b1bdecc828f566ce9d1c252912412 | 17.492958 | 57 | 0.565118 | 3.966767 | false | false | false | false |
WhisperSystems/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/database/ChatColorsDatabase.kt | 1 | 4823 | package org.thoughtcrime.securesms.database
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import org.thoughtcrime.securesms.conversation.colors.ChatColors
import org.thoughtcrime.securesms.database.helpers.SQLCipherOpenHelper
import org.thoughtcrime.securesms.database.model.databaseprotos.ChatColor
import org.thoughtcrime.securesms.dependencies.ApplicationDependencies
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.CursorUtil
import org.thoughtcrime.securesms.util.SqlUtil
class ChatColorsDatabase(context: Context, databaseHelper: SQLCipherOpenHelper) : Database(context, databaseHelper) {
companion object {
private const val TABLE_NAME = "chat_colors"
private const val ID = "_id"
private const val CHAT_COLORS = "chat_colors"
@JvmField
val CREATE_TABLE = """
CREATE TABLE $TABLE_NAME (
$ID INTEGER PRIMARY KEY AUTOINCREMENT,
$CHAT_COLORS BLOB
)
""".trimIndent()
}
fun getById(chatColorsId: ChatColors.Id): ChatColors {
val db = databaseHelper.signalReadableDatabase
val projection = arrayOf(ID, CHAT_COLORS)
val args = SqlUtil.buildArgs(chatColorsId.longValue)
db.query(TABLE_NAME, projection, ID_WHERE, args, null, null, null)?.use {
if (it.moveToFirst()) {
return it.getChatColors()
}
}
throw IllegalArgumentException("Could not locate chat color $chatColorsId")
}
fun saveChatColors(chatColors: ChatColors): ChatColors {
return when (chatColors.id) {
is ChatColors.Id.Auto -> throw AssertionError("Saving 'auto' does not make sense")
is ChatColors.Id.BuiltIn -> chatColors
is ChatColors.Id.NotSet -> insertChatColors(chatColors)
is ChatColors.Id.Custom -> updateChatColors(chatColors)
}
}
fun getSavedChatColors(): List<ChatColors> {
val db = databaseHelper.signalReadableDatabase
val projection = arrayOf(ID, CHAT_COLORS)
val result = mutableListOf<ChatColors>()
db.query(TABLE_NAME, projection, null, null, null, null, null)?.use {
while (it.moveToNext()) {
result.add(it.getChatColors())
}
}
return result
}
private fun insertChatColors(chatColors: ChatColors): ChatColors {
if (chatColors.id != ChatColors.Id.NotSet) {
throw IllegalArgumentException("Bad chat colors to insert.")
}
val db: SQLiteDatabase = databaseHelper.signalWritableDatabase
val values = ContentValues(1).apply {
put(CHAT_COLORS, chatColors.serialize().toByteArray())
}
val rowId = db.insert(TABLE_NAME, null, values)
if (rowId == -1L) {
throw IllegalStateException("Failed to insert ChatColor into database")
}
notifyListeners()
return chatColors.withId(ChatColors.Id.forLongValue(rowId))
}
private fun updateChatColors(chatColors: ChatColors): ChatColors {
if (chatColors.id == ChatColors.Id.NotSet || chatColors.id == ChatColors.Id.BuiltIn) {
throw IllegalArgumentException("Bad chat colors to update.")
}
val db: SQLiteDatabase = databaseHelper.signalWritableDatabase
val values = ContentValues(1).apply {
put(CHAT_COLORS, chatColors.serialize().toByteArray())
}
val rowsUpdated = db.update(TABLE_NAME, values, ID_WHERE, SqlUtil.buildArgs(chatColors.id.longValue))
if (rowsUpdated < 1) {
throw IllegalStateException("Failed to update ChatColor in database")
}
if (SignalStore.chatColorsValues().chatColors?.id == chatColors.id) {
SignalStore.chatColorsValues().chatColors = chatColors
}
val recipientDatabase = DatabaseFactory.getRecipientDatabase(context)
recipientDatabase.onUpdatedChatColors(chatColors)
notifyListeners()
return chatColors
}
fun deleteChatColors(chatColors: ChatColors) {
if (chatColors.id == ChatColors.Id.NotSet || chatColors.id == ChatColors.Id.BuiltIn) {
throw IllegalArgumentException("Cannot delete this chat color")
}
val db: SQLiteDatabase = databaseHelper.signalWritableDatabase
db.delete(TABLE_NAME, ID_WHERE, SqlUtil.buildArgs(chatColors.id.longValue))
if (SignalStore.chatColorsValues().chatColors?.id == chatColors.id) {
SignalStore.chatColorsValues().chatColors = null
}
val recipientDatabase = DatabaseFactory.getRecipientDatabase(context)
recipientDatabase.onDeletedChatColors(chatColors)
notifyListeners()
}
private fun notifyListeners() {
ApplicationDependencies.getDatabaseObserver().notifyChatColorsListeners()
}
private fun Cursor.getId(): Long = CursorUtil.requireLong(this, ID)
private fun Cursor.getChatColors(): ChatColors = ChatColors.forChatColor(
ChatColors.Id.forLongValue(getId()),
ChatColor.parseFrom(CursorUtil.requireBlob(this, CHAT_COLORS))
)
}
| gpl-3.0 | 0d1933925ce8932f6b58380e63fe51ea | 33.697842 | 117 | 0.730251 | 4.420715 | false | false | false | false |
team401/SnakeSkin | SnakeSkin-Core/src/main/kotlin/org/snakeskin/compiler/AnnotatedRunnableGenerator.kt | 1 | 3015 | package org.snakeskin.compiler
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.JavaFile
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.TypeSpec
import javax.annotation.processing.ProcessingEnvironment
import javax.lang.model.element.*
import javax.tools.Diagnostic
/**
* @author Cameron Earle
* @version 6/26/17
*/
class AnnotatedRunnableGenerator(val env: ProcessingEnvironment, val annotationName: String) {
companion object {
const val RUN_METHOD = "run"
const val GET_NAME_METHOD = "getName"
fun getMethodQualifiedName(method: ExecutableElement): String {
val type = method.enclosingElement as TypeElement
return "${type.qualifiedName}.${method.simpleName}"
}
}
private fun getWrapperClassName(typeName: String, method: ExecutableElement): String {
val name = method.simpleName.toString()
val capitalized = Character.toUpperCase(name.first()) + name.substring(1)
return typeName + capitalized + "Wrapper"
}
private fun getWrapperClassName(method: ExecutableElement): String {
val type = method.enclosingElement as TypeElement
return getWrapperClassName(type.qualifiedName.toString(), method)
}
private fun getWrapperSimpleName(method: ExecutableElement): String {
val type = method.enclosingElement as TypeElement
return getWrapperClassName(type.simpleName.toString(), method)
}
private fun getPackageName(element: Element): String? {
var e: Element? = element
while (e != null) {
if (e.kind == ElementKind.PACKAGE) {
return (e as PackageElement).qualifiedName.toString()
}
e = e.enclosingElement
}
return null
}
fun generate(method: ExecutableElement): String {
val className = getWrapperClassName(method)
val simpleName = getWrapperSimpleName(method)
val methodQualifiedName = getMethodQualifiedName(method)
val packageName = getPackageName(method)
val runMethodSpec = MethodSpec.methodBuilder(RUN_METHOD)
.addModifiers(Modifier.PUBLIC)
.returns(Void.TYPE)
.addStatement("\$L()", methodQualifiedName)
.build()
val getNameMethodSpec = MethodSpec.methodBuilder(GET_NAME_METHOD)
.addModifiers(Modifier.PUBLIC)
.returns(String::class.java)
.addStatement("return \$S", annotationName)
.build()
val classSpec = TypeSpec.classBuilder(simpleName)
.addModifiers(Modifier.PUBLIC, Modifier.FINAL)
.addSuperinterface(AnnotatedRunnable::class.java)
.addMethod(runMethodSpec)
.addMethod(getNameMethodSpec)
.build()
val javaFile = JavaFile.builder(packageName ?: "", classSpec).build()
javaFile.writeTo(env.filer)
return className
}
} | gpl-3.0 | fa9bfdee447f5b87c56ac976684fb33d | 35.337349 | 94 | 0.657048 | 5.136286 | false | false | false | false |
spinnaker/orca | orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/pending/DualPendingExecutionServiceTest.kt | 1 | 5824 | package com.netflix.spinnaker.orca.q.pending
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.netflix.spectator.api.NoopRegistry
import com.netflix.spinnaker.config.DualPendingExecutionServiceConfiguration
import com.netflix.spinnaker.kork.jedis.EmbeddedRedis
import com.netflix.spinnaker.orca.api.test.pipeline
import com.netflix.spinnaker.orca.api.test.stage
import com.netflix.spinnaker.orca.q.PendingExecutionServiceTest
import com.netflix.spinnaker.orca.q.RestartStage
import com.netflix.spinnaker.orca.q.StartExecution
import com.netflix.spinnaker.orca.q.redis.pending.RedisPendingExecutionService
import com.netflix.spinnaker.q.Message
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.verify
import java.util.UUID
import org.assertj.core.api.Assertions
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.given
import org.jetbrains.spek.api.dsl.it
import org.jetbrains.spek.api.dsl.on
import org.jetbrains.spek.subject.SubjectSpek
import org.jetbrains.spek.subject.itBehavesLike
internal object DualPendingExecutionServiceTest : SubjectSpek<DualPendingExecutionService>({
itBehavesLike(PendingExecutionServiceTest)
val primaryRedis = EmbeddedRedis.embed()
val previousRedis = EmbeddedRedis.embed()
val mapper = ObjectMapper().apply {
registerModule(KotlinModule.Builder().build())
registerSubtypes(StartExecution::class.java, RestartStage::class.java)
}
val primaryService = RedisPendingExecutionService(primaryRedis.pool, mapper)
val previousService = RedisPendingExecutionServiceProxy(
RedisPendingExecutionService(previousRedis.pool, mapper)
)
val properties = DualPendingExecutionServiceConfiguration().apply {
enabled = true
primaryClass = "com.netflix.spinnaker.orca.q.redis.pending.RedisPendingExecutionService"
previousClass = "com.netflix.spinnaker.orca.q.pending.RedisPendingExecutionServiceProxy"
}
subject {
DualPendingExecutionService(
properties,
listOf(primaryService, previousService),
NoopRegistry()
)
}
afterGroup {
primaryRedis.destroy()
previousRedis.destroy()
}
val id = UUID.randomUUID().toString()
val pipeline = pipeline {
pipelineConfigId = id
stage {
refId = "1"
}
stage {
refId = "2"
requisiteStageRefIds = setOf("1")
}
}
val startMessage = StartExecution(pipeline)
val restartMessage = RestartStage(pipeline.stageByRef("2"), "[email protected]")
val callback = mock<(Message) -> Unit>()
describe("enqueue only writes to primary") {
given("the queue is empty") {
beforeGroup {
Assertions.assertThat(subject.depth(id)).isZero()
}
on("enqueue a message") {
subject.enqueue(id, startMessage)
it("total queue depth is one") {
Assertions.assertThat(subject.depth(id)).isEqualTo(1)
}
it("previous queue depth is zero") {
Assertions.assertThat(previousService.depth(id)).isZero()
}
it("primary queue depth is one") {
Assertions.assertThat(primaryService.depth(id)).isEqualTo(1)
}
}
afterGroup { subject.purge(id, callback) }
}
}
describe("pop prioritizes prior") {
given("both services contain a message") {
beforeGroup {
Assertions.assertThat(subject.depth(id)).isZero()
previousService.enqueue(id, startMessage)
primaryService.enqueue(id, restartMessage)
Assertions.assertThat(subject.depth(id)).isEqualTo(2)
}
on("pop a message") {
val message = subject.popOldest(id)
it("pops from previous") {
Assertions.assertThat(message).isEqualTo(startMessage)
}
}
on("pop another message") {
val message = subject.popOldest(id)
it("pops from primary") {
Assertions.assertThat(message).isEqualTo(restartMessage)
}
}
}
afterGroup { subject.purge(id, callback) }
}
describe("purge iterates thru both services") {
val purgeCallback = mock<(Message) -> Unit>()
given("both services contain a message") {
beforeGroup {
Assertions.assertThat(subject.depth(id)).isZero()
previousService.enqueue(id, startMessage)
primaryService.enqueue(id, restartMessage)
Assertions.assertThat(previousService.depth(id)).isEqualTo(1)
Assertions.assertThat(primaryService.depth(id)).isEqualTo(1)
Assertions.assertThat(subject.depth(id)).isEqualTo(2)
}
on("purge the queue") {
subject.purge(id, purgeCallback)
it("both services are purged") {
Assertions.assertThat(previousService.depth(id)).isZero()
Assertions.assertThat(primaryService.depth(id)).isZero()
Assertions.assertThat(subject.depth(id)).isZero()
}
it("both services invoke callback") {
verify(purgeCallback).invoke(startMessage)
verify(purgeCallback).invoke(restartMessage)
}
}
}
}
})
class RedisPendingExecutionServiceProxy(
private val service: PendingExecutionService
) : PendingExecutionService {
override fun enqueue(pipelineConfigId: String, message: Message) =
service.enqueue(pipelineConfigId, message)
override fun popOldest(pipelineConfigId: String): Message? =
service.popOldest(pipelineConfigId)
override fun popNewest(pipelineConfigId: String): Message? =
service.popNewest(pipelineConfigId)
override fun purge(pipelineConfigId: String, callback: (Message) -> Unit) =
service.purge(pipelineConfigId, callback)
override fun depth(pipelineConfigId: String): Int =
service.depth(pipelineConfigId)
override fun pendingIds(): List<String> =
service.pendingIds()
}
| apache-2.0 | 036e65bfe102c224bebb19b7400827ce | 30.825137 | 92 | 0.713427 | 4.402116 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.