repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/instance/tasks/InstanceReload.kt | 1 | 1052 | package com.cognifide.gradle.aem.instance.tasks
import com.cognifide.gradle.aem.common.instance.action.AwaitUpAction
import com.cognifide.gradle.aem.common.instance.action.ReloadAction
import com.cognifide.gradle.aem.common.instance.names
import com.cognifide.gradle.aem.common.tasks.Instance
import org.gradle.api.tasks.TaskAction
open class InstanceReload : Instance() {
private var reloadOptions: ReloadAction.() -> Unit = {}
fun reload(options: ReloadAction.() -> Unit) {
this.reloadOptions = options
}
private var awaitUpOptions: AwaitUpAction.() -> Unit = {}
fun awaitUp(options: AwaitUpAction.() -> Unit) {
this.awaitUpOptions = options
}
@TaskAction
fun reload() {
instanceManager.awaitReloaded(anyInstances, reloadOptions, awaitUpOptions)
common.notifier.lifecycle("Instance(s) reloaded", "Which: ${anyInstances.names}")
}
init {
description = "Reloads all AEM instance(s)."
}
companion object {
const val NAME = "instanceReload"
}
}
| apache-2.0 | 58e4760293fa5e3870e9b9a12efdab8f | 28.222222 | 89 | 0.70057 | 4.109375 | false | false | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/ui/status/StatusView.kt | 1 | 8490 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.sinyuk.fanfou.ui.status
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentPagerAdapter
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.view.ViewTreeObserver
import cn.dreamtobe.kpswitch.util.KeyboardUtil
import com.linkedin.android.spyglass.suggestions.SuggestionsResult
import com.linkedin.android.spyglass.suggestions.interfaces.Suggestible
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsResultListener
import com.linkedin.android.spyglass.suggestions.interfaces.SuggestionsVisibilityManager
import com.linkedin.android.spyglass.tokenization.QueryToken
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizer
import com.linkedin.android.spyglass.tokenization.impl.WordTokenizerConfig
import com.linkedin.android.spyglass.tokenization.interfaces.QueryTokenReceiver
import com.sinyuk.fanfou.R
import com.sinyuk.fanfou.base.AbstractActivity
import com.sinyuk.fanfou.base.AbstractFragment
import com.sinyuk.fanfou.di.Injectable
import com.sinyuk.fanfou.domain.DO.Player
import com.sinyuk.fanfou.domain.DO.Status
import com.sinyuk.fanfou.domain.STATUS_LIMIT
import com.sinyuk.fanfou.domain.StatusCreation
import com.sinyuk.fanfou.domain.TIMELINE_CONTEXT
import com.sinyuk.fanfou.ui.editor.EditorView
import com.sinyuk.fanfou.ui.editor.MentionListView
import com.sinyuk.fanfou.ui.timeline.TimelineView
import com.sinyuk.fanfou.util.obtainViewModelFromActivity
import com.sinyuk.fanfou.viewmodel.FanfouViewModelFactory
import com.sinyuk.fanfou.viewmodel.PlayerViewModel
import kotlinx.android.synthetic.main.status_view.*
import kotlinx.android.synthetic.main.status_view_footer.*
import kotlinx.android.synthetic.main.status_view_reply_actionbar.*
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/12.
*
*/
class StatusView : AbstractFragment(), Injectable, QueryTokenReceiver, SuggestionsResultListener, SuggestionsVisibilityManager {
companion object {
fun newInstance(status: Status, photoExtra: Bundle? = null) = StatusView().apply {
arguments = Bundle().apply {
putParcelable("status", status)
putBundle("photoExtra", photoExtra)
}
}
}
override fun layoutId() = R.layout.status_view
@Inject
lateinit var factory: FanfouViewModelFactory
private val playerViewModel by lazy { obtainViewModelFromActivity(factory, PlayerViewModel::class.java) }
override fun onEnterAnimationEnd(savedInstanceState: Bundle?) {
super.onEnterAnimationEnd(savedInstanceState)
navBack.setOnClickListener { onBackPressedSupport() }
setupEditor()
setupKeyboard()
onTextChanged(0)
setupViewPager()
val status = arguments!!.getParcelable<Status>("status")
fullscreenButton.setOnClickListener {
(activity as AbstractActivity).start(EditorView.newInstance(status.id,
replyEt.mentionsText,
StatusCreation.REPOST_STATUS))
replyEt.text = null
}
}
private fun setupViewPager() {
val status = arguments!!.getParcelable<Status>("status")
val bundle = arguments!!.getBundle("photoExtra")
val fragments: List<Fragment> = if (findChildFragment(TimelineView::class.java) == null) {
val mentionView = MentionListView()
mentionView.onItemClickListener = onSuggestionSelectListener
mutableListOf(TimelineView.contextTimeline(TIMELINE_CONTEXT, status, bundle), mentionView)
} else {
mutableListOf(findChildFragment(TimelineView::class.java), MentionListView())
}
viewPager.setPagingEnabled(false)
viewPager.offscreenPageLimit = 1
viewPager.adapter = object : FragmentPagerAdapter(childFragmentManager) {
override fun getItem(position: Int) = fragments[position]
override fun getCount() = fragments.size
}
}
private var keyboardListener: ViewTreeObserver.OnGlobalLayoutListener? = null
private fun setupKeyboard() {
keyboardListener = KeyboardUtil.attach(activity, panelRoot, {
// TODO: how comes the Exception: panelRootContainer must not be null
panelRootContainer?.visibility =
if (it) {
if (replyEt.requestFocus()) replyEt.setSelection(replyEt.text.length)
View.VISIBLE
} else {
replyEt.clearFocus()
View.GONE
}
})
}
private val config = WordTokenizerConfig.Builder()
.setExplicitChars("@")
.setThreshold(3)
.setMaxNumKeywords(5)
.setWordBreakChars(" ").build()
private fun setupEditor() {
replyEt.tokenizer = WordTokenizer(config)
replyEt.setAvoidPrefixOnTap(true)
replyEt.setQueryTokenReceiver(this)
replyEt.setSuggestionsVisibilityManager(this)
replyEt.setAvoidPrefixOnTap(true)
replyCommitButton.setOnClickListener { }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
textCountProgress.min = 0
textCountProgress.max = STATUS_LIMIT
replyEt.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
onTextChanged(s?.length ?: 0)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
/**
* @param count 字数
*/
private fun onTextChanged(count: Int) {
textCountProgress.progress = count
replyCommitButton.isEnabled = count in 1..STATUS_LIMIT
}
private val onSuggestionSelectListener = object : MentionListView.OnItemClickListener {
override fun onItemClick(position: Int, item: Suggestible) {
(item as Player).let {
replyEt.insertMention(it)
displaySuggestions(false)
playerViewModel.updateMentionedAt(it) //
onTextChanged(replyEt.text.length)
replyEt.requestFocus()
replyEt.setSelection(replyEt.text.length)
}
}
}
@Suppress("PrivatePropertyName")
private val BUCKET = "player-mentioned"
override fun onQueryReceived(queryToken: QueryToken): MutableList<String> {
val data = playerViewModel.filter(queryToken.keywords)
onReceiveSuggestionsResult(SuggestionsResult(queryToken, data), BUCKET)
return arrayOf(BUCKET).toMutableList()
}
override fun onReceiveSuggestionsResult(result: SuggestionsResult, bucket: String) {
val data = result.suggestions
if (data?.isEmpty() != false) return
displaySuggestions(true)
findChildFragment(MentionListView::class.java).setData(data)
}
override fun displaySuggestions(display: Boolean) {
viewPager.setCurrentItem(if (display) 1 else 0, true)
}
override fun isDisplayingSuggestions() = viewPager.currentItem == 1
override fun onBackPressedSupport(): Boolean {
when {
panelRootContainer.visibility == View.VISIBLE -> KeyboardUtil.hideKeyboard(panelRootContainer)
isDisplayingSuggestions -> displaySuggestions(false)
else -> pop()
}
return true
}
override fun onDestroy() {
keyboardListener?.let { KeyboardUtil.detach(activity, it) }
activity?.currentFocus?.let { KeyboardUtil.hideKeyboard(it) }
super.onDestroy()
}
} | mit | 5af36f349b9d956a8978f0e89d209a86 | 35.9 | 128 | 0.686071 | 4.762065 | false | false | false | false |
TimePath/java-vfs | src/main/kotlin/com/timepath/vfs/provider/jdbc/JDBCTable.kt | 1 | 1410 | package com.timepath.vfs.provider.jdbc
import com.timepath.vfs.MockFile
import com.timepath.vfs.SimpleVFile
import com.timepath.vfs.provider.ProviderStub
import org.jetbrains.annotations.NonNls
import java.sql.SQLException
import java.text.MessageFormat
import java.util.LinkedList
import java.util.logging.Level
/**
* @author TimePath
*/
class JDBCTable(private val jdbcProvider: JDBCProvider, name: String) : ProviderStub(name) {
override fun get(NonNls name: String) = list().firstOrNull { name == it.name }
SuppressWarnings("NestedTryStatement")
override fun list(): Collection<SimpleVFile> {
val rows = LinkedList<MockFile>()
try {
jdbcProvider.conn.prepareStatement("SELECT * FROM ${name}").let { st ->
st.executeQuery().let { rs ->
val len = rs.getMetaData().getColumnCount()
while (rs.next()) {
val sb = StringBuilder()
for (i in 0..len - 1) {
sb.append('\t').append(rs.getString(i + 1))
}
rows.add(MockFile(rs.getString(1), sb.substring(1)))
}
}
}
} catch (e: SQLException) {
JDBCProvider.LOG.log(Level.SEVERE, MessageFormat.format("Reading from table {0}", name), e)
}
return rows
}
}
| artistic-2.0 | 0f28077c74af286debbd9eba0d5de3ef | 33.390244 | 103 | 0.580142 | 4.40625 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/preference/RoomAvatarPreference.kt | 2 | 1639 | /*
* Copyright 2018 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.preference
import android.content.Context
import android.util.AttributeSet
import im.vector.util.VectorUtils
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.data.Room
/**
* Specialized class to target a Room avatar preference.
* Based don the avatar preference class it redefines refreshAvatar() and
* add the new method setConfiguration().
*/
class RoomAvatarPreference : UserAvatarPreference {
private var mRoom: Room? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle)
override fun refreshAvatar() {
if (null != mAvatarView && null != mRoom) {
VectorUtils.loadRoomAvatar(context, mSession, mAvatarView, mRoom)
}
}
fun setConfiguration(aSession: MXSession, aRoom: Room) {
mSession = aSession
mRoom = aRoom
refreshAvatar()
}
} | apache-2.0 | ed599f3608c83ea8cc0a4af370b5893a | 31.156863 | 103 | 0.723002 | 4.235142 | false | false | false | false |
mikepenz/MaterialDrawer | materialdrawer/src/main/java/com/mikepenz/materialdrawer/model/AbstractToggleableDrawerItem.kt | 1 | 3288 | package com.mikepenz.materialdrawer.model
import android.view.View
import android.widget.CompoundButton
import android.widget.ToggleButton
import androidx.annotation.LayoutRes
import com.mikepenz.materialdrawer.R
import com.mikepenz.materialdrawer.interfaces.OnCheckedChangeListener
import com.mikepenz.materialdrawer.model.interfaces.Checkable
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem
/**
* An abstract [IDrawerItem] implementation describing a drawerItem with support for a toggle
*/
open class AbstractToggleableDrawerItem<Item : AbstractToggleableDrawerItem<Item>> : Checkable, BaseDescribeableDrawerItem<Item, AbstractToggleableDrawerItem.ViewHolder>() {
var isToggleEnabled = true
override var isChecked = false
var onCheckedChangeListener: OnCheckedChangeListener? = null
override val type: Int
get() = R.id.material_drawer_item_primary_toggle
override val layoutRes: Int
@LayoutRes
get() = R.layout.material_drawer_item_toggle
private val checkedChangeListener = object : CompoundButton.OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton, ic: Boolean) {
if (isEnabled) {
isChecked = ic
onCheckedChangeListener?.onCheckedChanged(this@AbstractToggleableDrawerItem, buttonView, ic)
} else {
buttonView.setOnCheckedChangeListener(null)
buttonView.isChecked = !ic
buttonView.setOnCheckedChangeListener(this)
}
}
}
@Deprecated("Please consider to replace with the actual property setter")
fun withToggleEnabled(toggleEnabled: Boolean): Item {
this.isToggleEnabled = toggleEnabled
return this as Item
}
@Deprecated("Please consider to replace with the actual property setter")
fun withOnCheckedChangeListener(onCheckedChangeListener: OnCheckedChangeListener): Item {
this.onCheckedChangeListener = onCheckedChangeListener
return this as Item
}
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
//bind the basic view parts
bindViewHelper(holder)
//handle the toggle
holder.toggle.setOnCheckedChangeListener(null)
holder.toggle.isChecked = isChecked
holder.toggle.setOnCheckedChangeListener(checkedChangeListener)
holder.toggle.isEnabled = isToggleEnabled
//add a onDrawerItemClickListener here to be able to check / uncheck if the drawerItem can't be selected
withOnDrawerItemClickListener { v, item, position ->
if (!isSelectable) {
isChecked = !isChecked
holder.toggle.isChecked = isChecked
}
false
}
//call the onPostBindView method to trigger post bind view actions (like the listener to modify the item if required)
onPostBindView(this, holder.itemView)
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
open class ViewHolder internal constructor(view: View) : BaseViewHolder(view) {
internal val toggle: ToggleButton = view.findViewById<ToggleButton>(R.id.material_drawer_toggle)
}
}
| apache-2.0 | 6aa352fe5951c4b3b9be36e335b1b810 | 37.232558 | 173 | 0.70955 | 5.452736 | false | false | false | false |
deltadak/plep | src/main/kotlin/nl/deltadak/plep/ui/taskcell/TaskLayout.kt | 1 | 4729 | package nl.deltadak.plep.ui.taskcell
import javafx.geometry.Pos
import javafx.scene.control.CheckBox
import javafx.scene.control.ComboBox
import javafx.scene.control.Label
import javafx.scene.control.TreeItem
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.Region
import javafx.scene.text.TextAlignment
import nl.deltadak.plep.HomeworkTask
import nl.deltadak.plep.database.tables.Colors
import nl.deltadak.plep.ui.taskcell.components.textlabel.TextLabelStyle
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.ChangeListenerWithBlocker
import nl.deltadak.plep.ui.taskcell.util.blockerlisteners.InvalidationListenerWithBlocker
import nl.deltadak.plep.ui.util.LABEL_MAGIK
/**
* Manages the layout of a TreeCell. Always contains a CheckBox and a Label (text). Also contains a ComboBox (dropdown menu) if the Cell is the root of a task.
* The given components are updated with the correct layout.
*
* @property taskCell Cell to set layout on.
* @property doneChangeListener Should provide the ability to temporarily block the listener of the checkbox.
* @property checkBox Checkbox of the task.
* @property label Text of the task.
* @property labelChangeListener Should provide the ability to temporarily block the listener of the combobox.
* @property root Root item of the TreeView in which the task is.
* @property comboBox Combobox of the task.
*/
class TaskLayout(private val taskCell: TaskCell, private val doneChangeListener: ChangeListenerWithBlocker<Boolean>, private val checkBox: CheckBox, val label: Label, private val labelChangeListener: InvalidationListenerWithBlocker, val root: TreeItem<HomeworkTask>, private val comboBox: ComboBox<String>) {
/**
* Updates the layout.
* The homeworktask could be null, since updating is initiated by JavaFX.
*
* @param homeworkTask The Homework task to be displayed in the Cell.
*/
fun update(homeworkTask: HomeworkTask?) {
if (taskCell.isEmpty) {
taskCell.graphic = null
taskCell.text = null
} else {
if (homeworkTask != null) {
setLayout(homeworkTask)
}
}
}
private fun setLayout(homeworkTask: HomeworkTask) {
// Create the container for components.
val cellBox = HBox(10.0)
cellBox.alignment = Pos.CENTER_LEFT
setCheckBox(homeworkTask)
setTextLabel(homeworkTask)
// Get style from the database and apply to the item.
val color = Colors.get(homeworkTask.colorID)
taskCell.style = "-fx-control-inner-background: #$color"
TextLabelStyle().setDoneStyle(homeworkTask.done, label, comboBox)
// If the item is top level, a parent task, it has to show a course label (ComboBox), and it has to have a context menu.
if (taskCell.treeItem.parent == root) {
val region = setComboBox(homeworkTask)
cellBox.children.addAll(checkBox, label, region, comboBox)
taskCell.graphic = cellBox
taskCell.text = null
} else {
// Set up subtask, with context menu disabled.
with(taskCell) {
contextMenu = null
graphic = cellBox.apply { children.addAll(checkBox, label) }
text = null
}
}
}
/**
* Setup checkbox.
*/
private fun setCheckBox(homeworkTask: HomeworkTask) {
// Block the listener on the checkbox when we manually toggle it, so it corresponds to the value in the database.
doneChangeListener.block = true
val done = homeworkTask.done
// Manually toggle, if necessary.
checkBox.isSelected = done
doneChangeListener.block = false
}
/**
* Setup text label.
*/
private fun setTextLabel(homeworkTask: HomeworkTask) {
with(label) {
text = homeworkTask.text
prefWidthProperty().bind(taskCell.treeView.widthProperty().subtract(LABEL_MAGIK))
isWrapText = true
textAlignment = TextAlignment.JUSTIFY
}
}
/**
* Setup combobox.
*/
private fun setComboBox(homeworkTask: HomeworkTask): Region {
// Before setting value, we need to temporarily disable the listener, otherwise it fires and goes unnecessarily updating the database, which takes a lot of time.
labelChangeListener.block = true
comboBox.value = homeworkTask.label
labelChangeListener.block = false
// Create a region to make sure that the ComboBox is aligned on the right.
val region = Region()
HBox.setHgrow(region, Priority.ALWAYS)
return region
}
}
| mit | 55703359bf4aa0d1e4effebbfc1dc383 | 36.832 | 308 | 0.683866 | 4.705473 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/query/QueryTokenizer.kt | 1 | 2478 | package com.orgzly.android.query
class QueryTokenizer(val str: String, private val groupOpen: String, private val groupClose: String) {
val tokens = tokanize(str)
var nextToken = 0
fun hasMoreTokens(): Boolean = nextToken < tokens.size
fun nextToken() = tokens[nextToken++]
private fun tokanize(str: String): List<String> {
return tokenRegex.findAll(str).map { it.value }.toList()
}
companion object {
val TAG: String = QueryTokenizer::class.java.name
private const val char = """[^")(\s]"""
private const val doubleQuoted = """"[^"\\]*(?:\\.[^"\\]*)*""""
private const val doubleQuotedWithPrefix = """$char*$doubleQuoted"""
private const val groupOpener = """\("""
private const val groupCloser = """\)"""
private const val rest = """$char+"""
private val tokenRegex =
listOf(doubleQuotedWithPrefix, groupOpener, groupCloser, rest)
.joinToString("|").toRegex()
fun unquote(s: String): String {
if (s.length < 2) {
return s
}
val first = s[0]
val last = s[s.length - 1]
if (first != last || first != '"') {
return s
}
val b = StringBuilder(s.length - 2)
var quote = false
for (i in 1 until s.length - 1) {
val c = s[i]
if (c == '\\' && !quote) {
quote = true
continue
}
quote = false
b.append(c)
}
return b.toString()
}
fun quote(s: String, delim: String): String {
if (s.isEmpty()) {
return "\"\""
}
for (element in s) {
if (element == '"' || element == '\\' || delim.indexOf(element) >= 0) {
return quoteUnconditionally(s)
}
}
return s
}
fun quoteUnconditionally(s: String): String {
val builder = StringBuilder(s.length + 8)
builder.append('"')
for (element in s) {
if (element == '"') {
builder.append('\\')
}
builder.append(element)
continue
}
builder.append('"')
return builder.toString()
}
}
} | gpl-3.0 | 1fde97a2f66940fc14668d1837d9747f | 28.164706 | 102 | 0.45682 | 4.783784 | false | false | false | false |
orgzly/orgzly-android | app/src/main/java/com/orgzly/android/ui/drawer/DrawerNavigationView.kt | 1 | 5383 | package com.orgzly.android.ui.drawer
import android.content.Intent
import android.content.res.Resources
import android.view.Menu
import androidx.lifecycle.Observer
import com.google.android.material.navigation.NavigationView
import com.orgzly.BuildConfig
import com.orgzly.R
import com.orgzly.android.AppIntent
import com.orgzly.android.db.entity.BookAction
import com.orgzly.android.db.entity.BookView
import com.orgzly.android.db.entity.SavedSearch
import com.orgzly.android.ui.books.BooksFragment
import com.orgzly.android.ui.main.MainActivity
import com.orgzly.android.ui.main.MainActivityViewModel
import com.orgzly.android.ui.notes.book.BookFragment
import com.orgzly.android.ui.notes.query.QueryFragment
import com.orgzly.android.ui.savedsearches.SavedSearchesFragment
import com.orgzly.android.util.LogUtils
import java.util.*
internal class DrawerNavigationView(
private val activity: MainActivity,
viewModel: MainActivityViewModel,
navView: NavigationView) {
private val menu: Menu = navView.menu
private val menuItemIdMap = hashMapOf<String, Int>()
private var activeFragmentTag: String? = null
init {
// Add mapping for groups
menuItemIdMap[BooksFragment.drawerItemId] = R.id.books
menuItemIdMap[SavedSearchesFragment.getDrawerItemId()] = R.id.searches
// Setup intents
menu.findItem(R.id.searches).intent = Intent(AppIntent.ACTION_OPEN_SAVED_SEARCHES)
menu.findItem(R.id.books).intent = Intent(AppIntent.ACTION_OPEN_BOOKS)
menu.findItem(R.id.settings).intent = Intent(AppIntent.ACTION_OPEN_SETTINGS)
viewModel.books().observe(activity, Observer {
refreshFromBooks(it)
})
viewModel.savedSearches().observe(activity, Observer {
refreshFromSavedSearches(it)
})
}
fun updateActiveFragment(fragmentTag: String) {
this.activeFragmentTag = fragmentTag
setActiveItem(fragmentTag)
}
private fun setActiveItem(fragmentTag: String) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, fragmentTag)
this.activeFragmentTag = fragmentTag
val fragment = activity.supportFragmentManager.findFragmentByTag(activeFragmentTag)
// Uncheck all
for (i in 0 until menu.size()) {
menu.getItem(i).isChecked = false
}
if (fragment != null && fragment is DrawerItem) {
val fragmentMenuItemId = fragment.getCurrentDrawerItemId()
val itemId = menuItemIdMap[fragmentMenuItemId]
if (itemId != null) {
menu.findItem(itemId)?.isChecked = true
}
}
}
private fun refreshFromSavedSearches(savedSearches: List<SavedSearch>) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, savedSearches.size)
removeItemsWithOrder(1)
savedSearches.forEach { savedSearch ->
val intent = Intent(AppIntent.ACTION_OPEN_QUERY)
intent.putExtra(AppIntent.EXTRA_QUERY_STRING, savedSearch.query)
val id = generateRandomUniqueId()
val item = menu.add(R.id.drawer_group, id, 1, savedSearch.name)
menuItemIdMap[QueryFragment.getDrawerItemId(savedSearch.query)] = id
item.intent = intent
item.isCheckable = true
}
activeFragmentTag?.let {
setActiveItem(it)
}
}
private fun refreshFromBooks(books: List<BookView>) {
if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, books.size)
removeItemsWithOrder(3)
books.forEach { book ->
val intent = Intent(AppIntent.ACTION_OPEN_BOOK)
intent.putExtra(AppIntent.EXTRA_BOOK_ID, book.book.id)
val id = generateRandomUniqueId()
val name = book.book.run { title ?: name }
val item = menu.add(R.id.drawer_group, id, 3, name)
item.isEnabled = !book.book.isDummy
item.intent = intent
item.isCheckable = true
if (book.book.lastAction?.type == BookAction.Type.ERROR) {
item.setActionView(R.layout.drawer_item_sync_failed)
} else if (book.isOutOfSync()) {
item.setActionView(R.layout.drawer_item_sync_needed)
}
menuItemIdMap[BookFragment.getDrawerItemId(book.book.id)] = id
}
activeFragmentTag?.let {
setActiveItem(it)
}
}
private fun generateRandomUniqueId(): Int {
val rand = Random()
while (true) {
val id = rand.nextInt(Integer.MAX_VALUE) + 1
try {
activity.resources.getResourceName(id)
} catch (e: Resources.NotFoundException) {
return id
}
}
}
private fun removeItemsWithOrder(orderToDelete: Int) {
val itemIdsToRemove = HashSet<Int>()
var i = 0
while (true) {
val item = menu.getItem(i++) ?: break
val order = item.order
if (order > orderToDelete) {
break
} else if (order == orderToDelete) {
itemIdsToRemove.add(item.itemId)
}
}
for (id in itemIdsToRemove) {
menu.removeItem(id)
}
}
companion object {
private val TAG = DrawerNavigationView::class.java.name
}
}
| gpl-3.0 | 23bd78f0ea78f40355777d5e6379a664 | 29.241573 | 91 | 0.636448 | 4.474647 | false | false | false | false |
whym/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/TestCommonsApplication.kt | 1 | 3762 | package fr.free.nrw.commons
import android.content.ContentProviderClient
import android.content.Context
import android.content.SharedPreferences
import android.support.v4.util.LruCache
import com.nhaarman.mockito_kotlin.mock
import com.squareup.leakcanary.RefWatcher
import fr.free.nrw.commons.auth.AccountUtil
import fr.free.nrw.commons.auth.SessionManager
import fr.free.nrw.commons.data.DBOpenHelper
import fr.free.nrw.commons.di.CommonsApplicationComponent
import fr.free.nrw.commons.di.CommonsApplicationModule
import fr.free.nrw.commons.di.DaggerCommonsApplicationComponent
import fr.free.nrw.commons.location.LocationServiceManager
import fr.free.nrw.commons.mwapi.MediaWikiApi
import fr.free.nrw.commons.nearby.NearbyPlaces
import fr.free.nrw.commons.upload.UploadController
class TestCommonsApplication : CommonsApplication() {
private var mockApplicationComponent: CommonsApplicationComponent? = null
override fun onCreate() {
if (mockApplicationComponent == null) {
mockApplicationComponent = DaggerCommonsApplicationComponent.builder()
.appModule(MockCommonsApplicationModule(this)).build()
}
super.onCreate()
}
// No leakcanary in unit tests.
override fun setupLeakCanary(): RefWatcher = RefWatcher.DISABLED
}
@Suppress("MemberVisibilityCanBePrivate")
class MockCommonsApplicationModule(appContext: Context) : CommonsApplicationModule(appContext) {
val accountUtil: AccountUtil = mock()
val appSharedPreferences: SharedPreferences = mock()
val defaultSharedPreferences: SharedPreferences = mock()
val otherSharedPreferences: SharedPreferences = mock()
val uploadController: UploadController = mock()
val mockSessionManager: SessionManager = mock()
val locationServiceManager: LocationServiceManager = mock()
val mockDbOpenHelper: DBOpenHelper = mock()
val nearbyPlaces: NearbyPlaces = mock()
val lruCache: LruCache<String, String> = mock()
val categoryClient: ContentProviderClient = mock()
val contributionClient: ContentProviderClient = mock()
val modificationClient: ContentProviderClient = mock()
val uploadPrefs: SharedPreferences = mock()
override fun provideCategoryContentProviderClient(context: Context?): ContentProviderClient = categoryClient
override fun provideContributionContentProviderClient(context: Context?): ContentProviderClient = contributionClient
override fun provideModificationContentProviderClient(context: Context?): ContentProviderClient = modificationClient
override fun providesDirectNearbyUploadPreferences(context: Context?): SharedPreferences = uploadPrefs
override fun providesAccountUtil(context: Context): AccountUtil = accountUtil
override fun providesApplicationSharedPreferences(context: Context): SharedPreferences = appSharedPreferences
override fun providesDefaultSharedPreferences(context: Context): SharedPreferences = defaultSharedPreferences
override fun providesOtherSharedPreferences(context: Context): SharedPreferences = otherSharedPreferences
override fun providesUploadController(sessionManager: SessionManager, sharedPreferences: SharedPreferences, context: Context): UploadController = uploadController
override fun providesSessionManager(context: Context, mediaWikiApi: MediaWikiApi, sharedPreferences: SharedPreferences): SessionManager = mockSessionManager
override fun provideLocationServiceManager(context: Context): LocationServiceManager = locationServiceManager
override fun provideDBOpenHelper(context: Context): DBOpenHelper = mockDbOpenHelper
override fun provideNearbyPlaces(): NearbyPlaces = nearbyPlaces
override fun provideLruCache(): LruCache<String, String> = lruCache
} | apache-2.0 | b17ee99f85f8731510a4c274d4677b20 | 46.632911 | 166 | 0.805954 | 5.614925 | false | false | false | false |
kmruiz/sonata | frontend/src/main/kotlin/io/sonatalang/snc/frontend/domain/token/NewLineToken.kt | 1 | 324 | package io.sonatalang.snc.frontend.domain.token
object NewLineToken : BasicToken(false), TokenFactory<NewLineToken> {
override fun with(character: Char) = this
override fun toString() = "\n"
override fun isSuitable(character: Char) = character == '\n'
override fun create(character: Char) = NewLineToken
}
| gpl-2.0 | 41dcacab5368a98018db38e1105170de | 35 | 69 | 0.728395 | 4.05 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/sessiondetails/presentationmodel/SessionDetailsPresentationModelTransformer.kt | 1 | 2271 | package com.openconference.sessiondetails.presentationmodel
import com.openconference.model.Session
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
import org.threeten.bp.format.DateTimeFormatter
import org.threeten.bp.format.FormatStyle
import java.util.*
/**
* Responsible to transform a Session to [SessionDetailItem]
*
* @author Hannes Dorfmann
*/
interface SessionDetailsPresentationModelTransformer {
fun transform(session: Session): SessionDetail
}
/**
* Phone Session Details Presentation Model Transformer
* @author Hannes Dorfmann
*/
// TODO Tablet
class PhoneSessionDetailsPresentationModelTransformer : SessionDetailsPresentationModelTransformer {
private val dateFormatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
override fun transform(session: Session): SessionDetail {
val items = ArrayList<SessionDetailItem>()
// TODO use settings for time zone (users preferences)
val zoneId = ZoneId.systemDefault()
val start = session.startTime()
val localStart = if (start == null) null else LocalDateTime.ofInstant(start, zoneId)
val end = session.endTime()
val localEnd = if (end == null) null else LocalDateTime.ofInstant(end, zoneId)
if (start != null) {
val dateStr = if (end != null) {
"${dateFormatter.format(localStart)} - ${dateFormatter.format(localEnd)}"
} else {
dateFormatter.format(localStart)
}
items.add(SessionDateTimeItem(dateStr))
}
// Location
val locationName = session.locationName()
if (locationName != null) items.add(SessionLocationItem(locationName))
// Description
val description = session.description()
if (description != null) {
if (items.isNotEmpty()) items.add(SessionSeparatorItem())
items.add(SessionDescriptionItem(description))
}
// TODO TAGS
// Tags
/*
val tags = session.tags()
if (tags != null) items.add(SessionTagsItem(tags))
*/
// Speakers
if (session.speakers().isNotEmpty()) {
items.add(SessionSeparatorItem())
}
session.speakers().forEach { items.add(SessionSpeakerItem(it)) }
// TODO refactor
return SessionDetail(session.id(), session.title(), session, items, session.favorite())
}
} | apache-2.0 | 82de0443dfb89a114e7cea847cdc68d1 | 27.4 | 100 | 0.713342 | 4.560241 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/traktapi/CheckInDialogFragment.kt | 1 | 1942 | package com.battlelancer.seriesguide.traktapi
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import com.battlelancer.seriesguide.provider.SgRoomDatabase.Companion.getInstance
import com.battlelancer.seriesguide.util.TextTools
import com.battlelancer.seriesguide.util.safeShow
/**
* Allows to check into an episode. Launching activities should subscribe to
* [TraktTask.TraktActionCompleteEvent] to display status toasts.
*/
class CheckInDialogFragment : GenericCheckInDialogFragment() {
override fun checkInTrakt(message: String) {
TraktTask(requireContext()).checkInEpisode(
requireArguments().getLong(ARG_EPISODE_ID),
requireArguments().getString(ARG_ITEM_TITLE),
message
).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
}
companion object {
/**
* Builds and shows a new [CheckInDialogFragment] setting all values based on the given
* episode row ID.
*
* @return `false` if the fragment was not shown.
*/
fun show(context: Context, fragmentManager: FragmentManager, episodeId: Long): Boolean {
val episode = getInstance(context).sgEpisode2Helper().getEpisodeWithShow(episodeId)
?: return false
val f = CheckInDialogFragment()
val args = Bundle()
args.putLong(ARG_EPISODE_ID, episodeId)
val episodeTitleWithNumbers = (episode.seriestitle
+ " "
+ TextTools.getNextEpisodeString(
context,
episode.season,
episode.episodenumber,
episode.episodetitle
))
args.putString(ARG_ITEM_TITLE, episodeTitleWithNumbers)
f.arguments = args
return f.safeShow(fragmentManager, "checkInDialog")
}
}
} | apache-2.0 | 8d8c7fd133c47abfc729684673c1adc7 | 35.660377 | 96 | 0.656025 | 5.044156 | false | false | false | false |
redpen-cc/redpen-intellij-plugin | src/cc/redpen/intellij/StatusWidget.kt | 1 | 5697 | package cc.redpen.intellij
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.LangDataKeys.PSI_FILE
import com.intellij.openapi.actionSystem.impl.SimpleDataContext
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ProjectComponent
import com.intellij.openapi.fileEditor.FileEditorManagerEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.CustomStatusBarWidget
import com.intellij.openapi.wm.StatusBarWidget
import com.intellij.openapi.wm.StatusBarWidget.WidgetBorder.WIDE
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.status.EditorBasedWidget
import com.intellij.openapi.wm.impl.status.TextPanel
import com.intellij.psi.PsiManager
import com.intellij.ui.ClickListener
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.ui.UIUtil
import java.awt.Component
import java.awt.Graphics
import java.awt.Point
import java.awt.event.MouseEvent
open class StatusWidget constructor(project: Project) : EditorBasedWidget(project), CustomStatusBarWidget, ProjectComponent {
val provider = RedPenProvider.forProject(project)
var enabled: Boolean = false
val actionGroupId = "RedPen " + project.basePath
companion object {
fun forProject(project: Project) = project.getComponent(StatusWidget::class.java)!!
}
var actionGroup: DefaultActionGroup? = null
private val component = object: TextPanel.ExtraSize() {
override fun paintComponent(g: Graphics) {
super.paintComponent(g)
if (enabled && text != null) {
val arrows = AllIcons.Ide.Statusbar_arrows
arrows.paintIcon(this, g, bounds.width - insets.right - arrows.iconWidth - 2,
bounds.height / 2 - arrows.iconHeight / 2)
}
}
}
override fun projectOpened() {
install(WindowManager.getInstance().getStatusBar(project))
myStatusBar.addWidget(this, "before Encoding")
object : ClickListener() {
override fun onClick(e: MouseEvent, clickCount: Int): Boolean {
showPopup(e)
return true
}
}.installOn(component)
component.border = WIDE
component.toolTipText = "RedPen language"
registerActions()
}
override fun projectClosed() {
myStatusBar.removeWidget(ID())
unregisterActions()
}
override fun getComponentName(): String = "StatusWidget"
override fun initComponent() {}
override fun disposeComponent() {}
open fun registerActions() {
val actionManager = ActionManager.getInstance() ?: return
actionGroup = DefaultActionGroup()
provider.configs.keys.forEach { key ->
actionGroup!!.add(object : AnAction() {
init { templatePresentation.text = key }
override fun actionPerformed(e: AnActionEvent) {
provider.setConfigFor(e.getData(PSI_FILE)!!, key)
DaemonCodeAnalyzer.getInstance(e.project).restart()
}
})
}
actionManager.registerAction(actionGroupId, actionGroup!!)
}
open internal fun unregisterActions() {
ActionManager.getInstance()?.unregisterAction(actionGroupId)
}
override fun ID(): String {
return "RedPen"
}
override fun getPresentation(platformType: StatusBarWidget.PlatformType): StatusBarWidget.WidgetPresentation? {
return null
}
open fun update(configKey: String) {
if (isDisposed) return
ApplicationManager.getApplication().invokeLater {
component.text = configKey
component.foreground = if (enabled) UIUtil.getActiveTextColor() else UIUtil.getInactiveTextColor()
}
}
override fun selectionChanged(event: FileEditorManagerEvent) {
val file = if (event.newFile == null) null else PsiManager.getInstance(project!!).findFile(event.newFile!!)
if (file != null && provider.getParser(file) != null) {
enabled = true
update(provider.getConfigKeyFor(file))
}
else {
enabled = false
update("n/a")
}
}
override fun getComponent(): TextPanel {
return component
}
internal fun showPopup(e: MouseEvent) {
if (!enabled) return
val popup = JBPopupFactory.getInstance().createActionGroupPopup(
"RedPen", actionGroup!!, getContext(), JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false)
val dimension = popup.content.preferredSize
val at = Point(0, -dimension.height)
popup.show(RelativePoint(e.component, at))
Disposer.register(this, popup)
}
private fun getContext(): DataContext {
val editor = editor
val parent = DataManager.getInstance().getDataContext(myStatusBar as Component)
return SimpleDataContext.getSimpleContext(
CommonDataKeys.VIRTUAL_FILE_ARRAY.name,
arrayOf(selectedFile!!),
SimpleDataContext.getSimpleContext(CommonDataKeys.PROJECT.name,
project,
SimpleDataContext.getSimpleContext(PlatformDataKeys.CONTEXT_COMPONENT.name,
editor?.component, parent)))
}
fun rebuild() {
unregisterActions()
registerActions()
}
}
| apache-2.0 | 2b4053ba36d846e90b27bb160e47611f | 35.754839 | 125 | 0.672284 | 5.07754 | false | false | false | false |
ColaGom/KtGitCloner | src/main/kotlin/net/ProjectExtractor.kt | 1 | 1848 | package net
import SearchResponse
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import data.Repository
import java.io.PrintWriter
import java.nio.file.Path
class ProjectExtractor(val savePath: Path, val start:String, val end:String)
{
fun extract(page : Int = 0)
{
var results = HashMap<String, Repository>()
var totalCount = 0
val requestBuilder = RequestBuilder(start, end)
if(savePath.toFile().exists())
results = Gson().fromJson(savePath.toFile().readText(), object : TypeToken<HashMap<String, Repository>>() {}.type)
requestBuilder.page = page;
while(true)
{
val (request, response, result) = requestBuilder.build().responseObject(SearchResponse.Deserializer());
val (search, err) = result
println(request.url)
search?.let {
search.items.forEach({
if(it.full_name.isNullOrEmpty() || it.language.isNullOrEmpty())
return@forEach
if(!results.containsKey(it.full_name) && it.size < 2048000 && it.language.equals("Java")) {
results.put(it.full_name, it);
println("added ${it.full_name}")
}
})
totalCount += search.items.size;
}
if(requestBuilder.page > 34)
break
else if(err != null) {
Thread.sleep(10000)
}else if(search!!.items.isEmpty())
break
else
requestBuilder.page++;
}
savePath.toFile().printWriter().use { out: PrintWriter ->
out.print(GsonBuilder().setPrettyPrinting().create().toJson(results))
}
}
}
| apache-2.0 | 3513c1b5dd0c5a0b9408d758f58f142a | 30.322034 | 126 | 0.555195 | 4.738462 | false | false | false | false |
duftler/orca | orca-queue-tck/src/main/kotlin/com/netflix/spinnaker/orca/q/ExecutionLatch.kt | 1 | 3713 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.netflix.spinnaker.orca.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.events.ExecutionComplete
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import org.springframework.context.ApplicationListener
import org.springframework.context.ConfigurableApplicationContext
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.function.Predicate
/**
* An [ApplicationListener] implementation you can use to wait for an execution
* to complete. Much better than `Thread.sleep(whatever)` in your tests.
*/
class ExecutionLatch(private val predicate: Predicate<ExecutionComplete>) :
ApplicationListener<ExecutionComplete> {
private val latch = CountDownLatch(1)
override fun onApplicationEvent(event: ExecutionComplete) {
if (predicate.test(event)) {
latch.countDown()
}
}
fun await() = latch.await(10, TimeUnit.SECONDS)
}
fun ConfigurableApplicationContext.runToCompletion(execution: Execution, launcher: (Execution) -> Unit, repository: ExecutionRepository) {
val latch = ExecutionLatch(Predicate {
it.executionId == execution.id
})
addApplicationListener(latch)
launcher.invoke(execution)
assert(latch.await()) { "Pipeline did not complete" }
repository.waitForAllStagesToComplete(execution)
}
/**
* Given parent and child pipelines:
* 1) Start child pipeline
* 2) Invoke parent pipeline and continue until completion
*
* Useful for testing failure interactions between pipelines. Child pipeline can be inspected prior to
* completion, and subsequently completed via [runToCompletion].
*/
fun ConfigurableApplicationContext.runParentToCompletion(
parent: Execution,
child: Execution,
launcher: (Execution) -> Unit,
repository: ExecutionRepository
) {
val latch = ExecutionLatch(Predicate {
it.executionId == parent.id
})
addApplicationListener(latch)
launcher.invoke(child)
launcher.invoke(parent)
assert(latch.await()) { "Pipeline did not complete" }
repository.waitForAllStagesToComplete(parent)
}
fun ConfigurableApplicationContext.restartAndRunToCompletion(stage: Stage, launcher: (Execution, String) -> Unit, repository: ExecutionRepository) {
val execution = stage.execution
val latch = ExecutionLatch(Predicate {
it.executionId == execution.id
})
addApplicationListener(latch)
launcher.invoke(execution, stage.id)
assert(latch.await()) { "Pipeline did not complete after restarting" }
repository.waitForAllStagesToComplete(execution)
}
private fun ExecutionRepository.waitForAllStagesToComplete(execution: Execution) {
var complete = false
while (!complete) {
Thread.sleep(100)
complete = retrieve(PIPELINE, execution.id)
.run {
status.isComplete && stages
.map(Stage::getStatus)
.all { it.isComplete || it == NOT_STARTED }
}
}
}
| apache-2.0 | 9f7e49b478f4afae4843f98df40e083b | 33.06422 | 148 | 0.764611 | 4.425507 | false | false | false | false |
willowtreeapps/assertk | assertk/src/commonTest/kotlin/test/assertk/assertions/MapTest.kt | 1 | 8247 | package test.assertk.assertions
import assertk.assertThat
import assertk.assertions.*
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFails
class MapTest {
//region contains
@Test fun contains_element_present_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).contains("two" to 2)
}
@Test fun contains_element_missing_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).contains("one" to 1)
}
assertEquals("expected to contain:<{\"one\"=1}> but was:<{}>", error.message)
}
@Test fun contains_element_with_nullable_value_missing_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int?>()).contains("one" to null)
}
assertEquals("expected to contain:<{\"one\"=null}> but was:<{}>", error.message)
}
//endregion
//region doesNotContain
@Test fun doesNotContain_element_missing_passes() {
assertThat(emptyMap<String, Int>()).doesNotContain("one" to 1)
}
@Test fun doesNotContain_element_with_missing_nullable_value_passes() {
assertThat(emptyMap<String, Int?>()).doesNotContain("one" to null)
}
@Test fun doesNotContain_element_present_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).doesNotContain("two" to 2)
}
assertEquals("expected to not contain:<{\"two\"=2}> but was:<{\"one\"=1, \"two\"=2}>", error.message)
}
//endregion
//region containsNone
@Test fun containsNone_missing_elements_passes() {
assertThat(emptyMap<String, Int>()).containsNone("one" to 1)
}
@Test fun containsNone_missing_elements_with_nullable_value_passes() {
assertThat(emptyMap<String, Int?>()).containsNone("one" to null)
}
@Test fun containsNone_present_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsNone("two" to 2, "three" to 3)
}
assertEquals(
"""expected to contain none of:<{"two"=2, "three"=3}> but was:<{"one"=1, "two"=2}>
| elements not expected:<{"two"=2}>
""".trimMargin(),
error.message
)
}
//region
//region containsAll
@Test fun containsAll_all_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).containsAll("two" to 2, "one" to 1)
}
@Test fun containsAll_extra_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2, "three" to 3)).containsAll("one" to 1, "two" to 2)
}
@Test fun containsAll_swapped_keys_and_values_fails() {
val error = assertFails {
assertThat(mapOf("one" to 2, "two" to 1)).containsAll("two" to 2, "one" to 1)
}
assertEquals(
"""expected to contain all:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}>
| elements not found:<{"two"=2, "one"=1}>
""".trimMargin(), error.message
)
}
@Test fun containsAll_nullable_values_fails() {
val error = assertFails {
assertThat(mapOf<String, Any?>()).containsAll("key" to null)
}
assertEquals(
"""expected to contain all:<{"key"=null}> but was:<{}>
| elements not found:<{"key"=null}>
""".trimMargin(), error.message
)
}
@Test fun containsAll_some_elements_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1)).containsAll("one" to 1, "two" to 2)
}
assertEquals(
"""expected to contain all:<{"one"=1, "two"=2}> but was:<{"one"=1}>
| elements not found:<{"two"=2}>
""".trimMargin(),
error.message
)
}
//endregion
//region containsOnly
@Test fun containsOnly_all_elements_passes() {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("two" to 2, "one" to 1)
}
@Test fun containsOnly_swapped_keys_and_values_fails() {
val error = assertFails {
assertThat(mapOf("one" to 2, "two" to 1)).containsOnly("two" to 2, "one" to 1)
}
assertEquals(
"""expected to contain only:<{"two"=2, "one"=1}> but was:<{"one"=2, "two"=1}>
| elements not found:<{"two"=2, "one"=1}>
| extra elements found:<{"one"=2, "two"=1}>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_missing_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("three" to 3)
}
assertEquals(
"""expected to contain only:<{"three"=3}> but was:<{"one"=1, "two"=2}>
| elements not found:<{"three"=3}>
| extra elements found:<{"one"=1, "two"=2}>
""".trimMargin(), error.message
)
}
@Test fun containsOnly_extra_element_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2)).containsOnly("one" to 1)
}
assertEquals(
"""expected to contain only:<{"one"=1}> but was:<{"one"=1, "two"=2}>
| extra elements found:<{"two"=2}>
""".trimMargin(), error.message
)
}
//endregion
//region isEmpty
@Test fun isEmpty_empty_passes() {
assertThat(emptyMap<Any?, Any?>()).isEmpty()
}
@Test fun isEmpty_non_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>(null to null)).isEmpty()
}
assertEquals("expected to be empty but was:<{null=null}>", error.message)
}
//endregion
//region isNotEmpty
@Test fun isNotEmpty_non_empty_passes() {
assertThat(mapOf<Any?, Any?>(null to null)).isNotEmpty()
}
@Test fun isNotEmpty_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>()).isNotEmpty()
}
assertEquals("expected to not be empty", error.message)
}
//endregion
//region isNullOrEmpty
@Test fun isNullOrEmpty_null_passes() {
assertThat(null as Map<Any?, Any?>?).isNullOrEmpty()
}
@Test fun isNullOrEmpty_empty_passes() {
assertThat(emptyMap<Any?, Any?>()).isNullOrEmpty()
}
@Test fun isNullOrEmpty_non_empty_fails() {
val error = assertFails {
assertThat(mapOf<Any?, Any?>(null to null)).isNullOrEmpty()
}
assertEquals("expected to be null or empty but was:<{null=null}>", error.message)
}
//endregion
//region hasSize
@Test fun hasSize_correct_size_passes() {
assertThat(emptyMap<String, Int>()).hasSize(0)
}
@Test fun hasSize_wrong_size_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).hasSize(1)
}
assertEquals("expected [size]:<[1]> but was:<[0]> ({})", error.message)
}
//endregion
//region hasSameSizeAs
@Test fun hasSameSizeAs_equal_sizes_passes() {
assertThat(emptyMap<String, Int>()).hasSameSizeAs(emptyMap<String, Int>())
}
@Test fun hasSameSizeAs_non_equal_sizes_fails() {
val error = assertFails {
assertThat(emptyMap<String, Int>()).hasSameSizeAs(mapOf("one" to 1))
}
assertEquals("expected to have same size as:<{\"one\"=1}> (1) but was size:(0)", error.message)
}
//endregion
//region key
@Test fun index_successful_assertion_passes() {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(1)
}
@Test fun index_unsuccessful_assertion_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("one").isEqualTo(2)
}
assertEquals("expected [subject[\"one\"]]:<[2]> but was:<[1]> ({\"one\"=1, \"two\"=2})", error.message)
}
@Test fun index_missing_key_fails() {
val error = assertFails {
assertThat(mapOf("one" to 1, "two" to 2), name = "subject").key("wrong").isEqualTo(1)
}
assertEquals("expected [subject] to have key:<\"wrong\">", error.message)
}
//endregion
}
| mit | 238aac7563b9417f7e567504e005dad5 | 32.79918 | 111 | 0.56566 | 4.127628 | false | true | false | false |
cketti/k-9 | app/storage/src/main/java/com/fsck/k9/storage/messages/RetrieveFolderOperations.kt | 1 | 7702 | package com.fsck.k9.storage.messages
import android.database.Cursor
import androidx.core.database.getLongOrNull
import com.fsck.k9.Account.FolderMode
import com.fsck.k9.helper.map
import com.fsck.k9.mail.FolderClass
import com.fsck.k9.mail.FolderType
import com.fsck.k9.mailstore.FolderDetailsAccessor
import com.fsck.k9.mailstore.FolderMapper
import com.fsck.k9.mailstore.FolderNotFoundException
import com.fsck.k9.mailstore.LockableDatabase
import com.fsck.k9.mailstore.MoreMessages
import com.fsck.k9.mailstore.toFolderType
internal class RetrieveFolderOperations(private val lockableDatabase: LockableDatabase) {
fun <T> getFolder(folderId: Long, mapper: FolderMapper<T>): T? {
return getFolder(
selection = "id = ?",
selectionArguments = arrayOf(folderId.toString()),
mapper = mapper
)
}
fun <T> getFolder(folderServerId: String, mapper: FolderMapper<T>): T? {
return getFolder(
selection = "server_id = ?",
selectionArguments = arrayOf(folderServerId),
mapper = mapper
)
}
private fun <T> getFolder(selection: String, selectionArguments: Array<String>, mapper: FolderMapper<T>): T? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
FOLDER_COLUMNS,
selection,
selectionArguments,
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) {
val cursorFolderAccessor = CursorFolderAccessor(cursor)
mapper.map(cursorFolderAccessor)
} else {
null
}
}
}
}
fun <T> getFolders(excludeLocalOnly: Boolean = false, mapper: FolderMapper<T>): List<T> {
val selection = if (excludeLocalOnly) "local_only = 0" else null
return lockableDatabase.execute(false) { db ->
db.query("folders", FOLDER_COLUMNS, selection, null, null, null, "id").use { cursor ->
val cursorFolderAccessor = CursorFolderAccessor(cursor)
cursor.map {
mapper.map(cursorFolderAccessor)
}
}
}
}
fun <T> getDisplayFolders(displayMode: FolderMode, outboxFolderId: Long?, mapper: FolderMapper<T>): List<T> {
return lockableDatabase.execute(false) { db ->
val displayModeSelection = getDisplayModeSelection(displayMode)
val outboxFolderIdOrZero = outboxFolderId ?: 0
val query =
"""
SELECT ${FOLDER_COLUMNS.joinToString()}, (
SELECT COUNT(messages.id)
FROM messages
WHERE messages.folder_id = folders.id
AND messages.empty = 0 AND messages.deleted = 0
AND (messages.read = 0 OR folders.id = ?)
), (
SELECT COUNT(messages.id)
FROM messages
WHERE messages.folder_id = folders.id
AND messages.empty = 0 AND messages.deleted = 0
AND messages.flagged = 1
)
FROM folders
$displayModeSelection
"""
db.rawQuery(query, arrayOf(outboxFolderIdOrZero.toString())).use { cursor ->
val cursorFolderAccessor = CursorFolderAccessor(cursor)
cursor.map {
mapper.map(cursorFolderAccessor)
}
}
}
}
private fun getDisplayModeSelection(displayMode: FolderMode): String {
return when (displayMode) {
FolderMode.ALL -> {
""
}
FolderMode.FIRST_CLASS -> {
"WHERE display_class = '${FolderClass.FIRST_CLASS.name}'"
}
FolderMode.FIRST_AND_SECOND_CLASS -> {
"WHERE display_class IN ('${FolderClass.FIRST_CLASS.name}', '${FolderClass.SECOND_CLASS.name}')"
}
FolderMode.NOT_SECOND_CLASS -> {
"WHERE display_class != '${FolderClass.SECOND_CLASS.name}'"
}
FolderMode.NONE -> {
throw AssertionError("Invalid folder display mode: $displayMode")
}
}
}
fun getFolderId(folderServerId: String): Long? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
arrayOf("id"),
"server_id = ?",
arrayOf(folderServerId),
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) cursor.getLong(0) else null
}
}
}
fun getFolderServerId(folderId: Long): String? {
return lockableDatabase.execute(false) { db ->
db.query(
"folders",
arrayOf("server_id"),
"id = ?",
arrayOf(folderId.toString()),
null,
null,
null
).use { cursor ->
if (cursor.moveToFirst()) cursor.getString(0) else null
}
}
}
fun getMessageCount(folderId: Long): Int {
return lockableDatabase.execute(false) { db ->
db.rawQuery(
"SELECT COUNT(id) FROM messages WHERE empty = 0 AND deleted = 0 AND folder_id = ?",
arrayOf(folderId.toString())
).use { cursor ->
if (cursor.moveToFirst()) cursor.getInt(0) else 0
}
}
}
fun hasMoreMessages(folderId: Long): MoreMessages {
return getFolder(folderId) { it.moreMessages } ?: throw FolderNotFoundException(folderId)
}
}
private class CursorFolderAccessor(val cursor: Cursor) : FolderDetailsAccessor {
override val id: Long
get() = cursor.getLong(0)
override val name: String
get() = cursor.getString(1)
override val type: FolderType
get() = cursor.getString(2).toFolderType()
override val serverId: String?
get() = cursor.getString(3)
override val isLocalOnly: Boolean
get() = cursor.getInt(4) == 1
override val isInTopGroup: Boolean
get() = cursor.getInt(5) == 1
override val isIntegrate: Boolean
get() = cursor.getInt(6) == 1
override val syncClass: FolderClass
get() = cursor.getString(7).toFolderClass(FolderClass.INHERITED)
override val displayClass: FolderClass
get() = cursor.getString(8).toFolderClass(FolderClass.NO_CLASS)
override val notifyClass: FolderClass
get() = cursor.getString(9).toFolderClass(FolderClass.INHERITED)
override val pushClass: FolderClass
get() = cursor.getString(10).toFolderClass(FolderClass.SECOND_CLASS)
override val visibleLimit: Int
get() = cursor.getInt(11)
override val moreMessages: MoreMessages
get() = MoreMessages.fromDatabaseName(cursor.getString(12))
override val lastChecked: Long?
get() = cursor.getLongOrNull(13)
override val unreadMessageCount: Int
get() = cursor.getInt(14)
override val starredMessageCount: Int
get() = cursor.getInt(15)
override fun serverIdOrThrow(): String {
return serverId ?: error("No server ID found for folder '$name' ($id)")
}
}
private fun String?.toFolderClass(defaultValue: FolderClass): FolderClass {
return if (this == null) defaultValue else FolderClass.valueOf(this)
}
private val FOLDER_COLUMNS = arrayOf(
"id",
"name",
"type",
"server_id",
"local_only",
"top_group",
"integrate",
"poll_class",
"display_class",
"notify_class",
"push_class",
"visible_limit",
"more_messages",
"last_updated"
)
| apache-2.0 | 8e5c09a2f2e22358a2e8571792545009 | 31.091667 | 114 | 0.583615 | 4.702076 | false | false | false | false |
Naliwe/IntelliJ_WowAddOnSupport | src/org/squarecell/wow/addon_support/builders/AddOnModuleBuilder.kt | 1 | 3241 | package org.squarecell.wow.addon_support.builders
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.ide.util.projectWizard.ModuleBuilder
import com.intellij.ide.util.projectWizard.ModuleBuilderListener
import com.intellij.ide.util.projectWizard.ModuleWizardStep
import com.intellij.ide.util.projectWizard.WizardContext
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleType
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFileManager
import org.squarecell.wow.addon_support.config.MainFile
import org.squarecell.wow.addon_support.config.ProjectSettingsKeys
import org.squarecell.wow.addon_support.modules.AddOnModuleType
import org.squarecell.wow.addon_support.wizard_steps.AddOnWizardStep
import java.io.File
class AddOnModuleBuilder : ModuleBuilder(), ModuleBuilderListener {
init {
addListener(this)
}
override fun moduleCreated(module: Module) {
val tocFilePath = contentEntryPath + File.separator + module.name + ".toc"
var mainFilePath = contentEntryPath + File.separator + PropertiesComponent
.getInstance().getValue(ProjectSettingsKeys.AddOnMainFileName)
if (!mainFilePath.endsWith(".lua"))
mainFilePath += ".lua"
File(tocFilePath).writeText(PropertiesComponent.getInstance().getValue("tocFile")!!)
val file = File(mainFilePath)
file.createNewFile()
file.appendText(MainFile.initAce3AddOn)
file.appendText(MainFile.defaultInitFunc)
file.appendText(MainFile.defaultLoadFunc)
file.appendText(MainFile.defaultUnloadFunc)
}
override fun setupRootModel(modifiableRootModel: ModifiableRootModel) {
val path = contentEntryPath + File.separator + "Libs"
File(path).mkdirs()
val sourceRoot = LocalFileSystem.getInstance().refreshAndFindFileByPath(path)!!
val jarUtil = JarFileSystem.getInstance()
val desc = PluginManager.getPlugin(PluginId.getId("org.squarecell.wow.addon_support"))!!
val pluginPath = desc.path.absolutePath
val realPath = VfsUtil.pathToUrl(pluginPath)
val pluginVD = VirtualFileManager.getInstance().findFileByUrl(realPath)!!
val file = jarUtil.refreshAndFindFileByPath(pluginVD.path + "!/Wow_sdk")!!
// val classesDir = pluginVD.findChild("classes")?: pluginVD
// val deps = classesDir.findChild("Wow_sdk")!!
file.children.forEach {
VfsUtil.copy(this, it, sourceRoot)
}
super.doAddContentEntry(modifiableRootModel)?.addSourceFolder(sourceRoot, false)
}
override fun getModuleType(): ModuleType<*> {
return AddOnModuleType.instance
}
override fun getCustomOptionsStep(context: WizardContext,
parentDisposable: Disposable?): ModuleWizardStep? {
return AddOnWizardStep()
}
}
| mit | ed67ccabfcb285c00c2dd178fc383999 | 40.025316 | 96 | 0.740512 | 4.794379 | false | false | false | false |
newbieandroid/AppBase | app/src/main/java/com/fuyoul/sanwenseller/ui/money/SettlementTypeActivity.kt | 1 | 9245 | package com.fuyoul.sanwenseller.ui.money
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import com.alibaba.fastjson.JSON
import com.csl.refresh.SmartRefreshLayout
import com.csl.refresh.api.RefreshLayout
import com.csl.refresh.listener.OnRefreshLoadmoreListener
import com.fuyoul.sanwenseller.R
import com.fuyoul.sanwenseller.base.BaseActivity
import com.fuyoul.sanwenseller.base.BaseAdapter
import com.fuyoul.sanwenseller.base.BaseViewHolder
import com.fuyoul.sanwenseller.bean.AdapterMultiItem
import com.fuyoul.sanwenseller.bean.MultBaseBean
import com.fuyoul.sanwenseller.bean.reqhttp.ReqInCome
import com.fuyoul.sanwenseller.bean.reshttp.ResMoneyItem
import com.fuyoul.sanwenseller.configs.Code
import com.fuyoul.sanwenseller.configs.Data
import com.fuyoul.sanwenseller.configs.TopBarOption
import com.fuyoul.sanwenseller.listener.AppBarStateChangeListener
import com.fuyoul.sanwenseller.structure.model.MoneyInComeM
import com.fuyoul.sanwenseller.structure.presenter.MoneyInComeP
import com.fuyoul.sanwenseller.structure.view.MoneyInComeV
import com.fuyoul.sanwenseller.utils.GlideUtils
import com.fuyoul.sanwenseller.utils.TimeDateUtils
import com.netease.nim.uikit.NimUIKit
import com.netease.nim.uikit.StatusBarUtils
import kotlinx.android.synthetic.main.moneyinfolayout.*
import kotlinx.android.synthetic.main.waitforsettlementlayout.*
import java.util.*
/**
* @author: chen
* @CreatDate: 2017\10\31 0031
* @Desc:待结算
*/
class SettlementTypeActivity : BaseActivity<MoneyInComeM, MoneyInComeV, MoneyInComeP>() {
companion object {
fun start(context: Context, isHistoryType: Boolean, year: String?, month: String?) {
val intent = Intent(context, SettlementTypeActivity::class.java)
intent.putExtra("isHistoryType", isHistoryType)
if (isHistoryType) {
intent.putExtra("year", year)
intent.putExtra("month", month)
}
context.startActivity(intent)
}
}
private val req = ReqInCome()
private var index = 0
private var defaultState = AppBarStateChangeListener.State.EXPANDED//默认是展开状态
private var adapter: ThisAdapter? = null
override fun setLayoutRes(): Int = R.layout.waitforsettlementlayout
override fun initData(savedInstanceState: Bundle?) {
StatusBarUtils.setTranslucentForCoordinatorLayout(this, 30)
setSupportActionBar(toolbar)
//如果是结算历史
if (intent.getBooleanExtra("isHistoryType", false)) {
req.ordersDate = "${intent.getStringExtra("year")}${intent.getStringExtra("month")}"
}
getPresenter().viewImpl?.initAdapter(this)
getPresenter().getData(this, req, true)
}
override fun setListener() {
waitForSettlementRefreshLayout.setOnRefreshLoadmoreListener(object : OnRefreshLoadmoreListener {
override fun onRefresh(refreshlayout: RefreshLayout?) {
index = 0
req.index = "$index"
getPresenter().getData(this@SettlementTypeActivity, req, true)
}
override fun onLoadmore(refreshlayout: RefreshLayout?) {
index++
req.index = "$index"
getPresenter().getData(this@SettlementTypeActivity, req, false)
}
})
appBarLayoutOfWaitSettlement.addOnOffsetChangedListener(listener)
toolbar.setNavigationOnClickListener {
finish()
}
}
override fun onResume() {
super.onResume()
appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener)
}
override fun onPause() {
super.onPause()
appBarLayoutOfWaitSettlement.removeOnOffsetChangedListener(listener)
}
override fun getPresenter(): MoneyInComeP = MoneyInComeP(initViewImpl())
override fun initViewImpl(): MoneyInComeV = object : MoneyInComeV() {
override fun getAdapter(): BaseAdapter {
if (adapter == null) {
adapter = ThisAdapter()
}
return adapter!!
}
override fun initAdapter(context: Context) {
val manager = LinearLayoutManager(this@SettlementTypeActivity)
manager.orientation = LinearLayoutManager.VERTICAL
waitForSettlementDataList.layoutManager = manager
waitForSettlementDataList.adapter = getAdapter()
}
override fun setViewInfo(data: ResMoneyItem) {
priceCount.text = "${data.countPrice}"
orderCount.text = "${data.countOrders}"
}
}
override fun initTopBar(): TopBarOption = TopBarOption()
inner class ThisAdapter : BaseAdapter(this) {
override fun convert(holder: BaseViewHolder, position: Int, datas: List<MultBaseBean>) {
val item = datas[position] as ResMoneyItem.IncomeListBean
GlideUtils.loadNormalImg(this@SettlementTypeActivity, JSON.parseArray(item.imgs).getJSONObject(0).getString("url"), holder.itemView.findViewById(R.id.orderItemIcon))
GlideUtils.loadNormalImg(this@SettlementTypeActivity, item.avatar, holder.itemView.findViewById(R.id.orderItemHead))
holder.itemView.findViewById<TextView>(R.id.orderItemPrice).text = "¥${item.totalPrice}"
holder.itemView.findViewById<TextView>(R.id.orderItemTitle).text = "${item.name}"
holder.itemView.findViewById<TextView>(R.id.orderItemDes).text = "${item.introduce}"
holder.itemView.findViewById<TextView>(R.id.orderItemTime).text = "${TimeDateUtils.stampToDate(item.ordersDate)}"
holder.itemView.findViewById<TextView>(R.id.orderItemNick).text = "${item.nickname}"
var typeIcon: Drawable? = null
if (item.type == Data.QUICKTESTBABY) {
typeIcon = resources.getDrawable(R.mipmap.icon_quicktesttype)
typeIcon.setBounds(0, 0, typeIcon.minimumWidth, typeIcon.minimumHeight)
}
holder.itemView.findViewById<TextView>(R.id.orderItemTitle).setCompoundDrawables(null, null, typeIcon, null)
val orderItemState = holder.itemView.findViewById<TextView>(R.id.orderItemState)
orderItemState.text = "交易完成"
val orderItemFuncLayout = holder.itemView.findViewById<LinearLayout>(R.id.orderItemFuncLayout)
orderItemFuncLayout.visibility = View.VISIBLE
val orderItemReleaseTime = holder.itemView.findViewById<LinearLayout>(R.id.orderItemReleaseTime)
orderItemReleaseTime.visibility = View.GONE
val orderItemFuncRight = holder.itemView.findViewById<TextView>(R.id.orderItem_Func_Right)
orderItemFuncRight.text = "联系买家"
orderItemFuncRight.setOnClickListener {
NimUIKit.startP2PSession(this@SettlementTypeActivity, "user_${item.user_info_id}")
}
}
override fun addMultiType(multiItems: ArrayList<AdapterMultiItem>) {
multiItems.add(AdapterMultiItem(Code.VIEWTYPE_MONEY, R.layout.orderitem))
}
override fun onItemClicked(view: View, position: Int) {
}
override fun onEmpryLayou(view: View, layoutResId: Int) {
}
override fun getSmartRefreshLayout(): SmartRefreshLayout = waitForSettlementRefreshLayout
override fun getRecyclerView(): RecyclerView = waitForSettlementDataList
}
private val listener = object : AppBarStateChangeListener() {
override fun onStateChanged(appBarLayout: AppBarLayout?, state: State) {
when (state) {
State.EXPANDED -> {
//展开状态
StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity)
StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30)
toolbar.setBackgroundColor(resources.getColor(R.color.transparent))
}
State.COLLAPSED -> {
//折叠状态
toolbarOfMoneyInfo.setNavigationIcon(R.mipmap.ic_yb_top_back)
StatusBarUtils.StatusBarLightMode(this@SettlementTypeActivity, R.color.color_white)
toolbar.setBackgroundResource(R.drawable.back_titlebar)
}
else -> {
//中间状态
//如果之前是折叠状态,则表示在向下滑动
if (defaultState == State.COLLAPSED) {
StatusBarUtils.StatusBarDarkMode(this@SettlementTypeActivity)
StatusBarUtils.setTranslucentForCoordinatorLayout(this@SettlementTypeActivity, 30)
toolbar.setBackgroundColor(resources.getColor(R.color.transparent))
}
}
}
defaultState = state
}
}
} | apache-2.0 | 67aad4b9b3464eee0113aff45dec2b67 | 36.138211 | 177 | 0.678818 | 4.932505 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/actions/PageEditInterface.kt | 5 | 3876 | package fr.free.nrw.commons.actions
import io.reactivex.Observable
import io.reactivex.Single
import org.wikipedia.dataclient.Service
import org.wikipedia.dataclient.mwapi.MwQueryResponse
import org.wikipedia.edit.Edit
import org.wikipedia.wikidata.Entities
import retrofit2.http.*
/**
* This interface facilitates wiki commons page editing services to the Networking module
* which provides all network related services used by the app.
*
* This interface posts a form encoded request to the wikimedia API
* with editing action as argument to edit a particular page
*/
interface PageEditInterface {
/**
* This method posts such that the Content which the page
* has will be completely replaced by the value being passed to the
* "text" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param text Holds the page content
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("text") text: String,
// NOTE: This csrf shold always be sent as the last field of form data
@Field("token") token: String
): Observable<Edit>
/**
* This method posts such that the Content which the page
* has will be appended with the value being passed to the
* "appendText" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param appendText Text to add to the end of the page
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postAppendEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("appendtext") appendText: String,
@Field("token") token: String
): Observable<Edit>
/**
* This method posts such that the Content which the page
* has will be prepended with the value being passed to the
* "prependText" field of the encoded form data
* @param title Title of the page to edit. Cannot be used together with pageid.
* @param summary Edit summary. Also section title when section=new and sectiontitle is not set
* @param prependText Text to add to the beginning of the page
* @param token A "csrf" token
*/
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=edit")
fun postPrependEdit(
@Field("title") title: String,
@Field("summary") summary: String,
@Field("prependtext") prependText: String,
@Field("token") token: String
): Observable<Edit>
@FormUrlEncoded
@Headers("Cache-Control: no-cache")
@POST(Service.MW_API_PREFIX + "action=wbsetlabel&format=json&site=commonswiki&formatversion=2")
fun postCaptions(
@Field("summary") summary: String,
@Field("title") title: String,
@Field("language") language: String,
@Field("value") value: String,
@Field("token") token: String
): Observable<Entities>
/**
* Get wiki text for provided file names
* @param titles : Name of the file
* @return Single<MwQueryResult>
*/
@GET(
Service.MW_API_PREFIX +
"action=query&prop=revisions&rvprop=content|timestamp&rvlimit=1&converttitles="
)
fun getWikiText(
@Query("titles") title: String
): Single<MwQueryResponse?>
} | apache-2.0 | 2dad9b77f9fa30fc35f6e13ccf9b55ef | 37.386139 | 100 | 0.668215 | 4.176724 | false | false | false | false |
kittinunf/ReactiveAndroid | reactiveandroid-support-v4/src/main/kotlin/com/github/kittinunf/reactiveandroid/support/v4/widget/SwipeRefreshLayoutProperty.kt | 1 | 959 | package com.github.kittinunf.reactiveandroid.support.v4.widget
import android.support.v4.widget.SwipeRefreshLayout
import com.github.kittinunf.reactiveandroid.MutableProperty
import com.github.kittinunf.reactiveandroid.createMainThreadMutableProperty
//================================================================================
// Property
//================================================================================
val SwipeRefreshLayout.rx_refreshing: MutableProperty<Boolean>
get() {
val getter = { isRefreshing }
val setter: (Boolean) -> Unit = { isRefreshing = it }
return createMainThreadMutableProperty(getter, setter)
}
val SwipeRefreshLayout.rx_nestedScrollingEnabled: MutableProperty<Boolean>
get() {
val getter = { isNestedScrollingEnabled }
val setter: (Boolean) -> Unit = { isNestedScrollingEnabled = it }
return createMainThreadMutableProperty(getter, setter)
}
| mit | 9ca709be2942535aef9b98cbf19c1d92 | 37.36 | 82 | 0.618352 | 6.031447 | false | false | false | false |
JayNewstrom/Concrete | concrete/src/main/java/com/jaynewstrom/concrete/ConcreteWallContext.kt | 1 | 732 | package com.jaynewstrom.concrete
import android.content.Context
import android.content.ContextWrapper
import android.view.LayoutInflater
internal class ConcreteWallContext<C>(
baseContext: Context,
private val wall: ConcreteWall<C>
) : ContextWrapper(baseContext) {
private var inflater: LayoutInflater? = null
override fun getSystemService(name: String): Any? {
if (Concrete.isService(name)) {
return wall
}
if (Context.LAYOUT_INFLATER_SERVICE == name) {
if (inflater == null) {
inflater = LayoutInflater.from(baseContext).cloneInContext(this)
}
return inflater
}
return super.getSystemService(name)
}
}
| apache-2.0 | 91fa178009178e8b5c03d9f05df34541 | 28.28 | 80 | 0.657104 | 4.815789 | false | false | false | false |
NuclearCoder/nuclear-bot | src/nuclearbot/gui/components/chat/LimitedStringList.kt | 1 | 2690 | package nuclearbot.gui.components.chat
import java.util.*
import javax.swing.AbstractListModel
import javax.swing.JList
/*
* Copyright (C) 2017 NuclearCoder
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Custom JList that uses a custom model which only keeps the last lines.<br></br>
* <br></br>
* NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br>
* @author NuclearCoder (contact on the GitHub repo)
*/
class LimitedStringList(capacity: Int = 50) : JList<String>() {
private val listModel = LimitedStringList.Model(capacity).also { model = it }
/**
* Adds an element to the model. If the size of the list
* will exceed the maximum capacity, the first element
* is removed before adding the new element to the end
* of the list.
*
* @param text the line to add to the list
*/
fun add(text: String) {
listModel.add(text)
}
/**
* The ListModel used by the LimitedStringList class
*/
class Model(private val capacity: Int) : AbstractListModel<String>() {
private val arrayList = ArrayList<String>(capacity)
/**
* Adds an element to the model. If the size of the list
* will exceed the maximum capacity, the first element
* is removed before adding the new element to the end
* of the list.
*
* @param text the line to add to the list
*/
fun add(text: String) {
val index0: Int
val index1: Int
if (arrayList.size == capacity) {
index0 = 0
index1 = capacity - 1
arrayList.removeAt(0)
} else {
index1 = arrayList.size
index0 = index1
}
arrayList.add(text)
fireContentsChanged(this, index0, index1)
}
override fun getSize(): Int {
return arrayList.size
}
override fun getElementAt(index: Int): String {
return arrayList[index]
}
}
}
| agpl-3.0 | f9ba378006bf76466fafc9152088c819 | 29.91954 | 82 | 0.624535 | 4.373984 | false | false | false | false |
lanhuaguizha/Christian | app/src/main/java/com/christian/nav/me/HidingGospelFragment.kt | 1 | 7641 | package com.christian.nav.me
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.NonNull
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import com.christian.R
import com.christian.common.GOSPEL_EN
import com.christian.common.GOSPEL_ZH
import com.christian.common.auth
import com.christian.common.data.Gospel
import com.christian.common.firestore
import com.christian.databinding.ItemChatBinding
import com.christian.databinding.ItemGospelBinding
import com.christian.nav.disciple.ChatItemView
import com.christian.nav.gospel.GospelItemView
import com.christian.nav.gospel.HidingGospelItemView
import com.christian.nav.home.VIEW_TYPE_CHAT
import com.christian.nav.home.VIEW_TYPE_GOSPEL
import com.christian.swipe.SwipeBackActivity
import com.christian.util.ChristianUtil
import com.christian.view.ItemDecoration
import com.firebase.ui.firestore.FirestoreRecyclerAdapter
import com.firebase.ui.firestore.FirestoreRecyclerOptions
import com.google.firebase.firestore.FirebaseFirestoreException
import com.google.firebase.firestore.Query
import kotlinx.android.synthetic.main.fragment_detail_me.view.*
import kotlinx.android.synthetic.main.fragment_nav_rv.view.*
import kotlinx.android.synthetic.main.activity_tb_immersive.*
class HidingGospelFragment: Fragment() {
var meDetailTabId: Int = -1
private lateinit var v: View
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
v = inflater.inflate(R.layout.fragment_detail_me, container, false)
initView()
return v
}
private lateinit var gospelAdapter: FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>
private lateinit var query: Query
var mPosition = -1
private fun initView() {
initRv()
v.me_detail_pb.isIndeterminate = true
v.fragment_nav_rv.setProgressBar(v.me_detail_pb)
}
private fun initRv() {
v.fragment_nav_rv.addItemDecoration(ItemDecoration(top = ChristianUtil.dpToPx(64)))
getMeFromSettingId()
if (::gospelAdapter.isInitialized) {gospelAdapter.startListening()
v.fragment_nav_rv.adapter = gospelAdapter} // 我的-门徒-喜欢 崩溃处理
}
override fun onDestroy() {
super.onDestroy()
if (::gospelAdapter.isInitialized) gospelAdapter.stopListening() // 我的-门徒-喜欢 崩溃处理
}
/**
* tabId = 0, settingId = 0, history gospels
* tabId = 0, settingId = 1, favorite gospels
* tabId = 0, settingId = 2, published gospels
*
*
* tabId = 1, settingId = 0, history disciples
* tabId = 1, settingId = 1, following disciples
* tabId = 1, settingId = 2, followed disciples
*/
private fun getMeFromSettingId() {
(requireActivity() as HidingGospelActivity).tb_immersive_toolbar.title =
getString(R.string.hidden_gospel)
query = if (meDetailTabId == 0) {
firestore.collection(GOSPEL_EN).orderBy("createTime", Query.Direction.DESCENDING)
.whereEqualTo("show", 0)
} else {
firestore.collection(GOSPEL_ZH).orderBy("createTime", Query.Direction.DESCENDING)
.whereEqualTo("show", 0)
}
val options = FirestoreRecyclerOptions.Builder<Gospel>()
// .setLifecycleOwner(this@NavFragment)
.setQuery(query, Gospel::class.java)
.build()
gospelAdapter = object : FirestoreRecyclerAdapter<Gospel, RecyclerView.ViewHolder>(options) {
override fun getItemViewType(position: Int): Int {
return when {
getItem(position).title.isEmpty() -> {
VIEW_TYPE_CHAT
}
else -> {
VIEW_TYPE_GOSPEL
}
}
}
@NonNull
override fun onCreateViewHolder(@NonNull parent: ViewGroup,
viewType: Int): RecyclerView.ViewHolder {
when(viewType) {
0 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_gospel, parent, false)
val binding = ItemGospelBinding.bind(view)
return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
1 -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_chat, parent, false)
val binding = ItemChatBinding.bind(view)
return ChatItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
else -> {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_gospel, parent, false)
val binding = ItemGospelBinding.bind(view)
return HidingGospelItemView(binding, requireActivity() as SwipeBackActivity, meDetailTabId)
}
}
}
override fun onBindViewHolder(@NonNull holder: RecyclerView.ViewHolder,
position: Int,
@NonNull model: Gospel
) {
when {
model.title.isEmpty() -> {
applyViewHolderAnimation(holder as ChatItemView)
holder.bind(meDetailTabId, model)
}
else -> {
applyViewHolderAnimation(holder as HidingGospelItemView)
holder.bind(meDetailTabId, model)
}
}
}
override fun onDataChanged() {
super.onDataChanged()
v.me_detail_pb.visibility = View.GONE
v.me_detail_pb.isIndeterminate = false
if (itemCount == 0) {
} else {
v.fragment_nav_rv.scheduleLayoutAnimation()
}
}
override fun onError(e: FirebaseFirestoreException) {
super.onError(e)
Log.d("MeDetailFragment", e.toString())
}
}
v.fragment_nav_rv.adapter = gospelAdapter
}
fun applyViewHolderAnimation(holder: HidingGospelItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
fun applyViewHolderAnimation(holder: GospelItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
fun applyViewHolderAnimation(holder: ChatItemView) {
if (holder.adapterPosition > mPosition) {
holder.animateItemView(holder.itemView)
mPosition = holder.adapterPosition
}
}
} | gpl-3.0 | c7a9636999f4701376e2115199f79a27 | 37.01 | 119 | 0.576503 | 5.177793 | false | false | false | false |
AlmasB/FXGLGames | OutRun/src/main/kotlin/com/almasb/fxglgames/outrun/PlayerComponent.kt | 1 | 2726 | /*
* The MIT License (MIT)
*
* FXGL - JavaFX Game Library
*
* Copyright (c) 2015-2016 AlmasB (almaslvl@gmail.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.almasb.fxglgames.outrun
import com.almasb.fxgl.entity.component.Component
import javafx.beans.property.SimpleDoubleProperty
import java.lang.Math.min
/**
*
*
* @author Almas Baimagambetov (almaslvl@gmail.com)
*/
class PlayerComponent : Component() {
private var speed = 0.0
private var dy = 0.0
val boost = SimpleDoubleProperty(100.0)
override fun onUpdate(tpf: Double) {
speed = tpf * 200
dy += tpf / 4;
if (entity.x < 80 || entity.rightX > 600 - 80) {
if (dy > 0.017) {
dy -= tpf
}
}
entity.y -= dy
boost.set(min(boost.get() + tpf * 5, 100.0))
}
fun getSpeed() = dy
fun up() {
entity.translateY(-speed)
}
fun down() {
entity.translateY(speed)
}
fun left() {
if (entity.x >= speed)
entity.translateX(-speed)
}
fun right() {
if (entity.rightX + speed <= 600)
entity.translateX(speed)
}
fun boost() {
if (boost.get() <= speed * 2)
return
boost.set(Math.max(boost.get() - speed / 2, 0.0))
entity.y -= speed
}
fun applyExtraBoost() {
dy += 10
}
fun removeExtraBoost() {
dy = Math.max(0.0, dy - 10)
}
fun reset() {
dy = 0.0
// val anim = fadeOutIn(entity.view, Duration.seconds(1.5))
// anim.animatedValue.interpolator = Interpolators.BOUNCE.EASE_IN()
// anim.startInPlayState()
}
} | mit | a0d1242ecc3216f1bc4e31b99552d765 | 25.221154 | 80 | 0.629127 | 3.967977 | false | false | false | false |
brunordg/ctanywhere | app/src/main/java/br/com/codeteam/ctanywhere/ext/ContextExt.kt | 1 | 991 | package br.com.codeteam.ctanywhere.ext
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.drawable.Drawable
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
/**
* Created by Bruno Rodrigues e Rodrigues on 21/05/2018.
*/
fun Context.hasPermissions(vararg permissions: String): Boolean {
for (permission in permissions) {
if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
return false
}
}
return true
}
@Suppress("unused")
fun Context.checkSelfPermissions(permission: String) = ContextCompat.checkSelfPermission(this, permission)
fun Context.getColorCompat(@ColorRes res: Int): Int = ContextCompat.getColor(this, res)
@Suppress("unused")
fun Context.getDrawableCompat(@DrawableRes res: Int): Drawable = ContextCompat.getDrawable(this, res)!!
| mit | 335c185ec4e2caf1405a8cf6142528e1 | 29.030303 | 106 | 0.774975 | 4.463964 | false | false | false | false |
westoncb/HNDesktop | src/main/java/App.kt | 1 | 17053 | import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import com.google.gson.JsonPrimitive
import javafx.application.Platform
import javafx.embed.swing.JFXPanel
import javafx.scene.Scene
import javafx.scene.web.WebView
import javax.swing.*
import java.net.URL
import javax.net.ssl.HttpsURLConnection
import java.io.InputStreamReader
import javax.swing.UIManager
import java.awt.*
import javax.swing.event.ListSelectionEvent
import javax.swing.tree.DefaultMutableTreeNode
import javax.swing.JTree
import javax.swing.event.TreeModelEvent
import javax.swing.event.TreeModelListener
import javax.swing.plaf.metal.DefaultMetalTheme
import javax.swing.plaf.metal.MetalLookAndFeel
import javax.swing.tree.DefaultTreeCellRenderer
import javax.swing.tree.DefaultTreeModel
import kotlin.collections.ArrayList
import javax.swing.text.html.HTMLDocument
import javax.swing.text.html.HTMLEditorKit
/**
* Created by weston on 8/26/17.
*/
/**
* TODO:
* +Webview toggling
* User profiles
* (periodic?) Refresh
*/
class App : PubSub.Subscriber {
companion object {
init {
// MetalLookAndFeel.setCurrentTheme(DefaultMetalTheme())
// UIManager.setLookAndFeel(MetalLookAndFeel())
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel")
}
}
val progressBar = JProgressBar(0, 30)
var contentPane = JPanel()
var storyControlPanel = JPanel()
var storyPanel: JPanel = JPanel()
var mainRightPane = JPanel()
val listModel = DefaultListModel<Story>()
val storyList = JList(listModel)
val userLabel = JLabel()
val pointsLabel = JLabel()
val storyTimeLabel = JLabel()
val storyURLLabel = JLabel()
val commentCountLabel = JLabel()
val contentToggleButton = JButton("View Page")
var headlinePanel = JPanel()
var storyIconPanel = JLabel()
var commentTree = JTree()
var commentTreeRoot = DefaultMutableTreeNode()
var commentsProgressBar = JProgressBar()
var loadedCommentCount = 0
val jfxPanel = JFXPanel()
var activeStory: Story? = null
var viewingComments = true
init {
val frame = JFrame("Hacker News")
val screenSize = Toolkit.getDefaultToolkit().screenSize
val frameSize = Dimension((screenSize.width*0.90f).toInt(), (screenSize.height*0.85f).toInt())
frame.size = frameSize
frame.contentPane = contentPane
contentPane.preferredSize = frameSize
contentPane.layout = GridBagLayout()
val c = GridBagConstraints()
c.anchor = GridBagConstraints.CENTER
progressBar.preferredSize = Dimension(400, 25)
progressBar.isStringPainted = true
//Just add so the display updates. Not sure why, but
//it delays showing the progress bar if we don't do this.
contentPane.add(JLabel(""), c)
c.gridy = 1
contentPane.add(progressBar, c)
progressBar.value = 0
frame.setLocation(screenSize.width / 2 - frame.size.width / 2, screenSize.height / 2 - frame.size.height / 2)
frame.pack()
frame.isVisible = true
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
val stories = getFrontPageStories()
contentPane = JPanel(BorderLayout())
frame.contentPane = contentPane
val mainPanel = getMainPanel(stories)
contentPane.add(mainPanel)
storyList.selectedIndex = 0
storyList.setCellRenderer(StoryCellRenderer())
contentToggleButton.addActionListener {
if (activeStory != null) {
if (viewingComments) {
showPage(activeStory)
} else {
showComments(activeStory)
}
}
}
frame.revalidate()
PubSub.subscribe(PubSub.STORY_ICON_LOADED, this)
styleComponents()
}
fun styleComponents() {
this.storyURLLabel.foreground = Color(100, 100, 100)
this.storyList.background = Color(242, 242, 242)
//Dimensions here are somewhat arbitrary, but if we want
//equal priority given to both splitpane panels, they each
//need minimum sizes
mainRightPane.minimumSize = Dimension(300, 200)
}
fun getMainPanel(storyNodes: ArrayList<JsonObject>) : JComponent {
val stories = storyNodes
.filter { it.get("type").asString.equals("story", true) }
.map { Story(it) }
val def = DefaultListCellRenderer()
val renderer = ListCellRenderer<Story> { list, value, index, isSelected, cellHasFocus ->
def.getListCellRendererComponent(list, value.title, index, isSelected, cellHasFocus)
}
storyList.cellRenderer = renderer
storyList.addListSelectionListener { e: ListSelectionEvent? ->
if (e != null) {
if (!e.valueIsAdjusting) {
changeActiveStory(stories[storyList.selectedIndex])
}
}
}
for (story in stories) {
listModel.addElement(story)
}
mainRightPane = buildMainRightPanel()
val storyScroller = JScrollPane(storyList)
storyScroller.minimumSize = Dimension(200, 200)
storyScroller.verticalScrollBar.unitIncrement = 16
val splitPane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT, storyScroller, mainRightPane)
splitPane.isOneTouchExpandable = true
return splitPane
}
fun changeActiveStory(story: Story) {
activeStory = story
userLabel.text = "Posted by: ${story.user}"
pointsLabel.text = "Points: ${story.points}"
storyTimeLabel.text = "Time: ${story.time}"
commentCountLabel.text = "Comments: ${story.totalComments}"
if (story.url != null) {
storyURLLabel.text = story.url
}
showComments(activeStory)
}
fun showComments(story: Story?) {
if (story != null) {
viewingComments = true
contentToggleButton.text = "View Page"
storyPanel.removeAll()
storyPanel.add(getCommentsPanel(story))
if (story.bigIcon != null) {
storyIconPanel.icon = ImageIcon(story.bigIcon)
} else {
storyIconPanel.icon = story.favicon
}
storyIconPanel.preferredSize = Dimension(storyIconPanel.icon.iconWidth+6, storyIconPanel.icon.iconHeight)
storyIconPanel.border = BorderFactory.createEmptyBorder(0, 3, 0, 3)
headlinePanel.preferredSize = Dimension(storyControlPanel.size.width, Math.max(32, storyIconPanel.icon.iconHeight))
loadComments(story)
}
}
fun showPage(story: Story?) {
if (story != null) {
viewingComments = false
contentToggleButton.text = "View Comments"
cancelCommentLoading()
storyPanel.removeAll()
storyPanel.add(jfxPanel)
Platform.runLater {
val webView = WebView()
jfxPanel.scene = Scene(webView)
webView!!.engine.load(story.url)
}
storyPanel.revalidate()
} else {
println("Tried showing page but story was null")
}
}
override fun messageArrived(eventName: String, data: Any?) {
if (eventName == PubSub.STORY_ICON_LOADED) {
storyList.repaint()
storyControlPanel.repaint()
}
}
fun loadComments(story: Story) {
if (story.totalComments == 0)
return
Thread(Runnable {
if (story.kids != null) {
var index = 0
val iter = story.kids.iterator()
while(iter.hasNext() && viewingComments) {
val commentId = iter.next().asInt
val address = "$index"
loadCommentAux(Comment(getItem(commentId), address), address)
index++
}
} }).start()
}
fun loadCommentAux(comment: Comment, treeAddress: String) {
commentArrived(comment, treeAddress)
if (comment.kids != null) {
var index = 0
val iter = comment.kids.iterator()
while(iter.hasNext() && viewingComments) {
val commentId = iter.next().asInt
val address = treeAddress+";$index"
loadCommentAux(Comment(getItem(commentId), address), address)
index++
}
}
}
fun commentArrived(comment: Comment, treeAddress: String) {
if (!viewingComments)
return
addNodeAtAddress(DefaultMutableTreeNode(comment), comment.treeAddress)
commentsProgressBar.value = ++loadedCommentCount
if (loadedCommentCount >= commentsProgressBar.maximum) {
val parent = commentsProgressBar.parent
if (parent != null) {
parent.remove(commentsProgressBar)
parent.revalidate()
}
}
}
fun cancelCommentLoading() {
loadedCommentCount = commentsProgressBar.maximum
}
fun addNodeAtAddress(node: DefaultMutableTreeNode, address: String) {
if (!viewingComments)
return
val addressArray = address.split(";")
var parentNode = commentTreeRoot
for ((index, addressComponent) in addressArray.withIndex()) {
// Don't use the last component in the addressArray since that's the index
// which the child should be added at
if (index < addressArray.size - 1) {
val childIndex = Integer.parseInt("$addressComponent")
if (childIndex < parentNode.childCount) {
parentNode = parentNode.getChildAt(childIndex) as DefaultMutableTreeNode
}
}
}
val childIndex = Integer.parseInt(addressArray[addressArray.size-1])
(commentTree.model as DefaultTreeModel).insertNodeInto(node, parentNode, childIndex)
}
fun getCommentsPanel(story: Story) : JPanel {
loadedCommentCount = 0
val panel = JPanel(BorderLayout())
commentTreeRoot = DefaultMutableTreeNode("Comments")
commentTree = JTree(commentTreeRoot)
commentTree.toggleClickCount = 1
commentTree.cellRenderer = CommentCellRenderer()
commentTree.model.addTreeModelListener(ExpandTreeListener(commentTree))
val treeScroller = JScrollPane(commentTree)
treeScroller.verticalScrollBar.unitIncrement = 16
treeScroller.horizontalScrollBar.unitIncrement = 16
if (!(UIManager.getLookAndFeel() is MetalLookAndFeel)) {
treeScroller.background = Color(242, 242, 242)
commentTree.background = Color(242, 242, 242)
}
panel.add(treeScroller, BorderLayout.CENTER)
var totalComments = 0
if (story.totalComments != null) {
totalComments = story.totalComments
}
commentsProgressBar = JProgressBar()
commentsProgressBar.minimum = 0
commentsProgressBar.maximum = totalComments
panel.add(commentsProgressBar, BorderLayout.NORTH)
return panel
}
fun buildMainRightPanel() : JPanel {
val root = JPanel()
root.layout = BorderLayout()
storyControlPanel = JPanel(GridLayout(1, 1))
storyPanel = JPanel(BorderLayout())
root.add(storyControlPanel, BorderLayout.NORTH)
headlinePanel = JPanel(BorderLayout())
headlinePanel.border = BorderFactory.createEmptyBorder(3, 3, 3, 3)
headlinePanel.add(storyIconPanel, BorderLayout.WEST)
headlinePanel.add(storyURLLabel, BorderLayout.CENTER)
headlinePanel.add(contentToggleButton, BorderLayout.EAST)
storyControlPanel.add(headlinePanel)
root.add(storyPanel, BorderLayout.CENTER)
return root
}
fun getFrontPageStories() : ArrayList<JsonObject> {
val storyIDs = treeFromURL("https://hacker-news.firebaseio.com/v0/topstories.json")
val iter = storyIDs.asJsonArray.iterator()
val stories = ArrayList<JsonObject>()
var count = 0
while (iter.hasNext()) {
val id = (iter.next() as JsonPrimitive).asInt
val story = getItem(id)
stories.add(story.asJsonObject)
count++
progressBar.value = count
if (count > 29)
break
}
return stories
}
fun getItem(id: Int) : JsonObject {
val item = treeFromURL("https://hacker-news.firebaseio.com/v0/item/$id.json")
return item.asJsonObject
}
fun treeFromURL(url: String) : JsonElement {
val url = URL(url)
val connection = (url.openConnection()) as HttpsURLConnection
val reader = InputStreamReader(connection?.inputStream)
val parser = JsonParser()
val element = parser.parse(reader)
reader.close()
return element
}
class StoryCellRenderer : DefaultListCellRenderer() {
override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus) as JComponent
this.border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(3, 3, 3, 3))
if (!isSelected && !cellHasFocus) {
this.background = Color(242, 242, 242)
}
this.icon = (value as Story).favicon
this.text = "<html><span style=\"color: #333333; font-size: 10px\">${value.title}</span><br><span style=\"color: #777777; font-size:8px;\"> ${value.points} points by ${value.user} ${value.time} | ${value.totalComments} comments</span></html>"
return this
}
}
class CommentCellRenderer : DefaultTreeCellRenderer() {
override fun getTreeCellRendererComponent(tree: JTree?, value: Any?, sel: Boolean, expanded: Boolean, leaf: Boolean, row: Int, hasFocus: Boolean): Component? {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus)
if ((value as DefaultMutableTreeNode).userObject !is Comment) {
return JLabel()
}
val comment = value.userObject as Comment
var originalCommentText = comment.text
if (originalCommentText == null)
originalCommentText = ""
val panel = JPanel()
panel.layout = BoxLayout(panel, BoxLayout.Y_AXIS)
panel.background = Color(225, 225, 235)
val metaDataLabel = JLabel(comment.user + " " + comment.time)
metaDataLabel.foreground = Color(60, 60, 60)
metaDataLabel.font = Font("Arial", Font.PLAIN, 11)
metaDataLabel.border = BorderFactory.createEmptyBorder(3, 3, 3, 3)
panel.add(metaDataLabel)
//Insert linebreaks periodically since this seems to be the only way to limit
//the width of the html rendering JTextPane without also limiting the height
var text = ""
var index = 0
val words = originalCommentText.split(" ")
for (word in words) {
if (word.indexOf("<br>") != -1 || word.indexOf("</p>") != -1 || word.indexOf("</pre>") != -1) {
index = 0
} else if (index > 20) {
index = 0
text += "<br>"
}
text += " " + word
index++
}
val textPane = JTextPane()
textPane.contentType = "text/html"
textPane.isEditable = false
val doc = textPane.document as HTMLDocument
val editorKit = textPane.editorKit as HTMLEditorKit
editorKit.insertHTML(doc, doc.length, text, 0, 0, null)
textPane.background = Color(242, 242, 255)
textPane.border = BorderFactory.createCompoundBorder(BorderFactory.createEtchedBorder(), BorderFactory.createEmptyBorder(5, 5, 5, 5))
textPane.minimumSize = Dimension(textPane.size.width, textPane.size.height)
panel.add(textPane)
return panel
}
}
class ExpandTreeListener(theTree: JTree) : TreeModelListener {
val tree = theTree
override fun treeStructureChanged(e: TreeModelEvent?) {
}
override fun treeNodesChanged(e: TreeModelEvent?) {
}
override fun treeNodesRemoved(e: TreeModelEvent?) {
}
override fun treeNodesInserted(e: TreeModelEvent?) {
if (e != null) {
if (e.treePath.pathCount == 1) {
this.tree.expandPath(e.treePath)
}
}
}
}
}
fun main(args: Array<String>) {
App()
}
| mit | 1f900d1051def469acfb5e875158ffd4 | 32.177043 | 254 | 0.615552 | 4.905926 | false | false | false | false |
talhacohen/android | app/src/main/java/com/etesync/syncadapter/log/PlainTextFormatter.kt | 1 | 1903 | /*
* Copyright © 2013 – 2016 Ricki Hirner (bitfire web engineering).
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*/
package com.etesync.syncadapter.log
import org.apache.commons.lang3.StringUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.apache.commons.lang3.time.DateFormatUtils
import java.util.logging.Formatter
import java.util.logging.LogRecord
class PlainTextFormatter private constructor(private val logcat: Boolean) : Formatter() {
override fun format(r: LogRecord): String {
val builder = StringBuilder()
if (!logcat)
builder.append(DateFormatUtils.format(r.millis, "yyyy-MM-dd HH:mm:ss"))
.append(" ").append(r.threadID).append(" ")
if (r.sourceClassName.replaceFirst("\\$.*".toRegex(), "") != r.loggerName)
builder.append("[").append(shortClassName(r.sourceClassName)).append("] ")
builder.append(r.message)
if (r.thrown != null)
builder.append("\nEXCEPTION ")
.append(ExceptionUtils.getStackTrace(r.thrown))
if (r.parameters != null) {
var idx = 1
for (param in r.parameters)
builder.append("\n\tPARAMETER #").append(idx++).append(" = ").append(param)
}
if (!logcat)
builder.append("\n")
return builder.toString()
}
private fun shortClassName(className: String): String? {
val s = StringUtils.replace(className, "com.etesync.syncadapter.", "")
return StringUtils.replace(s, "at.bitfire.", "")
}
companion object {
val LOGCAT = PlainTextFormatter(true)
val DEFAULT = PlainTextFormatter(false)
}
}
| gpl-3.0 | 78d679d25643810875d7816dee049fab | 31.758621 | 91 | 0.644737 | 4.269663 | false | false | false | false |
google/ksp | compiler-plugin/src/main/kotlin/com/google/devtools/ksp/symbol/impl/java/KSClassDeclarationJavaImpl.kt | 1 | 6743 | /*
* Copyright 2020 Google LLC
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.devtools.ksp.symbol.impl.java
import com.google.devtools.ksp.KSObjectCache
import com.google.devtools.ksp.isConstructor
import com.google.devtools.ksp.memoized
import com.google.devtools.ksp.processing.impl.ResolverImpl
import com.google.devtools.ksp.processing.impl.workaroundForNested
import com.google.devtools.ksp.symbol.*
import com.google.devtools.ksp.symbol.impl.*
import com.google.devtools.ksp.symbol.impl.binary.getAllFunctions
import com.google.devtools.ksp.symbol.impl.binary.getAllProperties
import com.google.devtools.ksp.symbol.impl.kotlin.KSErrorType
import com.google.devtools.ksp.symbol.impl.kotlin.KSExpectActualNoImpl
import com.google.devtools.ksp.symbol.impl.kotlin.KSNameImpl
import com.google.devtools.ksp.symbol.impl.kotlin.getKSTypeCached
import com.google.devtools.ksp.symbol.impl.replaceTypeArguments
import com.google.devtools.ksp.symbol.impl.synthetic.KSConstructorSyntheticImpl
import com.google.devtools.ksp.toKSModifiers
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiJavaFile
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.load.java.structure.impl.JavaClassImpl
import org.jetbrains.kotlin.types.typeUtil.replaceArgumentsWithStarProjections
class KSClassDeclarationJavaImpl private constructor(val psi: PsiClass) :
KSClassDeclaration,
KSDeclarationJavaImpl(psi),
KSExpectActual by KSExpectActualNoImpl() {
companion object : KSObjectCache<PsiClass, KSClassDeclarationJavaImpl>() {
fun getCached(psi: PsiClass) = cache.getOrPut(psi) { KSClassDeclarationJavaImpl(psi) }
}
override val origin = Origin.JAVA
override val location: Location by lazy {
psi.toLocation()
}
override val annotations: Sequence<KSAnnotation> by lazy {
psi.annotations.asSequence().map { KSAnnotationJavaImpl.getCached(it) }.memoized()
}
override val classKind: ClassKind by lazy {
when {
psi.isAnnotationType -> ClassKind.ANNOTATION_CLASS
psi.isInterface -> ClassKind.INTERFACE
psi.isEnum -> ClassKind.ENUM_CLASS
else -> ClassKind.CLASS
}
}
override val containingFile: KSFile? by lazy {
KSFileJavaImpl.getCached(psi.containingFile as PsiJavaFile)
}
override val isCompanionObject = false
// Could the resolution ever fail?
private val descriptor: ClassDescriptor? by lazy {
ResolverImpl.instance!!.moduleClassResolver.resolveClass(JavaClassImpl(psi).apply { workaroundForNested() })
}
// TODO in 1.5 + jvmTarget 15, will we return Java permitted types?
override fun getSealedSubclasses(): Sequence<KSClassDeclaration> = emptySequence()
override fun getAllFunctions(): Sequence<KSFunctionDeclaration> =
descriptor?.getAllFunctions() ?: emptySequence()
override fun getAllProperties(): Sequence<KSPropertyDeclaration> =
descriptor?.getAllProperties() ?: emptySequence()
override val declarations: Sequence<KSDeclaration> by lazy {
val allDeclarations = (
psi.fields.asSequence().map {
when (it) {
is PsiEnumConstant -> KSClassDeclarationJavaEnumEntryImpl.getCached(it)
else -> KSPropertyDeclarationJavaImpl.getCached(it)
}
} +
psi.innerClasses.map { KSClassDeclarationJavaImpl.getCached(it) } +
psi.constructors.map { KSFunctionDeclarationJavaImpl.getCached(it) } +
psi.methods.map { KSFunctionDeclarationJavaImpl.getCached(it) }
)
.distinct()
// java annotation classes are interface. they get a constructor in .class
// hence they should get one here.
if (classKind == ClassKind.ANNOTATION_CLASS || !psi.isInterface) {
val hasConstructor = allDeclarations.any {
it is KSFunctionDeclaration && it.isConstructor()
}
if (hasConstructor) {
allDeclarations.memoized()
} else {
(allDeclarations + KSConstructorSyntheticImpl.getCached(this)).memoized()
}
} else {
allDeclarations.memoized()
}
}
override val modifiers: Set<Modifier> by lazy {
val modifiers = mutableSetOf<Modifier>()
modifiers.addAll(psi.toKSModifiers())
if (psi.isAnnotationType) {
modifiers.add(Modifier.ANNOTATION)
}
if (psi.isEnum) {
modifiers.add(Modifier.ENUM)
}
modifiers
}
override val primaryConstructor: KSFunctionDeclaration? = null
override val qualifiedName: KSName by lazy {
KSNameImpl.getCached(psi.qualifiedName!!)
}
override val simpleName: KSName by lazy {
KSNameImpl.getCached(psi.name!!)
}
override val superTypes: Sequence<KSTypeReference> by lazy {
val adjusted = if (!psi.isInterface && psi.superTypes.size > 1) {
psi.superTypes.filterNot {
it.className == "Object" && it.canonicalText == "java.lang.Object"
}
} else {
psi.superTypes.toList()
}
adjusted.asSequence().map { KSTypeReferenceJavaImpl.getCached(it, this) }.memoized()
}
override val typeParameters: List<KSTypeParameter> by lazy {
psi.typeParameters.map { KSTypeParameterJavaImpl.getCached(it) }
}
override fun asType(typeArguments: List<KSTypeArgument>): KSType {
return descriptor?.let {
it.defaultType.replaceTypeArguments(typeArguments)?.let {
getKSTypeCached(it, typeArguments)
}
} ?: KSErrorType
}
override fun asStarProjectedType(): KSType {
return descriptor?.let {
getKSTypeCached(it.defaultType.replaceArgumentsWithStarProjections())
} ?: KSErrorType
}
override fun <D, R> accept(visitor: KSVisitor<D, R>, data: D): R {
return visitor.visitClassDeclaration(this, data)
}
}
| apache-2.0 | c989627a8e542a240d1cb9a6b9a869d5 | 37.976879 | 116 | 0.689901 | 4.772116 | false | false | false | false |
macleod2486/AndroidSwissKnife | app/src/main/java/com/macleod2486/androidswissknife/components/Flashlight.kt | 1 | 3071 | /*
AndroidSwissKnife
Copyright (C) 2016 macleod2486
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.macleod2486.androidswissknife.components
import android.Manifest
import android.content.pm.PackageManager
import android.graphics.SurfaceTexture
import android.hardware.Camera
import androidx.core.app.ActivityCompat
import androidx.fragment.app.FragmentActivity
import androidx.core.content.ContextCompat
import android.util.Log
import android.view.View
import android.widget.Toast
class Flashlight(var activity: FragmentActivity, var requestCode: Int) : View.OnClickListener {
var torchOn = false
lateinit var cam: Camera
lateinit var p: Camera.Parameters
override fun onClick(view: View) {
Log.i("Flashlight", "Current toggle $torchOn")
if (checkPermissions()) {
if (torchOn) {
turnOffLight()
} else {
turnOnLight()
}
}
}
fun toggleLight() {
if (torchOn) {
turnOffLight()
} else {
turnOnLight()
}
}
private fun turnOnLight() {
Log.i("Flashlight", "Toggling on light")
try {
cam = Camera.open()
p = cam.getParameters()
p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH)
cam.setParameters(p)
val mPreviewTexture = SurfaceTexture(0)
cam.setPreviewTexture(mPreviewTexture)
cam.startPreview()
torchOn = true
} catch (ex: Exception) {
torchOn = false
Log.e("Flashlight", ex.toString())
}
}
private fun turnOffLight() {
Log.i("Flashlight", "Toggling off light")
torchOn = false
cam.stopPreview()
cam.release()
}
private fun checkPermissions(): Boolean {
var allowed = false
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
Toast.makeText(activity.applicationContext, "Need to enable camera permissions", Toast.LENGTH_SHORT).show()
} else {
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.CAMERA), requestCode)
}
} else {
allowed = true
}
return allowed
}
} | gpl-3.0 | 15ecbd0d2f1ba51c5b00356febdc2483 | 32.758242 | 123 | 0.647021 | 4.783489 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/InsertKotlinClassAction.kt | 1 | 8218 | package wu.seal.jsontokotlin
import com.google.gson.Gson
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.editor.Caret
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import wu.seal.jsontokotlin.feedback.StartAction
import wu.seal.jsontokotlin.feedback.SuccessCompleteAction
import wu.seal.jsontokotlin.feedback.dealWithException
import wu.seal.jsontokotlin.feedback.sendActionInfo
import wu.seal.jsontokotlin.model.UnSupportJsonException
import wu.seal.jsontokotlin.ui.JsonInputDialog
import wu.seal.jsontokotlin.utils.*
import java.net.URL
import java.util.*
import kotlin.math.max
/**
* Plugin action
* Created by Seal.Wu on 2017/8/18.
*/
class InsertKotlinClassAction : AnAction("Kotlin data classes from JSON") {
private val gson = Gson()
override fun actionPerformed(event: AnActionEvent) {
var jsonString = ""
try {
actionStart()
val project = event.getData(PlatformDataKeys.PROJECT)
val caret = event.getData(PlatformDataKeys.CARET)
val editor = event.getData(PlatformDataKeys.EDITOR_EVEN_IF_INACTIVE)
if (couldNotInsertCode(editor)) return
val document = editor?.document ?: return
val editorText = document.text
/**
* temp class name for insert
*/
var tempClassName = ""
val couldGetAndReuseClassNameInCurrentEditFileForInsertCode =
couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText)
if (couldGetAndReuseClassNameInCurrentEditFileForInsertCode) {
/**
* auto obtain the current class name
*/
tempClassName = getCurrentEditFileTemClassName(editorText)
}
val inputDialog = JsonInputDialog(tempClassName, project!!)
inputDialog.show()
val className = inputDialog.getClassName()
val inputString = inputDialog.inputString
val json = if (inputString.startsWith("http")) {
URL(inputString).readText()
} else inputString
if (json.isEmpty()) {
return
}
jsonString = json
if (reuseClassName(couldGetAndReuseClassNameInCurrentEditFileForInsertCode, className, tempClassName)) {
executeCouldRollBackAction(project) {
/**
* if you don't clean then we will trick a conflict with two same class name error
*/
cleanCurrentEditFile(document)
}
}
if (insertKotlinCode(project, document, className, jsonString, caret)) {
actionComplete()
}
} catch (e: UnSupportJsonException) {
val advice = e.advice
Messages.showInfoMessage(dealWithHtmlConvert(advice), "Tip")
} catch (e: Throwable) {
dealWithException(jsonString, e)
throw e
}
}
private fun dealWithHtmlConvert(advice: String) = advice.replace("<", "<").replace(">", ">")
private fun reuseClassName(
couldGetAndReuseClassNameInCurrentEditFileForInserCode: Boolean,
className: String,
tempClassName: String
) = couldGetAndReuseClassNameInCurrentEditFileForInserCode && className == tempClassName
private fun couldNotInsertCode(editor: Editor?): Boolean {
if (editor == null || editor.document.isWritable.not()) {
Messages.showWarningDialog("Please open a file in edited state for inserting Kotlin code!", "No Edited File")
return true
}
return false
}
private fun actionComplete() {
Thread {
sendActionInfo(gson.toJson(SuccessCompleteAction()))
}.start()
}
private fun actionStart() {
Thread {
sendActionInfo(gson.toJson(StartAction()))
}.start()
}
private fun insertKotlinCode(
project: Project?,
document: Document,
className: String,
jsonString: String,
caret: Caret?
): Boolean {
ClassImportDeclarationWriter.insertImportClassCode(project, document)
val codeMaker: KotlinClassCodeMaker
try {
//passing current file directory along with className and json
val kotlinClass = KotlinClassMaker(className, jsonString).makeKotlinClass()
codeMaker = KotlinClassCodeMaker(kotlinClass, jsonString.isJSONSchema())
} catch (e: IllegalFormatFlagsException) {
e.printStackTrace()
Messages.showErrorDialog(e.message, "UnSupport Json")
return false
}
val generateClassesString = codeMaker.makeKotlinClassCode()
executeCouldRollBackAction(project) {
var offset: Int
if (caret != null) {
offset = caret.offset
if (offset == 0) {
offset = document.textLength
}
val lastPackageKeywordLineEndIndex = try {
"^[\\s]*package\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.last
} catch (e: Exception) {
-1
}
val lastImportKeywordLineEndIndex = try {
"^[\\s]*import\\s.+\n$".toRegex(RegexOption.MULTILINE).findAll(document.text).last().range.last
} catch (e: Exception) {
-1
}
if (offset < lastPackageKeywordLineEndIndex) {
offset = lastPackageKeywordLineEndIndex + 1
}
if (offset < lastImportKeywordLineEndIndex) {
offset = lastImportKeywordLineEndIndex + 1
}
} else {
offset = document.textLength
}
document.insertString(
max(offset, 0),
ClassCodeFilter.removeDuplicateClassCode(generateClassesString)
)
}
return true
}
private fun cleanCurrentEditFile(document: Document, editorText: String = document.text) {
val cleanText = getCleanText(editorText)
document.setText(cleanText)
}
fun getCleanText(editorText: String): String {
val tempCleanText = editorText.substringBeforeLast("class")
return if (tempCleanText.trim().endsWith("data")) tempCleanText.trim().removeSuffix("data") else tempCleanText
}
fun getCurrentEditFileTemClassName(editorText: String) = editorText.substringAfterLast("class")
.substringBefore("(").substringBefore("{").trim()
/**
* whether we could reuse current class name declared in the edit file for inserting data class code
* if we could use it,then we would clean the kotlin file as it was new file without any class code .
*/
fun couldGetAndReuseClassNameInCurrentEditFileForInsertCode(editorText: String): Boolean {
try {
val removeDocComment = editorText.replace(Regex("/\\*\\*(.|\n)*\\*/", RegexOption.MULTILINE), "")
val removeDocCommentAndPackageDeclareText = removeDocComment
.replace(Regex("^(?:\\s*package |\\s*import ).*$", RegexOption.MULTILINE), "")
removeDocCommentAndPackageDeclareText.run {
if (numberOf("class") == 1 &&
(substringAfter("class").containsAnyOf(listOf("(", ":", "=")).not()
|| substringAfter("class").substringAfter("(").replace(
Regex("\\s"),
""
).let { it == ")" || it == "){}" })
) {
return true
}
}
} catch (e: Throwable) {
e.printStackTrace()
}
return false
}
}
| gpl-3.0 | 331878500b49281dd63d70b1612b276f | 37.401869 | 121 | 0.597834 | 5.460465 | false | false | false | false |
jtransc/jtransc | benchmark_kotlin_mpp/wip/jzlib/GZIPInputStream.kt | 1 | 4000 | /* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /*
Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jtransc.compression.jzlib
import com.jtransc.annotation.JTranscInvisible
import java.io.IOException
@JTranscInvisible
class GZIPInputStream(
`in`: java.io.InputStream?,
inflater: Inflater?,
size: Int,
close_in: Boolean
) : InflaterInputStream(`in`, inflater, size, close_in) {
@JvmOverloads
constructor(
`in`: java.io.InputStream?,
size: Int = DEFAULT_BUFSIZE,
close_in: Boolean = true
) : this(`in`, Inflater(15 + 16), size, close_in) {
myinflater = true
}
val modifiedtime: Long
get() = inflater.istate.getGZIPHeader().getModifiedTime()
val oS: Int
get() = inflater.istate.getGZIPHeader().getOS()
val name: String
get() = inflater.istate.getGZIPHeader().getName()
val comment: String
get() = inflater.istate.getGZIPHeader().getComment()
/*DONE*/
@get:Throws(GZIPException::class)
val cRC: Long
get() {
if (inflater.istate.mode !== 12 /*DONE*/) throw GZIPException("checksum is not calculated yet.")
return inflater.istate.getGZIPHeader().getCRC()
}
@Throws(IOException::class)
override fun readHeader() {
val empty: ByteArray = "".toByteArray()
inflater.setOutput(empty, 0, 0)
inflater.setInput(empty, 0, 0, false)
val b = ByteArray(10)
var n = fill(b)
if (n != 10) {
if (n > 0) {
inflater.setInput(b, 0, n, false)
//inflater.next_in_index = n;
inflater.next_in_index = 0
inflater.avail_in = n
}
throw IOException("no input")
}
inflater.setInput(b, 0, n, false)
val b1 = ByteArray(1)
do {
if (inflater.avail_in <= 0) {
val i: Int = `in`.read(b1)
if (i <= 0) throw IOException("no input")
inflater.setInput(b1, 0, 1, true)
}
val err: Int = inflater.inflate(JZlib.Z_NO_FLUSH)
if (err != 0 /*Z_OK*/) {
val len: Int = 2048 - inflater.next_in.length
if (len > 0) {
val tmp = ByteArray(len)
n = fill(tmp)
if (n > 0) {
inflater.avail_in += inflater.next_in_index
inflater.next_in_index = 0
inflater.setInput(tmp, 0, n, true)
}
}
//inflater.next_in_index = inflater.next_in.length;
inflater.avail_in += inflater.next_in_index
inflater.next_in_index = 0
throw IOException(inflater.msg)
}
} while (inflater.istate.inParsingHeader())
}
private fun fill(buf: ByteArray): Int {
val len = buf.size
var n = 0
do {
var i = -1
try {
i = `in`.read(buf, n, buf.size - n)
} catch (e: IOException) {
}
if (i == -1) {
break
}
n += i
} while (n < len)
return n
}
} | apache-2.0 | 3520d2983fe6c587932c68ae53584650 | 30.753968 | 99 | 0.68975 | 3.433476 | false | false | false | false |
Fitbit/MvRx | mock_generation/ShellAccess.kt | 1 | 5910 | #!/usr/bin/env kscript
/**
* Functions for executing shell commands and receiving the result.
*/
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.lang.ProcessBuilder.Redirect
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess
/**
* Executes the receiving string and returns the stdOut as a single line.
* If the result is more than one line an exception is thrown.
* @throws IOException if an I/O error occurs
*/
fun String.executeForSingleLine(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
suppressStderr: Boolean = false,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): String {
val lines = executeForLines(
workingDir,
timeoutAmount,
timeoutUnit,
suppressStderr = suppressStderr,
redactedTokens = redactedTokens,
throwOnFailure = throwOnFailure
)
.filter { it.isNotBlank() }
return lines.singleOrNull() ?: throw IllegalStateException("Expected single line but got: $lines")
}
/**
* Executes the receiving string and returns the stdOut as a list of all lines outputted.
* @throws IOException if an I/O error occurs
* @param clearQuotes If true, double quotes will be removed if they wrap the line
*/
fun String.executeForLines(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
clearQuotes: Boolean = false,
suppressStderr: Boolean = false,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): List<String> {
return executeForBufferedReader(
workingDir,
timeoutAmount,
timeoutUnit,
suppressStderr = suppressStderr,
redactedTokens = redactedTokens,
throwOnFailure = throwOnFailure
)
.readLines()
.map { if (clearQuotes) it.removePrefix("\"").removeSuffix("\"") else it }
}
/**
* Executes the receiving string and returns the stdOut as a BufferedReader.
* @throws IOException if an I/O error occurs
*/
fun String.executeForBufferedReader(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
suppressStderr: Boolean = false,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): BufferedReader {
val stderrRedirectBehavior = if (suppressStderr) Redirect.PIPE else Redirect.INHERIT
return execute(
workingDir,
timeoutAmount,
timeoutUnit,
stderrRedirectBehavior = stderrRedirectBehavior,
redactedTokens = redactedTokens,
throwOnFailure = throwOnFailure
).stdOut
}
/**
* Executes the receiving string and returns the result,
* including exit code, stdOut, and stdErr streams.
* Some commands do not work if the command is redirected to PIPE.
* Use ProcessBuilder.Redirect.INHERIT in those cases.
*
* @throws IOException if an I/O error occurs
*/
fun String.execute(
workingDir: File = File("."),
timeoutAmount: Long = 60,
timeoutUnit: TimeUnit = TimeUnit.SECONDS,
timeoutMessage: String? = null,
stdoutRedirectBehavior: Redirect = Redirect.PIPE,
stderrRedirectBehavior: Redirect = Redirect.PIPE,
redactedTokens: List<String> = emptyList(),
throwOnFailure: Boolean = false
): ProcessResult {
var commandToLog = this
redactedTokens.forEach { commandToLog = commandToLog.replace(it, "<redacted>") }
// The command is disabled by default on local run to avoid cluttering people's consoles;
// Only printed on CI or if KSCRIPT_SHELL_ACCESS_DEBUG is set
if (!isMacOs() || !System.getenv("KSCRIPT_SHELL_ACCESS_DEBUG").isNullOrEmpty()) {
System.err.println("Executing command [workingDir: '$workingDir']: $commandToLog")
}
return ProcessBuilder("/bin/sh", "-c", this)
.directory(workingDir)
.redirectOutput(stdoutRedirectBehavior)
.redirectError(stderrRedirectBehavior)
.start()
.apply {
waitFor(timeoutAmount, timeoutUnit)
if (isAlive) {
destroyForcibly()
println("Command timed out after ${timeoutUnit.toSeconds(timeoutAmount)} seconds: '$commandToLog'")
if (
stdoutRedirectBehavior.type() == Redirect.Type.PIPE ||
stderrRedirectBehavior.type() == Redirect.Type.PIPE
) {
println(
listOf(
"Note: Timeout can potentially be due to deadlock when using stdout=PIPE and/or stderr=PIPE",
" and the child process (subpocess running the command) generates enough output to a pipe",
" (~50 KB) such that it blocks waiting for the OS pipe buffer to accept more data.",
"Please consider writing to a stdout/stderr to temp-file instead in such situations!"
).joinToString("")
)
}
timeoutMessage?.let { println(it) }
exitProcess(1)
}
}
.let { process ->
val result = ProcessResult(process.exitValue(), process.inputStream.bufferedReader(), process.errorStream.bufferedReader())
check(!(throwOnFailure && result.failed)) {
"Command failed with exit-code(${process.exitValue()}): '$commandToLog'"
}
result
}
}
fun isMacOs(): Boolean = System.getProperty("os.name").contains("mac", ignoreCase = true)
data class ProcessResult(val exitCode: Int, val stdOut: BufferedReader, val stdErr: BufferedReader) {
val succeeded: Boolean = exitCode == 0
val failed: Boolean = !succeeded
}
fun BufferedReader.print() {
lineSequence().forEach { println(it) }
}
| apache-2.0 | 448e3f92b126235d54663dec7631d407 | 36.405063 | 135 | 0.651777 | 4.974747 | false | false | false | false |
jtransc/jtransc | jtransc-core/src/com/jtransc/ast/dependency/analyzer.kt | 1 | 7670 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.ast.dependency
import com.jtransc.ast.*
import com.jtransc.error.noImpl
// @TODO: Use generic visitor!
object AstDependencyAnalyzer {
enum class Reason { UNKNWON, STATIC }
class Config(
val reason: Reason = Reason.UNKNWON,
val methodHandler: (AstExpr.CALL_BASE, AstDependencyAnalyzerGen) -> Unit = { b, d -> }
)
@JvmStatic fun analyze(program: AstProgram, body: AstBody?, name: String? = null, config: Config): AstReferences {
return AstDependencyAnalyzerGen(program, body, name, config = config).references
}
class AstDependencyAnalyzerGen(program: AstProgram, val body: AstBody?, val name: String? = null, val config: Config) {
val methodHandler = config.methodHandler
val ignoreExploring = hashSetOf<AstRef>()
val allSortedRefs = linkedSetOf<AstRef>()
val allSortedRefsStaticInit = linkedSetOf<AstRef>()
val types = hashSetOf<FqName>()
val fields = hashSetOf<AstFieldRef>()
val methods = hashSetOf<AstMethodRef>()
fun ignoreExploring(ref: AstRef) {
ignoreExploring += ref
}
fun flow() {
if (config.reason == Reason.STATIC) {
//println("Conditional execution in ${body?.methodRef ?: $name}")
}
}
fun ana(method: AstMethodRef) {
if (method in ignoreExploring) return
allSortedRefs.add(method)
methods.add(method)
}
fun ana(field: AstFieldRef) {
if (field in ignoreExploring) return
allSortedRefs.add(field)
fields.add(field)
}
fun ana(type: AstType) {
//if (type in ignoreExploring) return
allSortedRefs.addAll(type.getRefTypes())
types.addAll(type.getRefTypesFqName())
}
fun ana(types: List<AstType>) = types.forEach { ana(it) }
fun ana(expr: AstExpr.Box?) = ana(expr?.value)
fun ana(stm: AstStm.Box?) = ana(stm?.value)
fun ana(expr: AstExpr?) {
if (expr == null) return
when (expr) {
is AstExpr.BaseCast -> {
//is AstExpr.CAST -> {
ana(expr.from)
ana(expr.to)
ana(expr.subject)
}
is AstExpr.NEW_ARRAY -> {
for (c in expr.counts) ana(c)
ana(expr.arrayType)
allSortedRefsStaticInit += expr.arrayType.getRefClasses()
}
is AstExpr.INTARRAY_LITERAL -> {
//for (c in expr.values) ana(c)
ana(expr.arrayType)
}
is AstExpr.OBJECTARRAY_LITERAL -> {
//for (c in expr.values) ana(c)
ana(expr.arrayType)
allSortedRefsStaticInit += AstType.STRING
}
is AstExpr.ARRAY_ACCESS -> {
ana(expr.type)
ana(expr.array)
ana(expr.index)
}
is AstExpr.ARRAY_LENGTH -> {
ana(expr.array)
}
is AstExpr.TERNARY -> {
ana(expr.cond)
ana(expr.etrue)
ana(expr.efalse)
}
is AstExpr.BINOP -> {
ana(expr.left)
ana(expr.right)
}
is AstExpr.CALL_BASE -> {
methodHandler(expr, this)
ana(expr.method.type)
for (arg in expr.args) ana(arg)
ana(expr.method)
if (expr is AstExpr.CALL_STATIC) ana(expr.clazz)
if (expr is AstExpr.CALL_INSTANCE) ana(expr.obj)
if (expr is AstExpr.CALL_SUPER) ana(expr.obj)
allSortedRefsStaticInit += expr.method
}
is AstExpr.CONCAT_STRING -> {
ana(expr.original)
}
is AstExpr.CAUGHT_EXCEPTION -> {
ana(expr.type)
}
is AstExpr.FIELD_INSTANCE_ACCESS -> {
ana(expr.expr)
ana(expr.field)
}
is AstExpr.FIELD_STATIC_ACCESS -> {
ana(expr.clazzName)
ana(expr.field)
allSortedRefsStaticInit += expr.field.containingTypeRef
}
is AstExpr.INSTANCE_OF -> {
ana(expr.expr)
ana(expr.checkType)
}
is AstExpr.UNOP -> ana(expr.right)
is AstExpr.THIS -> ana(expr.type)
is AstExpr.LITERAL -> {
val value = expr.value
when (value) {
is AstType -> {
ana(value)
allSortedRefsStaticInit += value.getRefClasses()
}
//null -> Unit
//is Void, is String -> Unit
//is Boolean, is Byte, is Char, is Short, is Int, is Long -> Unit
//is Float, is Double -> Unit
is AstMethodHandle -> {
ana(value.type)
ana(value.methodRef)
allSortedRefsStaticInit += value.methodRef
}
//else -> invalidOp("Literal: ${expr.value}")
}
}
is AstExpr.LOCAL -> Unit
is AstExpr.TYPED_LOCAL -> Unit
is AstExpr.PARAM -> ana(expr.type)
is AstExpr.INVOKE_DYNAMIC_METHOD -> {
ana(expr.type)
ana(expr.methodInInterfaceRef)
ana(expr.methodToConvertRef)
ana(expr.methodInInterfaceRef.allClassRefs)
ana(expr.methodToConvertRef.allClassRefs)
allSortedRefsStaticInit += expr.methodInInterfaceRef
allSortedRefsStaticInit += expr.methodToConvertRef
}
is AstExpr.NEW_WITH_CONSTRUCTOR -> {
ana(expr.target)
allSortedRefsStaticInit += expr.target
for (arg in expr.args) ana(arg)
ana(AstExpr.CALL_STATIC(expr.constructor, expr.args.unbox, isSpecial = true))
}
//is AstExpr.REF -> ana(expr.expr)
is AstExpr.LITERAL_REFNAME -> {
ana(expr.type)
}
else -> noImpl("Not implemented $expr")
}
}
fun ana(stm: AstStm?) {
if (stm == null) return
when (stm) {
is AstStm.STMS -> for (s in stm.stms) ana(s)
is AstStm.STM_EXPR -> ana(stm.expr)
is AstStm.STM_LABEL -> Unit
is AstStm.MONITOR_ENTER -> ana(stm.expr)
is AstStm.MONITOR_EXIT -> ana(stm.expr)
is AstStm.SET_LOCAL -> ana(stm.expr)
is AstStm.SET_ARRAY -> {
ana(stm.array);
ana(stm.expr); ana(stm.index)
}
is AstStm.SET_ARRAY_LITERALS -> {
ana(stm.array)
for (v in stm.values) ana(v)
}
is AstStm.SET_FIELD_INSTANCE -> {
ana(stm.field); ana(stm.left); ana(stm.expr)
}
is AstStm.SET_FIELD_STATIC -> {
ana(stm.field); ana(stm.expr)
allSortedRefsStaticInit += stm.field.containingTypeRef
}
is AstStm.RETURN -> ana(stm.retval)
is AstStm.RETURN_VOID -> Unit
is AstStm.THROW -> {
ana(stm.exception)
}
is AstStm.CONTINUE -> Unit
is AstStm.BREAK -> Unit
is AstStm.TRY_CATCH -> {
ana(stm.trystm);
ana(stm.catch)
}
is AstStm.LINE -> Unit
is AstStm.NOP -> Unit
is AstStm.SWITCH_GOTO -> {
flow()
ana(stm.subject)
}
is AstStm.SWITCH -> {
flow()
ana(stm.subject); ana(stm.default)
for (catch in stm.cases) ana(catch.second)
}
is AstStm.IF_GOTO -> {
flow()
ana(stm.cond)
}
is AstStm.GOTO -> {
flow()
}
is AstStm.IF -> {
flow()
ana(stm.cond); ana(stm.strue);
}
is AstStm.IF_ELSE -> {
flow()
ana(stm.cond); ana(stm.strue); ana(stm.sfalse)
}
is AstStm.WHILE -> {
flow()
ana(stm.cond); ana(stm.iter)
}
else -> noImpl("Not implemented STM $stm")
}
}
init {
if (body != null) {
for (local in body.locals) ana(local.type)
ana(body.stm)
for (trap in body.traps) ana(trap.exception)
}
}
val references = AstReferences(
program = program,
allSortedRefs = allSortedRefs,
allSortedRefsStaticInit = allSortedRefsStaticInit,
classes = types.map { AstType.REF(it) }.toSet(),
fields = fields.toSet(),
methods = methods.toSet()
)
}
}
| apache-2.0 | 14cf0a519011e11202c21b01d7705ca9 | 25.912281 | 120 | 0.633246 | 3.244501 | false | false | false | false |
premisedata/cameraview | demo/src/main/kotlin/com/otaliastudios/cameraview/demo/MessageView.kt | 1 | 1057 | package com.otaliastudios.cameraview.demo
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
class MessageView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
init {
orientation = VERTICAL
View.inflate(context, R.layout.option_view, this)
val content = findViewById<ViewGroup>(R.id.content)
View.inflate(context, R.layout.spinner_text, content)
}
private val message: TextView = findViewById<ViewGroup>(R.id.content).getChildAt(0) as TextView
private val title: TextView = findViewById(R.id.title)
fun setMessage(message: String) { this.message.text = message }
fun setTitle(title: String) { this.title.text = title }
fun setTitleAndMessage(title: String, message: String) {
setTitle(title)
setMessage(message)
}
}
| apache-2.0 | 5fdd56a4f33825eed84c9400a8c1d548 | 30.088235 | 99 | 0.712394 | 4.24498 | false | false | false | false |
msebire/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/GrCodeReferenceResolver.kt | 1 | 10648 | // 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 org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.psi.*
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.parentOfType
import org.jetbrains.plugins.groovy.lang.psi.GrReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrNewExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrExtendsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrImplementsClause
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.CodeReferenceKind.*
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter
import org.jetbrains.plugins.groovy.lang.psi.impl.explicitTypeArguments
import org.jetbrains.plugins.groovy.lang.psi.util.contexts
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.psi.util.treeWalkUp
import org.jetbrains.plugins.groovy.lang.resolve.imports.GroovyImport
import org.jetbrains.plugins.groovy.lang.resolve.imports.StarImport
import org.jetbrains.plugins.groovy.lang.resolve.imports.StaticImport
import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.CollectElementsProcessor
import org.jetbrains.plugins.groovy.lang.resolve.processors.TypeParameterProcessor
// https://issues.apache.org/jira/browse/GROOVY-8358
// https://issues.apache.org/jira/browse/GROOVY-8359
// https://issues.apache.org/jira/browse/GROOVY-8361
// https://issues.apache.org/jira/browse/GROOVY-8362
// https://issues.apache.org/jira/browse/GROOVY-8364
// https://issues.apache.org/jira/browse/GROOVY-8365
internal object GrCodeReferenceResolver : GroovyResolver<GrCodeReferenceElement> {
override fun resolve(ref: GrCodeReferenceElement, incomplete: Boolean): Collection<GroovyResolveResult> {
return when (ref.kind) {
PACKAGE_REFERENCE -> ref.resolveAsPackageReference()
IMPORT_REFERENCE -> ref.resolveAsImportReference()
REFERENCE -> ref.resolveReference()
}
}
}
private fun GrCodeReferenceElement.resolveAsPackageReference(): Collection<GroovyResolveResult> {
val aPackage = resolvePackageFqn() ?: return emptyList()
return listOf(ElementResolveResult(aPackage))
}
private fun GrCodeReferenceElement.resolveAsImportReference(): Collection<GroovyResolveResult> {
val file = containingFile as? GroovyFile ?: return emptyList()
val statement = parentOfType<GrImportStatement>() ?: return emptyList()
val topLevelReference = statement.importReference ?: return emptyList()
val import = statement.import ?: return emptyList()
if (this === topLevelReference) {
return if (import is StaticImport) {
resolveStaticImportReference(file, import)
}
else {
resolveImportReference(file, import)
}
}
if (parent === topLevelReference && import is StaticImport) {
return resolveImportReference(file, import)
}
if (import is StarImport) {
// reference inside star import
return resolveAsPackageReference()
}
val clazz = import.resolveImport(file) as? PsiClass
val classReference = if (import is StaticImport) topLevelReference.qualifier else topLevelReference
if (clazz == null || classReference == null) return resolveAsPackageReference()
return resolveAsPartOfFqn(classReference, clazz)
}
private fun resolveStaticImportReference(file: GroovyFile, import: StaticImport): Collection<GroovyResolveResult> {
val processor = CollectElementsProcessor()
import.processDeclarations(processor, ResolveState.initial(), file, file)
return processor.results.collapseReflectedMethods().collapseAccessors().map(::ElementResolveResult)
}
private fun resolveImportReference(file: GroovyFile, import: GroovyImport): Collection<GroovyResolveResult> {
val resolved = import.resolveImport(file) ?: return emptyList()
return listOf(ElementResolveResult(resolved))
}
private fun GrCodeReferenceElement.resolveReference(): Collection<GroovyResolveResult> {
val name = referenceName ?: return emptyList()
if (canResolveToTypeParameter()) {
val typeParameters = resolveToTypeParameter(this, name)
if (typeParameters.isNotEmpty()) return typeParameters
}
val (_, outerMostReference) = skipSameTypeParents()
if (outerMostReference !== this) {
val fqnReferencedClass = outerMostReference.resolveClassFqn()
if (fqnReferencedClass != null) {
return resolveAsPartOfFqn(outerMostReference, fqnReferencedClass)
}
}
else if (isQualified) {
val clazz = resolveClassFqn()
if (clazz != null) {
return listOf(ClassProcessor.createResult(clazz, this, ResolveState.initial(), explicitTypeArguments))
}
}
val processor = ClassProcessor(name, this, explicitTypeArguments, isAnnotationReference())
val state = ResolveState.initial()
processClasses(processor, state)
val classes = processor.results
if (classes.isNotEmpty()) return classes
if (canResolveToPackage()) {
val packages = resolveAsPackageReference()
if (packages.isNotEmpty()) return packages
}
return emptyList()
}
private fun GrReferenceElement<*>.canResolveToTypeParameter(): Boolean {
if (isQualified) return false
val parent = parent
return when (parent) {
is GrReferenceElement<*>,
is GrExtendsClause,
is GrImplementsClause,
is GrAnnotation,
is GrImportStatement,
is GrNewExpression,
is GrAnonymousClassDefinition,
is GrCodeReferenceElement -> false
else -> true
}
}
private fun resolveToTypeParameter(place: PsiElement, name: String): Collection<GroovyResolveResult> {
val processor = TypeParameterProcessor(name)
place.treeWalkUp(processor)
return processor.results
}
private fun GrReferenceElement<*>.canResolveToPackage(): Boolean = parent is GrReferenceElement<*>
private fun GrCodeReferenceElement.resolveAsPartOfFqn(reference: GrCodeReferenceElement, clazz: PsiClass): Collection<GroovyResolveResult> {
var currentReference = reference
var currentElement: PsiNamedElement = clazz
while (currentReference !== this) {
currentReference = currentReference.qualifier ?: return emptyList()
val e: PsiNamedElement? = when (currentElement) {
is PsiClass -> currentElement.containingClass ?: currentElement.getPackage()
is PsiPackage -> currentElement.parentPackage
else -> null
}
currentElement = e ?: return emptyList()
}
return listOf(BaseGroovyResolveResult(currentElement, this))
}
private fun PsiClass.getPackage(): PsiPackage? {
val file = containingFile
val name = (file as? PsiClassOwner)?.packageName ?: return null
return JavaPsiFacade.getInstance(file.project).findPackage(name)
}
fun GrCodeReferenceElement.processClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean {
val qualifier = qualifier
if (qualifier == null) {
return processUnqualified(processor, state)
}
else {
return processQualifier(qualifier, processor, state)
}
}
fun PsiElement.processUnqualified(processor: PsiScopeProcessor, state: ResolveState): Boolean {
return processInnerClasses(processor, state) &&
processFileLevelDeclarations(processor, state)
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.resolveNestedClass
*/
private fun PsiElement.processInnerClasses(processor: PsiScopeProcessor, state: ResolveState): Boolean {
val currentClass = getCurrentClass() ?: return true
if (this !is GrCodeReferenceElement || canResolveToInnerClassOfCurrentClass()) {
if (!currentClass.processInnerInHierarchy(processor, state, this)) return false
}
return currentClass.processInnersInOuters(processor, state, this)
}
/**
* @see org.codehaus.groovy.control.ResolveVisitor.resolveFromModule
* @see org.codehaus.groovy.control.ResolveVisitor.resolveFromDefaultImports
*/
private fun PsiElement.processFileLevelDeclarations(processor: PsiScopeProcessor, state: ResolveState): Boolean {
// There is no point in processing imports in dummy files.
val file = containingFile.skipDummies() ?: return true
return file.treeWalkUp(processor, state, this)
}
private fun GrCodeReferenceElement.processQualifier(qualifier: GrCodeReferenceElement,
processor: PsiScopeProcessor,
state: ResolveState): Boolean {
for (result in qualifier.multiResolve(false)) {
val clazz = result.element as? PsiClass ?: continue
if (!clazz.processDeclarations(processor, state.put(PsiSubstitutor.KEY, result.substitutor), null, this)) return false
}
return true
}
private fun GrCodeReferenceElement.canResolveToInnerClassOfCurrentClass(): Boolean {
val (_, outerMostReference) = skipSameTypeParents()
val parent = outerMostReference.getActualParent()
return parent !is GrExtendsClause &&
parent !is GrImplementsClause &&
(parent !is GrAnnotation || parent.classReference != this) // annotation's can't be inner classes of current class
}
/**
* Reference element may be created from stub. In this case containing file will be dummy, and its context will be reference parent
*/
private fun GrCodeReferenceElement.getActualParent(): PsiElement? = containingFile.context ?: parent
/**
* @see org.codehaus.groovy.control.ResolveVisitor.currentClass
*/
private fun PsiElement.getCurrentClass(): GrTypeDefinition? {
for (context in contexts()) {
if (context !is GrTypeDefinition) {
continue
}
else if (context is GrTypeParameter) {
continue
}
else if (context is GrAnonymousClassDefinition && this === context.baseClassReferenceGroovy) {
continue
}
else {
return context
}
}
return null
}
private fun PsiFile?.skipDummies(): PsiFile? {
var file: PsiFile? = this
while (file != null && !file.isPhysical) {
val context = file.context
if (context == null) return file
file = context.containingFile
}
return file
}
| apache-2.0 | 839efefb2945d31d77a5e1e9216aa8d0 | 39.181132 | 140 | 0.766529 | 4.796396 | false | false | false | false |
square/duktape-android | zipline-loader/src/commonTest/kotlin/app/cash/zipline/loader/internal/fetcher/HttpFetcherTest.kt | 1 | 3505 | /*
* Copyright (C) 2022 Block, 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 app.cash.zipline.loader.internal.fetcher
import app.cash.zipline.EventListener
import app.cash.zipline.loader.FakeZiplineHttpClient
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonElement
class HttpFetcherTest {
private val httpFetcher = HttpFetcher(FakeZiplineHttpClient(), EventListener.NONE)
private val json = Json {
prettyPrint = true
}
@Test
fun happyPath() {
val manifestWithRelativeUrls =
"""
|{
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| },
| "./jello.js": {
| "url": "jello.zipline",
| "sha256": "7af37185091e22463ff627686aedfec3528376eb745026fae1d6153688885e73"
| }
| }
|}
""".trimMargin()
val manifestWithBaseUrl = httpFetcher.withBaseUrl(
manifest = json.parseToJsonElement(manifestWithRelativeUrls),
baseUrl = "https://example.com/path/",
)
assertEquals(
"""
|{
| "unsigned": {
| "baseUrl": "https://example.com/path/"
| },
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| },
| "./jello.js": {
| "url": "jello.zipline",
| "sha256": "7af37185091e22463ff627686aedfec3528376eb745026fae1d6153688885e73"
| }
| }
|}
""".trimMargin(),
json.encodeToString(JsonElement.serializer(), manifestWithBaseUrl),
)
}
@Test
fun withBaseUrlRetainsUnknownFields() {
val manifestWithRelativeUrls =
"""
|{
| "unknown string": "hello",
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| }
| }
|}
""".trimMargin()
val manifestWithResolvedUrls = httpFetcher.withBaseUrl(
manifest = json.parseToJsonElement(manifestWithRelativeUrls),
baseUrl = "https://example.com/path/",
)
assertEquals(
"""
|{
| "unsigned": {
| "baseUrl": "https://example.com/path/"
| },
| "unknown string": "hello",
| "modules": {
| "./hello.js": {
| "url": "hello.zipline",
| "sha256": "6bd4baa9f46afa62477fec8c9e95528de7539f036d26fc13885177b32fc0d6ab"
| }
| }
|}
""".trimMargin(),
json.encodeToString(JsonElement.serializer(), manifestWithResolvedUrls),
)
}
}
| apache-2.0 | 504e17d33dfea18f287c3e4dfbf0fb60 | 29.745614 | 95 | 0.580884 | 3.651042 | false | true | false | false |
kannix68/advent_of_code_2016 | day11/src_kotlin/Day11a.kt | 1 | 11501 | import java.security.* // MessageDigest
import java.math.* // BigInteger
import AocBase
/**
* AoC2016 Day11a main class.
* Run with:
*
* ```
* run.sh
* ```
*
* Document with:
* `java -jar dokka-fatjar.jar day13a.kt -format html -module "aoc16 day11a" -nodeprecated`
*/
class Day11a : AocBase() {
val maxround = 256
val seen: MutableSet<String>
init {
seen = mutableSetOf(""); seen.clear()
LOGLEVEL = 0
}
val TESTSTR = """
The first floor contains a elerium generator, a elerium-compatible microchip, a dilithium generator, a dilithium-compatible microchip, a strontium generator, a strontium-compatible microchip, a plutonium generator, and a plutonium-compatible microchip.
The second floor contains a thulium generator, a ruthenium generator, a ruthenium-compatible microchip, a curium generator, and a curium-compatible microchip.
The third floor contains a thulium-compatible microchip.
The fourth floor contains nothing relevant.
""".trimIndent()
/*
val TESTSTR = """
The first floor contains a hydrogen-compatible microchip.
The second floor contains nothing relevant.
The third floor contains a hydrogen generator.
The fourth floor contains a lithium-compatible microchip and a lithium generator.
""".trimIndent()
val TESTSTR = """
The first floor contains a hydrogen-compatible microchip and a lithium-compatible microchip.
The second floor contains a hydrogen generator.
The third floor contains a lithium generator.
The fourth floor contains nothing relevant.
""".trimIndent()
//!! PART 1:
val TESTSTR = """
The first floor contains a strontium generator, a strontium-compatible microchip, a plutonium generator, and a plutonium-compatible microchip.
The second floor contains a thulium generator, a ruthenium generator, a ruthenium-compatible microchip, a curium generator, and a curium-compatible microchip.
The third floor contains a thulium-compatible microchip.
The fourth floor contains nothing relevant.
""".trimIndent()
*/
companion object {
/**
* Factory create function.
*/
fun create(): Day11a = Day11a()
/**
* PSVM main entry point.
*/
@JvmStatic fun main(args: Array<String>) {
println("Starting")
val o = create()
o.process()
}
}
//**** problem domain
/**
* Get Elevator floor number stored in world.
*/
private fun elevatorAt(world: MutableList<MutableSet<String>>): Int {
return world[4].toList().get(0).toInt()
}
/**
* Return list of directions, 1; -1 oder 1, -1.
*/
private fun elevatorDirsOk(oldFloorNum: Int): List<Int> {
if (oldFloorNum == 1) {
return listOf<Int>(1)
} else if (oldFloorNum == 4) {
return listOf<Int>(-1)
} else {
return listOf<Int>(1, -1)
}
}
/**
* Returns Combinations (like Permutations, but order does not count)
* of 2 and 1 items of the given set.
*/
private fun get2Permuts(fset: MutableSet<String>): MutableList<List<String>> {
val ret = mutableListOf(listOf("")); ret.clear()
val aset = fset.sorted()
if (aset.size > 2) {
for (idx in 0..aset.size-1) { // permutate-2
for (nxidx in idx+1..aset.size-1) { // permutate-2
//println("permut=($idx,$nxidx)")
ret.add(listOf(aset[idx], aset[nxidx]))
}
}
for (idx in 0..aset.size-1) { // permutate-1
ret.add(listOf(aset[idx]))
}
} else if (aset.size == 2) {
ret.add(listOf(aset[0], aset[1]))
ret.add(listOf(aset[0]))
ret.add(listOf(aset[1]))
} else if (fset.size == 1) {
ret.add(listOf(aset[0]))
} else {
// nothing to add
}
tracelog("getPermuts($aset) => $ret")
return ret
}
private fun getElevatorPermuts(world: MutableList<MutableSet<String>>): MutableList<List<String>> {
val currentFloor = elevatorAt(world)
//elevatorDirsOk(currentFloor).forEach { edir ->
// tracelog("possible direction $edir; currently at $currentFloor")
//}
val fset = world[currentFloor-1]
//deblog("fset.size=${fset.size} fset=$fset")
return get2Permuts(fset)
}
private fun checkPayloadFloor(perm: List<String>, targetFloor: Int, world: MutableList<MutableSet<String>>): Boolean {
val targetfset = world[targetFloor - 1]
val micros = perm.filter { it.endsWith("M") }
if (micros.size > 0) {
val generators = targetfset.union(perm).filter { it.endsWith("G") }
micros.forEach { micro ->
val micGen = micro[0] + "G"
if (generators.size > 0 && !generators.contains(micGen)) {
tracelog("$micro fried on payload=$perm to floor#$targetFloor :: $targetfset. no $micGen")
return false
}
}
}
return true
}
/**
* Generate world from a multiline string.
*/
private fun generateWorld(mlstr: String): MutableList<MutableSet<String>> {
// "The second floor contains a hydrogen generator."
val rx1 = Regex("""^The (.*) floor contains (.*)\.$""")
val rx2 = Regex("""a ([a-z].*?).(?:compatible )?(microchip|generator)""")
val world = mutableListOf(mutableSetOf("")); world.clear()
mlstr.split("\n").forEach { line ->
val mset = mutableSetOf(""); mset.clear()
//tracelog("line=$line")
val mr1 = rx1.find(line)
if (mr1 == null) {
throw RuntimeException("unparseable line:: $line")
}
val (floorstr, rest) = mr1.destructured
//tracelog("floorstr=$floorstr, rest=$rest")
if (!rest.startsWith("nothing")) {
rx2.findAll(rest).forEach { mr2 ->
val (elem, device) = mr2.destructured
val marker: String = "${elem[0]}${device[0]}".toUpperCase()
//infolog("add marker $marker")
mset.add(marker)
}
}
world.add(mset)
}
world.add(mutableSetOf(1.toString()))
infolog("world=${signat(world)}")
//infolog("floor#1=${world[0]}")
assertmsg(elevatorAt(world) == 1, "elevator at creation is at floor #1")
return world
}
private fun printWorld(world: MutableList<MutableSet<String>>, title: String = "") {
val allset = mutableSetOf(""); allset.clear()
val cols = mutableListOf(""); cols.clear()
world.forEachIndexed { idx, floor ->
if (idx < 4) {
floor.forEach { allset.add(it) }
}
}
val items = allset.sorted()
var s = "Wl>|" //">Wrld |"
s += "El|"
items.forEach {
s += it + "|"
cols.add(it)
}
if (title != "") {
s += " :: >$title<"
}
s += " :: world-id=" + Integer.toHexString(world.hashCode())
s += "\n"
for (f in 4 downTo 1) {
s += " F#$f: ;"
if (f == elevatorAt(world)) {
s += "El;"
} else {
s += "__;"
}
val fset = world[f-1]
items.forEach {
if (fset.contains(it)) {
s += "$it;"
} else {
s +="..;"
}
}
if (f==1) {
s += " :: signat=${signat(world)}"
}
s += "\n"
}
infolog("$s") // "\n$s"
}
/**
* Process problem domain.
*/
fun process(): Boolean {
infolog(":process() started.")
//infolog("TESTSTR =>>$TESTSTR<<.")
assertmsg(TESTSTR.length > 0, "found TESTSTR")
val mlstr = TESTSTR
val world = generateWorld(mlstr)
seen.add(signat(world))
printWorld(world, "initial-world")
var round = 0
var stack: MutableList<MutableList<MutableSet<String>>>
var nextstack = mutableListOf(world)
var stackCounts = mutableListOf(0); stackCounts.clear()
var lastWorlds = 1
var lastMoves = 0
var invalidNum = 0
var rejectedNum = 0
stackCounts.add(nextstack.size)
val starttm = System.currentTimeMillis()
var lasttm = starttm
var tooktm: Long
while (round < maxround) {
round += 1
tooktm = System.currentTimeMillis()
stack = copyMListOfMListOfMSet(nextstack)
nextstack.clear()
//infolog("start-round#$round; stack=$stack; next-stack:$nextstack")
infolog("START-ROUND #$round; stack-count=${stack.size}, seen-count=${seen.size}; invalid-ct=$invalidNum, rejected=$rejectedNum, last-TM=${tooktm-lasttm}, sum-TM=${(tooktm-starttm)/1000.0}")
lasttm = tooktm
infolog("stackCounts=" + stackCounts.joinToString(","))
deblog(" last-world=$lastWorlds, last-moves=$lastMoves")
lastWorlds = 0; lastMoves = 0
//if (stack.size == 1) {
// printWorld(stack[0], "stacked1")
//}
stack.forEach { baseworld ->
lastWorlds += 1
val currentFloor = elevatorAt(baseworld)
val permuts = getElevatorPermuts(baseworld)
elevatorDirsOk(currentFloor).forEach { edir ->
tracelog("possible direction $edir; currently at $currentFloor; permuts=$permuts")
val targetFloor = currentFloor + edir
permuts.forEach { perm ->
if (checkPayloadFloor(perm, targetFloor, baseworld)){
deblog("ok-move to-flr=$targetFloor from-flr=$currentFloor, perm=$perm to=${baseworld[targetFloor-1]}")
val newworld = compute_world(edir, perm, baseworld)
val nwsig = signat(newworld)
if (nwsig.contains(":;;;")) {
printWorld(newworld, "solution-world")
tooktm = System.currentTimeMillis()
infolog("sum-TM=${(tooktm-starttm)/1000.0}")
throw RuntimeException("finished-world found! at round $round")
}
if (!seen.contains(nwsig)) {
lastMoves += 1
seen.add(nwsig)
//printWorld(newworld, title="newworld :p")
nextstack.add(newworld)
//!!!deblog("OK added next-move newworld-sig=$nwsig");
//printWorld(newworld, "stacked-next-world")
} else {
//!!!deblog("rejected seen world $nwsig")
rejectedNum += 1
}
} else {
//!!!deblog("invalid move to-flr=$targetFloor from-flr=$currentFloor, with=$perm to=${baseworld[targetFloor-1]}")
invalidNum += 1
}
}
}
}
stackCounts.add(nextstack.size)
}
return false
}
private fun signat(world: MutableList<MutableSet<String>>): String {
var sign = ""
world.forEachIndexed { idx, floor ->
if (idx == 4) {
sign = floor.elementAt(0).toString() + ":" + sign
} else if (idx == 3) {
sign += floor.sorted().joinToString(",") + "."
} else {
sign += floor.sorted().joinToString(",") + ";"
}
}
//tracelog("signat(wrld)=$sign from ${world}")
return sign
}
private fun compute_world(edir: Int, perm: List<String>, baseWorld: MutableList<MutableSet<String>>): MutableList<MutableSet<String>> {
val newWorld = copyMListOfMSet(baseWorld)
//printWorld(baseWorld, "oldworld :compt1");
val currentFloor = elevatorAt(newWorld)
val targetFloor = currentFloor + edir
tracelog("compute ok: to-flr=$targetFloor from-flr=$currentFloor, perm=$perm to-flr-items=${baseWorld[targetFloor-1]}")
val elevInfo = newWorld[4]; elevInfo.clear(); elevInfo.add(targetFloor.toString()) // set Elevator floor!
val basefset = newWorld[currentFloor - 1]
perm.forEach { basefset.remove(it) }
val targetfset = newWorld[targetFloor - 1]
perm.forEach { targetfset.add(it) }
//printWorld(baseWorld, "oldworld :compt2")
//printWorld(newWorld, "newworld")
return newWorld
}
}
| mit | be1cd3f8e6963162c3caff3db71d8b1a | 33.026627 | 254 | 0.604295 | 3.837504 | false | false | false | false |
infinum/android_dbinspector | dbinspector/src/main/kotlin/com/infinum/dbinspector/domain/history/interactors/RemoveExecutionInteractor.kt | 1 | 1116 | package com.infinum.dbinspector.domain.history.interactors
import com.infinum.dbinspector.data.Sources
import com.infinum.dbinspector.data.models.local.proto.input.HistoryTask
import com.infinum.dbinspector.data.models.local.proto.output.HistoryEntity
import com.infinum.dbinspector.domain.Interactors
internal class RemoveExecutionInteractor(
private val dataStore: Sources.Local.History
) : Interactors.RemoveExecution {
override suspend fun invoke(input: HistoryTask) {
input.execution?.let { execution ->
dataStore.store().updateData { value: HistoryEntity ->
value.toBuilder()
.removeExecutions(
value.executionsList.indexOfFirst {
it.databasePath == execution.databasePath &&
it.execution == execution.execution &&
it.timestamp == execution.timestamp &&
it.success == execution.success
}
)
.build()
}
}
}
}
| apache-2.0 | 107dff75e63636decff790c01e281692 | 38.857143 | 75 | 0.58871 | 5.552239 | false | false | false | false |
akvo/akvo-flow-mobile | domain/src/main/java/org/akvo/flow/domain/interactor/DownloadDataPoints.kt | 1 | 3117 | /*
* Copyright (C) 2017-2018 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow 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.
*
* Akvo Flow 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 Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.akvo.flow.domain.interactor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.akvo.flow.domain.entity.DownloadResult
import org.akvo.flow.domain.exception.AssignmentRequiredException
import org.akvo.flow.domain.repository.DataPointRepository
import org.akvo.flow.domain.repository.FormRepository
import org.akvo.flow.domain.util.ConnectivityStateManager
import timber.log.Timber
import javax.inject.Inject
class DownloadDataPoints @Inject constructor(
private val dataPointRepository: DataPointRepository,
private val formRepository: FormRepository,
private val connectivityStateManager: ConnectivityStateManager
) {
suspend fun execute(parameters: Map<String, Any>): DownloadResult {
if (parameters[KEY_SURVEY_ID] == null) {
throw IllegalArgumentException("Missing surveyId or registrationFormId")
}
return if (!connectivityStateManager.isConnectionAvailable) {
DownloadResult(
DownloadResult.ResultCode.ERROR_NO_NETWORK,
0
)
} else {
syncDataPoints(parameters)
}
}
private suspend fun syncDataPoints(parameters: Map<String, Any>): DownloadResult {
return withContext(Dispatchers.IO) {
try {
val surveyId = (parameters[KEY_SURVEY_ID] as Long?)!!
val assignedForms = formRepository.getForms(surveyId)
val assignedFormIds = mutableListOf<String>()
for (f in assignedForms) {
assignedFormIds.add(f.formId)
}
val downloadDataPoints =
dataPointRepository.downloadDataPoints(surveyId, assignedFormIds)
DownloadResult(DownloadResult.ResultCode.SUCCESS, downloadDataPoints)
} catch (ex: AssignmentRequiredException) {
Timber.e(ex)
DownloadResult(
DownloadResult.ResultCode.ERROR_ASSIGNMENT_MISSING,
0
)
} catch (ex: Exception) {
Timber.e(ex)
DownloadResult(
DownloadResult.ResultCode.ERROR_OTHER,
0
)
}
}
}
companion object {
const val KEY_SURVEY_ID = "survey_id"
}
}
| gpl-3.0 | 689b85dcb6c7dbcd573550adf750916b | 37.012195 | 86 | 0.652871 | 4.955485 | false | false | false | false |
android/topeka | quiz/src/main/java/com/google/samples/apps/topeka/widget/quiz/FillTwoBlanksQuizView.kt | 1 | 2908 | /*
* 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.view.inputmethod.EditorInfo
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.LinearLayout
import com.google.samples.apps.topeka.quiz.R
import com.google.samples.apps.topeka.model.Category
import com.google.samples.apps.topeka.model.quiz.FillTwoBlanksQuiz
@SuppressLint("ViewConstructor")
class FillTwoBlanksQuizView(
context: Context,
category: Category,
quiz: FillTwoBlanksQuiz
) : TextInputQuizView<FillTwoBlanksQuiz>(context, category, quiz) {
private val KEY_ANSWER_ONE = "ANSWER_ONE"
private val KEY_ANSWER_TWO = "ANSWER_TWO"
private var answerOne: EditText? = null
private var answerTwo: EditText? = null
override fun createQuizContentView(): View {
val layout = LinearLayout(context)
answerOne = createEditText().apply {
imeOptions = EditorInfo.IME_ACTION_NEXT
}
answerTwo = createEditText().apply {
id = com.google.samples.apps.topeka.base.R.id.quiz_edit_text_two
}
layout.orientation = LinearLayout.VERTICAL
addEditText(layout, answerOne)
addEditText(layout, answerTwo)
return layout
}
override var userInput: Bundle
get() {
return Bundle().apply {
putString(KEY_ANSWER_ONE, answerOne?.text?.toString())
putString(KEY_ANSWER_TWO, answerTwo?.text?.toString())
}
}
set(savedInput) {
answerOne?.setText(savedInput.getString(KEY_ANSWER_ONE))
answerTwo?.setText(savedInput.getString(KEY_ANSWER_TWO))
}
private fun addEditText(layout: LinearLayout, editText: EditText?) {
layout.addView(editText, LinearLayout
.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, 0, 1f))
}
override val isAnswerCorrect: Boolean
get() {
val partOne = getAnswerFrom(answerOne)
val partTwo = getAnswerFrom(answerTwo)
return quiz.isAnswerCorrect(arrayOf(partOne, partTwo))
}
private fun getAnswerFrom(view: EditText?) = view?.text.toString()
}
| apache-2.0 | 626d80544164e9fdb30f858d42ee89c4 | 33.619048 | 76 | 0.690165 | 4.432927 | false | false | false | false |
andersonlucasg3/SpriteKit-Android | SpriteKitLib/src/main/java/br/com/insanitech/spritekit/easing/Quint.kt | 1 | 871 | package br.com.insanitech.spritekit.easing
object Quint {
fun easeIn(t: Float, b: Float, c: Float, d: Float): Float {
var t = t
val tLambda = { a: Float -> Float
t = a
t
}
return c * (tLambda(t / d)) * t * t * t * t + b
}
fun easeOut(t: Float, b: Float, c: Float, d: Float): Float {
var t = t
val tLambda = { a: Float -> Float
t = a
t
}
return c * ((tLambda(t / d - 1)) * t * t * t * t + 1) + b
}
fun easeInOut(t: Float, b: Float, c: Float, d: Float): Float {
var t = t
val tLambda = { a: Float -> Float
t = a
t
}
return if ((tLambda(t / d / 2)) < 1) c / 2 * t * t * t * t * t + b else c / 2 * ((tLambda(t - 2f)) * t * t * t * t + 2) + b
}
}
| bsd-3-clause | c1e6d40878a009af5c5d8efde875844e | 25.21875 | 131 | 0.397245 | 3.178832 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/command/argument/ArgumentTypes.kt | 1 | 2839 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.command.argument
object ArgumentTypes {
val BOOL = argumentTypeOf("brigadier:bool")
val GAME_PROFILE = argumentTypeOf("minecraft:game_profile")
val BLOCK_POS = argumentTypeOf("minecraft:block_pos")
val VEC3 = argumentTypeOf("minecraft:vec3")
val VEC2 = argumentTypeOf("minecraft:vec2")
val BLOCK = argumentTypeOf("minecraft:block")
val ITEM = argumentTypeOf("minecraft:item")
val COLOR = argumentTypeOf("minecraft:color")
val COMPONENT = argumentTypeOf("minecraft:component")
val MESSAGE = argumentTypeOf("minecraft:message")
val NBT = argumentTypeOf("minecraft:nbt")
val NBT_PATH = argumentTypeOf("minecraft:nbt_path")
val OBJECTIVE = argumentTypeOf("minecraft:objective")
val OBJECTIVE_CRITERIA = argumentTypeOf("minecraft:objective_criteria")
val OPERATION = argumentTypeOf("minecraft:operation")
val PARTICLE = argumentTypeOf("minecraft:particle")
val ROTATION = argumentTypeOf("minecraft:rotation")
val SCOREBOARD_SLOT = argumentTypeOf("minecraft:scoreboard_slot")
val SWIZZLE = argumentTypeOf("minecraft:swizzle")
val TEAM = argumentTypeOf("minecraft:team")
val ITEM_SLOT = argumentTypeOf("minecraft:item_slot")
val RESOURCE_LOCATION = argumentTypeOf("minecraft:resource_location")
val MOB_EFFECT = argumentTypeOf("minecraft:mob_effect")
val DOUBLE = numberArgumentTypeOf<DoubleArgument, Double>("brigadier:double") { writeDouble(it) }
val FLOAT = numberArgumentTypeOf<FloatArgument, Float>("brigadier:float") { writeFloat(it) }
val INTEGER = numberArgumentTypeOf<IntArgument, Int>("brigadier:integer") { writeInt(it) }
val LONG = numberArgumentTypeOf<LongArgument, Long>("brigadier:long") { writeLong(it) }
@JvmField
val STRING = argumentTypeOf<StringArgument>("brigadier:string") { buf, message ->
buf.writeVarInt(message.type.ordinal)
}
val ENTITY = argumentTypeOf<EntityArgument>("minecraft:entity") { buf, message ->
var flags = 0
if (!message.allowMultipleEntities)
flags += 0x1
if (!message.allowOnlyPlayers)
flags += 0x2
buf.writeByte(flags.toByte())
}
val SCORE_HOLDER = argumentTypeOf<ScoreHolderArgument>("minecraft:score_holder") { buf, message ->
var flags = 0
if (message.hasUnknownFlag)
flags += 0x1
if (message.allowMultipleEntities)
flags += 0x2
buf.writeByte(flags.toByte())
}
}
| mit | d28c72e6955c10b90c867f70ce89664e | 42.015152 | 102 | 0.702008 | 4.422118 | false | false | false | false |
Kotlin/kotlinx.serialization | formats/json-tests/commonTest/src/kotlinx/serialization/json/JsonUnionEnumTest.kt | 1 | 842 | /*
* Copyright 2017-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json
import kotlinx.serialization.*
import kotlin.test.Test
import kotlin.test.assertEquals
class JsonUnionEnumTest : JsonTestBase() {
enum class SomeEnum { ALPHA, BETA, GAMMA }
@Serializable
data class WithUnions(val s: String,
val e: SomeEnum = SomeEnum.ALPHA,
val i: Int = 42)
@Test
fun testEnum() = parametrizedTest { jsonTestingMode ->
val data = WithUnions("foo", SomeEnum.BETA)
val json = default.encodeToString(WithUnions.serializer(), data, jsonTestingMode)
val restored = default.decodeFromString(WithUnions.serializer(), json, jsonTestingMode)
assertEquals(data, restored)
}
}
| apache-2.0 | ca2d82b3a9cdb9bb2b437b18256c0546 | 30.185185 | 102 | 0.671021 | 4.502674 | false | true | false | false |
Kotlin/kotlinx.serialization | formats/protobuf/commonTest/src/kotlinx/serialization/protobuf/ProtobufPrimitiveWrappersTest.kt | 1 | 2133 | /*
* Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.protobuf
import kotlinx.serialization.*
import kotlin.test.*
/*
* TODO improve these tests:
* * All primitive types
* * All nullable types
* * Built-in types (TBD)
* * Primitives nullability
*/
class ProtobufPrimitiveWrappersTest {
@Test
fun testSignedInteger() {
assertSerializedToBinaryAndRestored(TestInt(-150), TestInt.serializer(), ProtoBuf, hexResultToCheck = "08AB02")
}
@Test
fun testIntList() {
assertSerializedToBinaryAndRestored(
TestList(listOf(1, 2, 3)),
TestList.serializer(), ProtoBuf, hexResultToCheck = "080108020803"
)
}
@Test
fun testString() {
assertSerializedToBinaryAndRestored(
TestString("testing"),
TestString.serializer(), ProtoBuf, hexResultToCheck = "120774657374696E67"
)
}
@Test
fun testTwiceNested() {
assertSerializedToBinaryAndRestored(
TestInner(TestInt(-150)),
TestInner.serializer(), ProtoBuf, hexResultToCheck = "1A0308AB02"
)
}
@Test
fun testMixedTags() {
assertSerializedToBinaryAndRestored(
TestComplex(42, "testing"),
TestComplex.serializer(), ProtoBuf, hexResultToCheck = "D0022A120774657374696E67"
)
}
@Test
fun testDefaultPrimitiveValues() {
assertSerializedToBinaryAndRestored(TestInt(0), TestInt.serializer(), ProtoBuf, hexResultToCheck = "0800")
assertSerializedToBinaryAndRestored(TestList(listOf()), TestList.serializer(), ProtoBuf, hexResultToCheck = "")
assertSerializedToBinaryAndRestored(
TestString(""),
TestString.serializer(), ProtoBuf, hexResultToCheck = "1200"
)
}
@Test
fun testFixedIntWithLong() {
assertSerializedToBinaryAndRestored(
TestNumbers(100500, Long.MAX_VALUE),
TestNumbers.serializer(), ProtoBuf, hexResultToCheck = "0D9488010010FFFFFFFFFFFFFFFF7F"
)
}
}
| apache-2.0 | bc3b36843cf9515c97d4a54745040cd1 | 28.625 | 119 | 0.65354 | 4.960465 | false | true | false | false |
k0kubun/github-ranking | worker/src/main/kotlin/com/github/k0kubun/gitstar_ranking/db/PaginatedUsers.kt | 2 | 1044 | package com.github.k0kubun.gitstar_ranking.db
import com.github.k0kubun.gitstar_ranking.core.StarsCursor
import com.github.k0kubun.gitstar_ranking.core.User
import org.jooq.DSLContext
private const val PAGE_SIZE = 5000
// This class does cursor-based-pagination for users order by stargazers_count DESC.
class PaginatedUsers(private val database: DSLContext) {
private var lastMinStars: Long? = null
private var lastMinId: Long? = null
fun nextUsers(): List<User> {
val users = if (lastMinId != null && lastMinStars != null) {
UserQuery(database).orderByStarsDesc(
limit = PAGE_SIZE,
after = StarsCursor(id = lastMinId!!, stars = lastMinStars!!),
)
} else {
UserQuery(database).orderByStarsDesc(limit = PAGE_SIZE)
}
if (users.isEmpty()) {
return users
}
val lastUser = users[users.size - 1]
lastMinStars = lastUser.stargazersCount
lastMinId = lastUser.id
return users
}
}
| mit | f9627a8d9371803379190e98f6339a44 | 32.677419 | 84 | 0.64272 | 4.142857 | false | false | false | false |
debop/debop4k | debop4k-timeperiod/src/main/kotlin/debop4k/timeperiod/timeranges/HourRangeCollection.kt | 1 | 2365 | /*
* Copyright (c) 2016. Sunghyouk Bae <sunghyouk.bae@gmail.com>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package debop4k.timeperiod.timeranges
import debop4k.core.kodatimes.asDateTime
import debop4k.core.kodatimes.now
import debop4k.timeperiod.DefaultTimeCalendar
import debop4k.timeperiod.ITimeCalendar
import debop4k.timeperiod.utils.hourRangeSequence
import org.joda.time.DateTime
/**
* Created by debop
*/
open class HourRangeCollection @JvmOverloads constructor(startTime: DateTime = now(),
hourCount: Int = 1,
calendar: ITimeCalendar = DefaultTimeCalendar)
: HourTimeRange(startTime, hourCount, calendar) {
@JvmOverloads
constructor(year: Int,
monthOfYear: Int,
dayOfMonth: Int,
hour: Int,
hourCount: Int = 1, calendar: ITimeCalendar = DefaultTimeCalendar)
: this(asDateTime(year, monthOfYear, dayOfMonth, hour), hourCount, calendar)
fun hourSequence(): Sequence<HourRange> {
return hourRangeSequence(startHourOfStart, hourCount, calendar)
}
fun hours(): List<HourRange> {
return hourSequence().toList()
}
companion object {
@JvmStatic
@JvmOverloads
fun of(startTime: DateTime = now(),
hourCount: Int = 1,
calendar: ITimeCalendar = DefaultTimeCalendar): HourRangeCollection {
return HourRangeCollection(startTime, hourCount, calendar)
}
@JvmStatic
@JvmOverloads
fun of(year: Int,
monthOfYear: Int,
dayOfMonth: Int,
hour: Int,
hourCount: Int = 1,
calendar: ITimeCalendar = DefaultTimeCalendar): HourRangeCollection {
return HourRangeCollection(year, monthOfYear, dayOfMonth, hour, hourCount, calendar)
}
}
} | apache-2.0 | 3ce599d39b219060423eecb010356343 | 32.323944 | 103 | 0.672304 | 4.748996 | false | false | false | false |
Geobert/radis | app/src/main/kotlin/fr/geobert/radis/tools/PauseHandler.kt | 1 | 1797 | package fr.geobert.radis.tools
import android.app.Activity
import android.os.Handler
import android.os.Message
import java.util.*
/**
* Message Handler class that supports buffering up of messages when the activity is paused i.e. in the background.
*/
public abstract class PauseHandler : Handler() {
/**
* Message Queue Buffer
*/
private val messageQueueBuffer = Collections.synchronizedList(ArrayList<Message>())
/**
* Flag indicating the pause state
*/
private var activity: Activity? = null
/**
* Resume the handler.
*/
@Synchronized public fun resume(activity: Activity) {
this.activity = activity
while (messageQueueBuffer.size > 0) {
val msg = messageQueueBuffer.get(0)
messageQueueBuffer.removeAt(0)
sendMessage(msg)
}
}
/**
* Pause the handler.
*/
@Synchronized public fun pause() {
activity = null
}
/**
* Store the message if we have been paused, otherwise handle it now.
* @param msg Message to handle.
*/
@Synchronized override fun handleMessage(msg: Message) {
val act = activity
if (act == null) {
val msgCopy = Message()
msgCopy.copyFrom(msg)
messageQueueBuffer.add(msgCopy)
} else {
processMessage(act, msg)
}
}
/**
* Notification message to be processed. This will either be directly from
* handleMessage or played back from a saved message when the activity was
* paused.
* @param act Activity owning this Handler that isn't currently paused.
* *
* @param message Message to be handled
*/
protected abstract fun processMessage(act: Activity, message: Message)
}
| gpl-2.0 | 712dc203b004076c376ca72f8befa80a | 24.671429 | 115 | 0.621035 | 4.667532 | false | false | false | false |
Mauin/detekt | detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/Entity.kt | 2 | 775 | package io.gitlab.arturbosch.detekt.api
import org.jetbrains.kotlin.com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtElement
/**
* Stores information about a specific code fragment.
*
* @author Artur Bosch
*/
data class Entity(val name: String,
val className: String,
val signature: String,
val location: Location,
val ktElement: KtElement? = null) : Compactable {
override fun compact() = "[$name] at ${location.compact()}"
companion object {
fun from(element: PsiElement, offset: Int = 0): Entity {
val name = element.searchName()
val signature = element.buildFullSignature()
val clazz = element.searchClass()
return Entity(name, clazz, signature, Location.from(element, offset), element as? KtElement)
}
}
}
| apache-2.0 | 4ea2b8988fb502a24a85085a0b129a97 | 27.703704 | 95 | 0.709677 | 3.836634 | false | false | false | false |
mopsalarm/Pr0 | app/src/main/java/kotterknife/Kotterknife.kt | 1 | 865 | package kotterknife
import android.app.Activity
import android.view.View
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
fun <V : View> Activity.bindView(id: Int): ReadOnlyProperty<Activity, V> = Lazy { _: Any?, desc ->
findViewById<V>(id) ?: viewNotFound(id, desc)
}
private fun viewNotFound(id: Int, desc: KProperty<*>): Nothing =
throw IllegalStateException("View ID $id for '${desc.name}' not found.")
class Lazy<T, V>(private val initializer: (T, KProperty<*>) -> V) : ReadOnlyProperty<T, V> {
private var value: Any? = EMPTY
override fun getValue(thisRef: T, property: KProperty<*>): V {
if (value == EMPTY) {
value = initializer(thisRef, property)
}
@Suppress("UNCHECKED_CAST")
return value as V
}
companion object {
private object EMPTY
}
} | mit | e0154a8ad55d19e4a211a5cdca9485c9 | 27.866667 | 98 | 0.655491 | 4.138756 | false | false | false | false |
if710/if710.github.io | 2019-08-28/Threads/app/src/main/java/br/ufpe/cin/android/threads/ThreadViewPost.kt | 1 | 1256 | package br.ufpe.cin.android.threads
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.widget.Toast
import kotlinx.android.synthetic.main.threads.*
class ThreadViewPost : Activity() {
private var mBitmap: Bitmap? = null
private val mDelay = 5000
internal var toasts = 0
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.threads)
loadButton.setOnClickListener { loadIcon() }
otherButton.setOnClickListener {
toasts++
contadorToasts.text = getString(R.string.contador_de_toasts) + toasts
Toast.makeText(applicationContext, "Estou trabalhando... ($toasts)", Toast.LENGTH_SHORT).show()
}
}
private fun loadIcon() {
Thread(Runnable {
try {
Thread.sleep(mDelay.toLong())
} catch (e: InterruptedException) {
e.printStackTrace()
}
mBitmap = BitmapFactory.decodeResource(resources,
R.drawable.painter)
imageView.post { imageView.setImageBitmap(mBitmap) }
}).start()
}
}
| mit | db07b7ab2f5487a62e6e2773b8960f47 | 28.904762 | 107 | 0.642516 | 4.70412 | false | false | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/fragments/relprofile/RelationshipProfilePresenter.kt | 1 | 5546 | package com.duopoints.android.fragments.relprofile
import com.duopoints.android.Calls
import com.duopoints.android.fragments.base.BasePresenter
import com.duopoints.android.logistics.SessionManager
import com.duopoints.android.rest.models.composites.CompositeRelationship
import com.duopoints.android.rest.models.enums.rel.RelationshipBreakupRequestStatus
import com.duopoints.android.rest.models.post.NewRelationshipBreakupRequest
import com.duopoints.android.utils.ReactiveUtils
import com.duopoints.android.utils.logging.LogLevel
import com.duopoints.android.utils.logging.log
import io.reactivex.Observable
import io.reactivex.functions.Consumer
import io.reactivex.functions.Function3
import org.joda.time.DateTime
import org.joda.time.DateTimeZone
import java.util.*
class RelationshipProfilePresenter(relationshipProfileFrag: RelationshipProfileFrag) : BasePresenter<RelationshipProfileFrag>(relationshipProfileFrag) {
fun observeNewPoints() {
Observable.combineLatest(
SessionManager.observePointsGivenWithDefault(),
SessionManager.observeUserRelationshipWithDefault(),
SessionManager.observeUserRelationshipBreakupRequestWithDefault(),
Function3<Any?, Any?, Any?, Boolean> { _, _, _ -> true })
.skip(1)
.compose(ReactiveUtils.commonObservableTransformation(view, true))
.subscribe({ view.reloadRelationshipData() }, { it.printStackTrace() })
}
fun processRelationship(relationship: CompositeRelationship) {
if (SessionManager.getUserRelationship()?.relationshipUuid == relationship.relationshipUuid) {
// Get any BreakupRequest that might exist
val breakupRequest = SessionManager.getUserRelationshipBreakupRequests()
view.showingOwnRelationship(breakupRequest)
breakupRequest?.let {
val requestedByCurrentUser = SessionManager.getUser().userUuid == it.userUuid
// Get the "must wait until" Datetime
val waitUntil = DateTime(it.relationshipBreakupRequestWaitUntil, DateTimeZone.UTC)
// If the time NOW is passed the Cool-Off period
if (DateTime.now(DateTimeZone.UTC).isAfter(waitUntil)) {
if (requestedByCurrentUser) {
view.requestedUserCoolOffWaitPassed()
} else {
view.partnerCoolOffWaitPassed()
}
} else {
if (requestedByCurrentUser) {
view.requestedUserCoolOffNotWaitPassed(waitUntil)
} else {
view.partnerCoolOffNotWaitPassed(waitUntil)
}
}
}
}
}
fun loadFullRelationshipData(relationshipUuid: UUID) {
Calls.relationshipService.getFullRelationshipData(relationshipUuid)
.compose(ReactiveUtils.commonMaybeTransformation(view, true))
.subscribe(Consumer(view::relationshipLoaded), ReactiveUtils.notNotFound(view::errorLoadingRelationship))
}
/********************
* BREAKUP REQUESTS
********************/
fun requestRelationshipBreakup() {
val relationship = SessionManager.getUserRelationship()
val breakupRequest = SessionManager.getUserRelationshipBreakupRequests()
when {
relationship == null -> javaClass.log(LogLevel.ERROR, "Session Relationship was null! Error!")
breakupRequest != null -> javaClass.log(LogLevel.ERROR, "Session Breakup Request already exists! Error!")
else -> {
val newRequest = NewRelationshipBreakupRequest(SessionManager.getUser().userUuid, relationship.relationshipUuid, "Let us break up!")
Calls.relationshipService.requestCompositeRelationshipBreakup(newRequest)
.compose(ReactiveUtils.commonMaybeTransformation(view, true))
.subscribe({ SessionManager.syncRelationshipBreakup() }, Throwable::printStackTrace)
}
}
}
fun cancelRelationshipBreakup() {
requestRelationshipStatus(RelationshipBreakupRequestStatus.CANCELLED)
}
fun acceptRelationshipBreakup() {
requestRelationshipStatus(RelationshipBreakupRequestStatus.COMPLETED)
}
private fun requestRelationshipStatus(status: RelationshipBreakupRequestStatus) {
val relationship = SessionManager.getUserRelationship()
val breakupRequest = SessionManager.getUserRelationshipBreakupRequests()
when {
relationship == null -> javaClass.log(LogLevel.ERROR, "Session Relationship was null! Error!")
breakupRequest == null -> javaClass.log(LogLevel.ERROR, "Session Breakup Request was null! Error!")
relationship.relationshipUuid != breakupRequest.relationshipUuid -> javaClass.log(LogLevel.ERROR, "Session Relationship did not match Session Breakup Request! Error!")
else -> {
Calls.relationshipService.setFinalCompositeRelationshipBreakupRequestStatus(breakupRequest.relationshipBreakupRequestUuid, status)
.compose(ReactiveUtils.commonMaybeTransformation(view, true))
.subscribe({
SessionManager.syncRelationship()
SessionManager.syncRelationshipBreakup()
}, Throwable::printStackTrace)
}
}
}
} | gpl-3.0 | b15e4275615e6a3ed3e01308d4bd99dd | 46.008475 | 179 | 0.669672 | 5.765073 | false | false | false | false |
lukashaertel/megal-vm | src/main/kotlin/org/softlang/util/Lists.kt | 1 | 868 | package org.softlang.util
/**
* Skips [num] elements in the list.
*/
fun <E> List<E>.skip(num: Int) = subList(num, size)
/**
* Returns the tail of the list.
*/
fun <E> List<E>.tail() = skip(1)
/**
* Constructs a list from the first element and a list of remaining elements.
*/
infix fun <E> E.then(list: List<E>) = listOf(this) + list
/**
* Checks if list contains item, returns false if item is null and list is
* not nullable.
*/
fun <E> List<E>.contains(item: E?) =
if (item == null)
false
else contains(item)
/**
* Returns consecutive values of the list as pairs.
*/
val <E> List<E>.pairs: List<Pair<E, E>> get() = (1 until size)
.map { get(it - 1) to get(it) }
/**
* Decomposes the list as head and tail for pair variable assignments.
*/
val <E> List<E>.decomposed: Pair<E, List<E>> get() = first() to tail() | mit | d518663a1415b1e47278cbf2be39a28d | 23.138889 | 77 | 0.612903 | 3.056338 | false | false | false | false |
chibatching/Kotpref | kotpref/src/main/kotlin/com/chibatching/kotpref/pref/StringSetPref.kt | 1 | 8490 | package com.chibatching.kotpref.pref
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.os.Build
import android.os.SystemClock
import com.chibatching.kotpref.KotprefModel
import com.chibatching.kotpref.execute
import kotlin.reflect.KProperty
/**
* Delegate string set shared preferences property.
* @param default default string set value
* @param key custom preferences key
* @param commitByDefault commit this property instead of apply
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public fun KotprefModel.stringSetPref(
default: Set<String> = LinkedHashSet(),
key: String? = null,
commitByDefault: Boolean = commitAllPropertiesByDefault
): AbstractStringSetPref = stringSetPref(key, commitByDefault) { default }
/**
* Delegate string set shared preferences property.
* @param default default string set value
* @param key custom preferences key resource id
* @param commitByDefault commit this property instead of apply
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public fun KotprefModel.stringSetPref(
default: Set<String> = LinkedHashSet(),
key: Int,
commitByDefault: Boolean = commitAllPropertiesByDefault
): AbstractStringSetPref = stringSetPref(context.getString(key), commitByDefault) { default }
/**
* Delegate string set shared preferences property.
* @param key custom preferences key
* @param commitByDefault commit this property instead of apply
* @param default default string set value creation function
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public fun KotprefModel.stringSetPref(
key: String? = null,
commitByDefault: Boolean = commitAllPropertiesByDefault,
default: () -> Set<String>
): AbstractStringSetPref = StringSetPref(default, key, commitByDefault)
/**
* Delegate string set shared preferences property.
* @param key custom preferences key resource id
* @param commitByDefault commit this property instead of apply
* @param default default string set value
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public fun KotprefModel.stringSetPref(
key: Int,
commitByDefault: Boolean = commitAllPropertiesByDefault,
default: () -> Set<String>
): AbstractStringSetPref = stringSetPref(context.getString(key), commitByDefault, default)
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
internal class StringSetPref(
val default: () -> Set<String>,
override val key: String?,
private val commitByDefault: Boolean
) : AbstractStringSetPref() {
private var stringSet: MutableSet<String>? = null
private var lastUpdate: Long = 0L
override operator fun getValue(
thisRef: KotprefModel,
property: KProperty<*>
): MutableSet<String> {
if (stringSet != null && lastUpdate >= thisRef.kotprefTransactionStartTime) {
return stringSet!!
}
val prefSet = thisRef.kotprefPreference.getStringSet(preferenceKey, null)
?.let { HashSet(it) }
stringSet = PrefMutableSet(
thisRef,
prefSet ?: default.invoke().toMutableSet(),
preferenceKey
)
lastUpdate = SystemClock.uptimeMillis()
return stringSet!!
}
internal inner class PrefMutableSet(
val kotprefModel: KotprefModel,
val set: MutableSet<String>,
val key: String
) : MutableSet<String> by set {
init {
addAll(set)
}
private var transactionData: MutableSet<String>? = null
get() {
field = field ?: set.toMutableSet()
return field
}
internal fun syncTransaction() {
synchronized(this) {
transactionData?.let {
set.clear()
set.addAll(it)
transactionData = null
}
}
}
@SuppressLint("CommitPrefEdits")
override fun add(element: String): Boolean {
if (kotprefModel.kotprefInTransaction) {
val result = transactionData!!.add(element)
kotprefModel.kotprefEditor!!.putStringSet(key, this)
return result
}
val result = set.add(element)
kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault)
return result
}
@SuppressLint("CommitPrefEdits")
override fun addAll(elements: Collection<String>): Boolean {
if (kotprefModel.kotprefInTransaction) {
val result = transactionData!!.addAll(elements)
kotprefModel.kotprefEditor!!.putStringSet(key, this)
return result
}
val result = set.addAll(elements)
kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault)
return result
}
@SuppressLint("CommitPrefEdits")
override fun remove(element: String): Boolean {
if (kotprefModel.kotprefInTransaction) {
val result = transactionData!!.remove(element)
kotprefModel.kotprefEditor!!.putStringSet(key, this)
return result
}
val result = set.remove(element)
kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault)
return result
}
@SuppressLint("CommitPrefEdits")
override fun removeAll(elements: Collection<String>): Boolean {
if (kotprefModel.kotprefInTransaction) {
val result = transactionData!!.removeAll(elements)
kotprefModel.kotprefEditor!!.putStringSet(key, this)
return result
}
val result = set.removeAll(elements)
kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault)
return result
}
@SuppressLint("CommitPrefEdits")
override fun retainAll(elements: Collection<String>): Boolean {
if (kotprefModel.kotprefInTransaction) {
val result = transactionData!!.retainAll(elements)
kotprefModel.kotprefEditor!!.putStringSet(key, this)
return result
}
val result = set.retainAll(elements)
kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault)
return result
}
@SuppressLint("CommitPrefEdits")
override fun clear() {
if (kotprefModel.kotprefInTransaction) {
val result = transactionData!!.clear()
kotprefModel.kotprefEditor!!.putStringSet(key, this)
return result
}
set.clear()
kotprefModel.kotprefPreference.edit().putStringSet(key, set).execute(commitByDefault)
}
override fun contains(element: String): Boolean {
if (kotprefModel.kotprefInTransaction) {
return element in transactionData!!
}
return element in set
}
override fun containsAll(elements: Collection<String>): Boolean {
if (kotprefModel.kotprefInTransaction) {
return transactionData!!.containsAll(elements)
}
return set.containsAll(elements)
}
override fun iterator(): MutableIterator<String> {
return if (kotprefModel.kotprefInTransaction) {
kotprefModel.kotprefEditor!!.putStringSet(key, this@PrefMutableSet)
KotprefMutableIterator(transactionData!!.iterator(), true)
} else {
KotprefMutableIterator(set.iterator(), false)
}
}
override val size: Int
get() {
if (kotprefModel.kotprefInTransaction) {
return transactionData!!.size
}
return set.size
}
private inner class KotprefMutableIterator(
val baseIterator: MutableIterator<String>,
val inTransaction: Boolean
) : MutableIterator<String> by baseIterator {
@SuppressLint("CommitPrefEdits")
override fun remove() {
baseIterator.remove()
if (!inTransaction) {
kotprefModel.kotprefPreference.edit().putStringSet(key, set)
.execute(commitByDefault)
}
}
}
}
}
| apache-2.0 | 5d5baa1158a4b1132724ce1d595a8d6b | 35.282051 | 97 | 0.62768 | 5.690349 | false | false | false | false |
rsiebert/TVHClient | app/src/main/java/org/tvheadend/tvhclient/util/worker/RecordingNotificationWorker.kt | 1 | 2026 | package org.tvheadend.tvhclient.util.worker
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationManagerCompat
import androidx.work.Worker
import androidx.work.WorkerParameters
import org.tvheadend.tvhclient.R
import org.tvheadend.tvhclient.service.ConnectionService
import org.tvheadend.tvhclient.ui.common.getNotificationBuilder
import timber.log.Timber
import java.text.SimpleDateFormat
import java.util.*
class RecordingNotificationWorker(val context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
companion object {
const val WORK_NAME = "RecordingNotificationWorker"
}
override fun doWork(): Result {
val dvrTitle = inputData.getString("dvrTitle")
val dvrId = inputData.getInt("dvrId", 0)
val startTime = inputData.getLong("start", 0)
Timber.d("Received notification broadcast for recording $dvrTitle")
// Create the intent that handles the cancelling of the scheduled recording
val recordIntent = Intent(context, ConnectionService::class.java)
recordIntent.action = "cancelDvrEntry"
recordIntent.putExtra("id", dvrId)
val cancelRecordingPendingIntent = PendingIntent.getService(context, 0, recordIntent, PendingIntent.FLAG_UPDATE_CURRENT)
// Create the title of the notification.
// The text below the title will be the recording name
val sdf = SimpleDateFormat("HH:mm", Locale.US)
val title = "Recording starts at ${sdf.format(startTime)} in ${(startTime - Date().time) / 1000 / 60} minutes."
val builder = getNotificationBuilder(context)
builder.setContentTitle(title)
.setContentText(dvrTitle)
.addAction(R.attr.ic_menu_record_cancel, context.getString(R.string.record_cancel), cancelRecordingPendingIntent)
NotificationManagerCompat.from(context).notify(dvrId, builder.build())
return Result.success()
}
}
| gpl-3.0 | e0049610ed966b009be1a6a5f7a8fcec | 40.346939 | 129 | 0.733465 | 4.689815 | false | false | false | false |
rubixhacker/Kontact | kontact/src/main/kotlin/com/hackedcube/kontact/ContactUtils.kt | 1 | 4119 | @file:JvmName("ContactUtils")
package com.hackedcube.kontact
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.ContactsContract
fun Context.queryAllContacts(): List<Kontact> {
contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null).use {
return generateSequence { if (it.moveToNext()) it else null }
.map { kontactFromCursor(this, it) }
.toList()
}
}
fun Context.getContactFromId(uri: Uri): Kontact? {
contentResolver.query(uri, null, null, null, null).use { cursorContact ->
cursorContact.moveToFirst()
return kontactFromCursor(this, cursorContact)
}
}
private fun kontactFromCursor(context: Context, cursor: Cursor): Kontact {
var kontact = Kontact.create(cursor)
// Fetch Phone Numbers
if (kontact.hasPhoneNumber()) {
context.contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", arrayOf(kontact.id()), null).use { phoneCursor ->
val phoneNumbers = phoneCursor.toSequence()
.map { PhoneNumber.create(it) }
.toList()
kontact = kontact.withPhoneNumbers(phoneNumbers)
}
}
// Fetch Email addresses
context.contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", arrayOf(kontact.id()), null).use { emailCursor ->
val emailAddresses = emailCursor.toSequence()
.map { EmailAddress.create(it) }
.toList()
kontact = kontact.withEmailAddresses(emailAddresses)
}
val select = arrayOf(ContactsContract.Data.MIMETYPE, "data1", "data2", "data3", "data4",
"data5", "data6", "data7", "data8", "data9", "data10", "data11", "data12", "data13",
"data14", "data15")
// Fetch additional info
val where = "${ContactsContract.Data.CONTACT_ID} = ? AND ${ContactsContract.Data.MIMETYPE} IN (?, ?, ?, ?)"
val whereParams = arrayOf(
kontact.id(),
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE
)
context.contentResolver.query(ContactsContract.Data.CONTENT_URI, select, where, whereParams, null).use { dataCursor ->
val data = dataCursor.toSequence()
.map {
val columnType = it.getString(it.getColumnIndex(ContactsContract.Data.MIMETYPE))
when(columnType) {
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE -> columnType to Event.create(it)
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE -> columnType to Nickname.create(it)
ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE -> columnType to Relation.create(it)
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE -> columnType to PostalAddress.create(it)
else -> columnType to null
}
}
.groupBy({it.first}, {it.second})
kontact = kontact.toBuilder()
.events(data[ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE] as MutableList<Event>?)
.nicknames(data[ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE] as MutableList<Nickname>?)
.postalAddresses(data[ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE] as MutableList<PostalAddress>?)
.relations(data[ContactsContract.CommonDataKinds.Relation.CONTENT_ITEM_TYPE] as MutableList<Relation>?)
.build()
}
return kontact
} | apache-2.0 | e704061328587b219133feb413b8dad2 | 41.840426 | 205 | 0.640447 | 4.772885 | false | false | false | false |
olonho/carkot | server/src/main/java/clInterface/executor/Sonar.kt | 1 | 2359 | package clInterface.executor
import SonarRequest
import objects.Car
import objects.Environment
import java.net.ConnectException
import java.util.*
import java.util.concurrent.TimeUnit
class Sonar : CommandExecutor {
private val SONAR_REGEX = Regex("sonar [0-9]{1,10}")
override fun execute(command: String) {
if (!SONAR_REGEX.matches(command)) {
println("incorrect args of command sonar.")
return
}
val id: Int
try {
id = command.split(" ")[1].toInt()
} catch (e: NumberFormatException) {
e.printStackTrace()
println("error in converting id to int type")
return
}
val car: Car? = synchronized(Environment, {
Environment.map[id]
})
if (car == null) {
println("car with id=$id not found")
return
}
val angles = getRequiredAngles() ?: return
try {
val sonarResult = car.scan(angles, 5, 3, SonarRequest.Smoothing.MEDIAN)
val distances = sonarResult.get(2, TimeUnit.MINUTES)
println("angles : ${Arrays.toString(angles)}")
println("distances: ${Arrays.toString(distances)}")
} catch (e: ConnectException) {
synchronized(Environment, {
Environment.map.remove(id)
})
}
}
private fun getRequiredAngles(): IntArray? {
println("print angles, after printing all angles print done")
val angles = arrayListOf<Int>()
while (true) {
val command = readLine()!!.toLowerCase()
when (command) {
"reset" -> return null
"done" -> {
return angles.toIntArray()
}
else -> {
try {
val angle = command.toInt()
if (angle < 0 || angle > 180) {
println("incorrect angle $angle. angle must be in [0,180] and div on 4")
} else {
angles.add(angle)
}
} catch (e: NumberFormatException) {
println("error in converting angle to int. try again")
}
}
}
}
}
} | mit | dee442a4a34cf7e43cb2c3da48fdbe77 | 31.777778 | 100 | 0.496397 | 5.019149 | false | false | false | false |
genobis/tornadofx | src/main/java/tornadofx/Async.kt | 1 | 14271 | package tornadofx
import com.sun.javafx.tk.Toolkit
import javafx.application.Platform
import javafx.beans.property.*
import javafx.beans.value.ChangeListener
import javafx.beans.value.ObservableValue
import javafx.concurrent.Task
import javafx.scene.Node
import javafx.scene.control.Labeled
import javafx.scene.control.ProgressIndicator
import javafx.scene.layout.BorderPane
import javafx.scene.layout.Region
import javafx.util.Duration
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.ThreadFactory
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong
import java.util.logging.Level
import java.util.logging.Logger
internal val log = Logger.getLogger("tornadofx.async")
internal val dummyUncaughtExceptionHandler = Thread.UncaughtExceptionHandler { t, e -> log.log(Level.WARNING, e) { "Exception in ${t?.name ?: "?"}: ${e?.message ?: "?"}" } }
internal val tfxThreadPool = Executors.newCachedThreadPool(object : ThreadFactory {
private val threadCounter = AtomicLong(0L)
override fun newThread(runnable: Runnable?) = Thread(runnable, "tornadofx-thread-${threadCounter.incrementAndGet()}")
})
fun <T> task(taskStatus: TaskStatus? = null, func: FXTask<*>.() -> T): Task<T> = FXTask(taskStatus, func = func).apply {
setOnFailed({ (Thread.getDefaultUncaughtExceptionHandler() ?: dummyUncaughtExceptionHandler).uncaughtException(Thread.currentThread(), exception) })
tfxThreadPool.execute(this)
}
fun <T> runAsync(status: TaskStatus? = null, func: FXTask<*>.() -> T) = task(status, func)
infix fun <T> Task<T>.ui(func: (T) -> Unit) = success(func)
infix fun <T> Task<T>.success(func: (T) -> Unit) = apply {
Platform.runLater {
setOnSucceeded { func(value) }
}
}
infix fun <T> Task<T>.fail(func: (Throwable) -> Unit) = apply {
Platform.runLater {
setOnFailed { func(exception) }
}
}
/**
* Run the specified Runnable on the JavaFX Application Thread at some
* unspecified time in the future.
*/
fun runLater(op: () -> Unit) = Platform.runLater(op)
/**
* Run the specified Runnable on the JavaFX Application Thread after a
* specified delay.
*
* runLater(10.seconds) {
* // Do something on the application thread
* }
*
* This function returns a TimerTask which includes a runningProperty as well as the owning timer.
* You can cancel the task before the time is up to abort the execution.
*/
fun runLater(delay: Duration, op: () -> Unit): FXTimerTask {
val timer = Timer(true)
val task = FXTimerTask(op, timer)
timer.schedule(task, delay.toMillis().toLong())
return task
}
/**
* Wait on the UI thread until a certain value is available on this observable.
*
* This method does not block the UI thread even though it halts further execution until the condition is met.
*/
fun <T> ObservableValue<T>.awaitUntil(condition: (T) -> Boolean) {
if (!Toolkit.getToolkit().canStartNestedEventLoop()) {
throw IllegalStateException("awaitUntil is not allowed during animation or layout processing")
}
val changeListener = object : ChangeListener<T> {
override fun changed(observable: ObservableValue<out T>?, oldValue: T, newValue: T) {
if (condition(value)) {
runLater {
Toolkit.getToolkit().exitNestedEventLoop(this@awaitUntil, null)
removeListener(this)
}
}
}
}
changeListener.changed(this, value, value)
addListener(changeListener)
Toolkit.getToolkit().enterNestedEventLoop(this)
}
/**
* Wait on the UI thread until this observable value is true.
*
* This method does not block the UI thread even though it halts further execution until the condition is met.
*/
fun ObservableValue<Boolean>.awaitUntil() {
this.awaitUntil { it }
}
/**
* Replace this node with a progress node while a long running task
* is running and swap it back when complete.
*
* If this node is Labeled, the graphic property will contain the progress bar instead while the task is running.
*
* The default progress node is a ProgressIndicator that fills the same
* client area as the parent. You can swap the progress node for any Node you like.
*
* For latch usage see [runAsyncWithOverlay]
*/
fun Node.runAsyncWithProgress(latch: CountDownLatch, timeout: Duration? = null, progress: Node = ProgressIndicator()): Task<Boolean> {
return if(timeout == null) {
runAsyncWithProgress(progress) { latch.await(); true }
} else {
runAsyncWithOverlay(progress) { latch.await(timeout.toMillis().toLong(), TimeUnit.MILLISECONDS) }
}
}
/**
* Replace this node with a progress node while a long running task
* is running and swap it back when complete.
*
* If this node is Labeled, the graphic property will contain the progress bar instead while the task is running.
*
* The default progress node is a ProgressIndicator that fills the same
* client area as the parent. You can swap the progress node for any Node you like.
*/
fun <T : Any> Node.runAsyncWithProgress(progress: Node = ProgressIndicator(), op: () -> T): Task<T> {
if (this is Labeled) {
val oldGraphic = graphic
(progress as? Region)?.setPrefSize(16.0, 16.0)
graphic = progress
return task {
try {
op()
} finally {
runLater {
this@runAsyncWithProgress.graphic = oldGraphic
}
}
}
} else {
val paddingHorizontal = (this as? Region)?.paddingHorizontal?.toDouble() ?: 0.0
val paddingVertical = (this as? Region)?.paddingVertical?.toDouble() ?: 0.0
(progress as? Region)?.setPrefSize(boundsInParent.width - paddingHorizontal, boundsInParent.height - paddingVertical)
val children = requireNotNull(parent.getChildList()){"This node has no child list, and cannot contain the progress node"}
val index = children.indexOf(this)
children.add(index, progress)
removeFromParent()
return task {
val result = op()
runLater {
children.add(index, this@runAsyncWithProgress)
progress.removeFromParent()
}
result
}
}
}
/**
* Covers node with overlay (by default - an instance of [MaskPane]) until [latch] is released by another thread.
* It's useful when more control over async execution is needed, like:
* * A task already have its thread and overlay should be visible until some callback is invoked (it should invoke
* [CountDownLatch.countDown] or [Latch.release]) in order to unlock UI. Keep in mind that if [latch] is not released
* and [timeout] is not set, overlay may never get removed.
* * An overlay should be removed after some time, even if task is getting unresponsive (use [timeout] for this).
* Keep in mind that this timeout applies to overlay only, not the latch itself.
* * In addition to masking UI, you need an access to property indicating if background process is running;
* [Latch.lockedProperty] serves exactly that purpose.
* * More threads are involved in task execution. You can create a [CountDownLatch] for number of workers, call
* [CountDownLatch.countDown] from each of them when it's done and overlay will stay visible until all workers finish
* their jobs.
*
* @param latch an instance of [CountDownLatch], usage of [Latch] is recommended.
* @param timeout timeout after which overlay will be removed anyway. Can be `null` (which means no timeout).
* @param overlayNode optional custom overlay node. For best effect set transparency.
*
* # Example 1
* The simplest case: overlay is visible for two seconds - until latch release. Replace [Thread.sleep] with any
* blocking action. Manual thread creation is for the sake of the example only.
*
* ```kotlin
* val latch = Latch()
* root.runAsyncWithOverlay(latch) ui {
* //UI action
* }
*
* Thread({
* Thread.sleep(2000)
* latch.release()
* }).start()
* ```
*
* # Example 2
* The latch won't be released until both workers are done. In addition, until workers are done, button will stay
* disabled. New latch has to be created and rebound every time.
*
* ```kotlin
* val latch = Latch(2)
* root.runAsyncWithOverlay(latch)
* button.disableWhen(latch.lockedProperty())
* runAsync(worker1.work(); latch.countDown())
* runAsync(worker2.work(); latch.countDown())
*/
@JvmOverloads
fun Node.runAsyncWithOverlay(latch: CountDownLatch, timeout: Duration? = null, overlayNode: Node = MaskPane()): Task<Boolean> {
return if(timeout == null) {
runAsyncWithOverlay(overlayNode) { latch.await(); true }
} else {
runAsyncWithOverlay(overlayNode) { latch.await(timeout.toMillis().toLong(), TimeUnit.MILLISECONDS) }
}
}
/**
* Runs given task in background thread, covering node with overlay (default one is [MaskPane]) until task is done.
*
* # Example
*
* ```kotlin
* root.runAsyncWithOverlay {
* Thread.sleep(2000)
* } ui {
* //UI action
* }
* ```
*
* @param overlayNode optional custom overlay node. For best effect set transparency.
*/
@JvmOverloads
fun <T : Any> Node.runAsyncWithOverlay(overlayNode: Node = MaskPane(), op: () -> T): Task<T> {
val overlayContainer = stackpane { add(overlayNode) }
replaceWith(overlayContainer)
overlayContainer.children.add(0,this)
return task {
try { op() }
finally { runLater { overlayContainer.replaceWith(this@runAsyncWithOverlay) } }
}
}
/**
* A basic mask pane, intended for blocking gui underneath. Styling example:
*
* ```css
* .mask-pane {
* -fx-background-color: rgba(0,0,0,0.5);
* -fx-accent: aliceblue;
* }
*
* .mask-pane > .progress-indicator {
* -fx-max-width: 300;
* -fx-max-height: 300;
* }
* ```
*/
class MaskPane : BorderPane() {
init {
addClass("mask-pane")
center = progressindicator()
}
override fun getUserAgentStylesheet() = MaskPane::class.java.getResource("maskpane.css").toExternalForm()!!
}
/**
* Adds some superpowers to good old [CountDownLatch], like exposed [lockedProperty] or ability to release latch
* immediately.
*
* All documentation of superclass applies here. Default behavior has not been altered.
*/
class Latch(count: Int) : CountDownLatch(count) {
/**
* Initializes latch with count of `1`, which means that the first invocation of [countDown] will allow all
* waiting threads to proceed.
*/
constructor() : this(1)
private val lockedProperty by lazy { ReadOnlyBooleanWrapper(locked) }
/**
* Locked state of this latch exposed as a property. Keep in mind that latch instance can be used only once, so
* this property has to rebound every time.
*/
fun lockedProperty() : ReadOnlyBooleanProperty = lockedProperty.readOnlyProperty
/**
* Locked state of this latch. `true` if and only if [CountDownLatch.getCount] is greater than `0`.
* Once latch is released it changes to `false` permanently.
*/
val locked get() = count > 0L
/**
* Releases latch immediately and allows waiting thread(s) to proceed. Can be safely used if this latch has been
* initialized with `count` of `1`, should be used with care otherwise - [countDown] invocations ar preferred in
* such cases.
*/
fun release() = (1..count).forEach { countDown() } //maybe not the prettiest way, but works fine
override fun countDown() {
super.countDown()
lockedProperty.set(locked)
}
}
class FXTimerTask(val op: () -> Unit, val timer: Timer) : TimerTask() {
private val internalRunning = ReadOnlyBooleanWrapper(false)
val runningProperty: ReadOnlyBooleanProperty get() = internalRunning.readOnlyProperty
val running: Boolean get() = runningProperty.value
private val internalCompleted = ReadOnlyBooleanWrapper(false)
val completedProperty: ReadOnlyBooleanProperty get() = internalCompleted.readOnlyProperty
val completed: Boolean get() = completedProperty.value
override fun run() {
internalRunning.value = true
Platform.runLater {
try {
op()
} finally {
internalRunning.value = false
internalCompleted.value = true
}
}
}
}
class FXTask<T>(val status: TaskStatus? = null, val func: FXTask<*>.() -> T) : Task<T>() {
private var internalCompleted = ReadOnlyBooleanWrapper(false)
val completedProperty: ReadOnlyBooleanProperty get() = internalCompleted.readOnlyProperty
val completed: Boolean get() = completedProperty.value
override fun call() = func(this)
init {
status?.item = this
}
override fun succeeded() {
internalCompleted.value = true
}
override fun failed() {
internalCompleted.value = true
}
override fun cancelled() {
internalCompleted.value = true
}
override public fun updateProgress(workDone: Long, max: Long) {
super.updateProgress(workDone, max)
}
override public fun updateProgress(workDone: Double, max: Double) {
super.updateProgress(workDone, max)
}
@Suppress("UNCHECKED_CAST")
fun value(v: Any) {
super.updateValue(v as T)
}
override public fun updateTitle(t: String?) {
super.updateTitle(t)
}
override public fun updateMessage(m: String?) {
super.updateMessage(m)
}
}
open class TaskStatus : ItemViewModel<FXTask<*>>() {
val running: ReadOnlyBooleanProperty = bind { SimpleBooleanProperty().apply { if (item != null) bind(item.runningProperty()) } }
val completed: ReadOnlyBooleanProperty = bind { SimpleBooleanProperty().apply { if (item != null) bind(item.completedProperty) } }
val message: ReadOnlyStringProperty = bind { SimpleStringProperty().apply { if (item != null) bind(item.messageProperty()) } }
val title: ReadOnlyStringProperty = bind { SimpleStringProperty().apply { if (item != null) bind(item.titleProperty()) } }
val progress: ReadOnlyDoubleProperty = bind { SimpleDoubleProperty().apply { if (item != null) bind(item.progressProperty()) } }
}
| apache-2.0 | f832bffad9e6af27ea5be4c5180f5e43 | 35.312977 | 173 | 0.683204 | 4.320618 | false | false | false | false |
d9n/intellij-rust | src/test/kotlin/org/rust/ide/inspections/RsMissingElseInspectionTest.kt | 1 | 2651 | package org.rust.ide.inspections
/**
* Tests for Missing Else inspection.
*/
class RsMissingElseInspectionTest : RsInspectionsTestBase(RsMissingElseInspection()) {
fun testSimple() = checkByText("""
fn main() {
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>true {
}
}
""")
fun testNoSpaces() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?">if</warning>(a > 10){
}
}
""")
fun testWideSpaces() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>(a > 10) {
}
}
""")
fun testComments() = checkByText("""
fn main() {
let a = 10;
if true {
}<warning descr="Suspicious if. Did you mean `else if`?"> /* commented */ /* else */ if </warning>a > 10 {
}
}
""")
fun testNotLastExpr() = checkByText("""
fn main() {
let a = 10;
if a > 5 {
}<warning descr="Suspicious if. Did you mean `else if`?"> if </warning>a > 10{
}
let b = 20;
}
""")
fun testHandlesBlocksWithNoSiblingsCorrectly() = checkByText("""
fn main() {if true {}}
""")
fun testNotAppliedWhenLineBreakExists() = checkByText("""
fn main() {
if true {}
if true {}
}
""")
fun testNotAppliedWhenTheresNoSecondIf() = checkByText("""
fn main() {
if {
92;
}
{}
}
""")
fun testFix() = checkFixByText("Change to `else if`", """
fn main() {
let a = 10;
if a > 7 {
}<warning descr="Suspicious if. Did you mean `else if`?"> i<caret>f </warning>a > 14 {
}
}
""", """
fn main() {
let a = 10;
if a > 7 {
} else if a > 14 {
}
}
""")
fun testFixPreservesComments() = checkFixByText("Change to `else if`", """
fn main() {
let a = 10;
if a > 7 {
}<warning descr="Suspicious if. Did you mean `else if`?"> /* comment */<caret> if /* ! */ </warning>a > 14 {
}
}
""", """
fn main() {
let a = 10;
if a > 7 {
} /* comment */ else if /* ! */ a > 14 {
}
}
""")
}
| mit | b2a0577c8252db8a99e672c9f4f49895 | 24.490385 | 120 | 0.422482 | 4.42571 | false | true | false | false |
gdomingues/keural | src/test/kotlin/br/com/germanno/keural/KeuralManagerTest.kt | 1 | 1883 | package br.com.germanno.keural
import br.com.germanno.keural.activation_functions.HyperbolicTangent
import org.junit.Assert
import org.junit.Test
/**
* @author Germanno Domingues - germanno.domingues@gmail.com
* @since 1/30/17 3:10 AM
*/
class KeuralManagerTest {
private val wordsDatabase = arrayOf(
"banana",
"sorteio",
"carvalho",
"montanha",
"frasco"
)
private val inputSize = wordsDatabase.maxBy { it.length }!!.length * 8
private val keuralManager by lazy {
object : KeuralManager<String, String>(
inputSize,
wordsDatabase.size,
activationFunction = HyperbolicTangent(),
debugMode = true
) {
override val inputToDoubleArray: (String) -> DoubleArray = { string ->
val bitsInString = string.length * 8
val initialArray = DoubleArray(inputSize - bitsInString) { 0.0 }
string.reversed().fold(initialArray) { array, c -> array + c.toBitArray() }
}
override val doubleArrayToOutput: (DoubleArray) -> String = { doubleArray ->
with(doubleArray) { wordsDatabase[indexOf(max()!!)] }
}
override val outputToDoubleArray: (String) -> DoubleArray = { string ->
wordsDatabase.map { if (it == string) 1.0 else 0.0 }.toDoubleArray()
}
}.apply { trainNetwork(wordsDatabase, wordsDatabase, 100000) }
}
@Test
fun recognize() {
val enteredWords = arrayOf(
"batata",
"sorvete",
"carrasco",
"montando",
"frescor"
)
enteredWords.forEachIndexed { i, s ->
Assert.assertEquals(wordsDatabase[i], keuralManager.recognize(s))
}
}
}
| mit | b71a669bc6765f32565bcd891ee39cc6 | 27.530303 | 91 | 0.554434 | 4.399533 | false | false | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/SectionSeekBar.kt | 1 | 8139 | package com.hewking.custom
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import com.hewking.custom.util.dp2px
/**
* 类的描述:
* 创建人员:hewking
* 创建时间:2018/3/16
* 修改人员:hewking
* 修改时间:2018/3/16
* 修改备注:
* Version: 1.0.0
*/
class SectionSeekBar(ctx: Context, attrs: AttributeSet) : View(ctx, attrs) {
/**
* 未选中的圆和线的颜色
*/
private var mUnselectColor = 0
/**
* 已选中的圆和半径
*/
private var mSelectColor = 0
/**
* 小圆的半径
*/
private var mRadius = 0f
/**
* 选中的园的半径
*/
private var mSelectRadius = 0f
/**
* 线的宽度
*/
private var mLineWidth = 0f
/**
* 需要的section 数量
*/
private var sectionCount = 0
/**
* 当前选中的位置
*/
private var mCurPosition = -1
/**
* 是否支持拖动进度
*/
private var canDrag = true
private val mLinePaint by lazy {
Paint().apply {
isAntiAlias = true
strokeWidth = mLineWidth
style = Paint.Style.FILL
color = mUnselectColor
}
}
private val mSectionPaint by lazy {
Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
color = mUnselectColor
}
}
private var mOnSectionChangeListener : OnSectionChangeListener? = null
init {
val attrs = ctx.obtainStyledAttributes(attrs, R.styleable.SectionSeekBar)
mRadius = attrs.getDimensionPixelSize(R.styleable.SectionSeekBar_section_radius, dp2px(4f)).toFloat()
mSelectRadius = attrs.getDimensionPixelSize(R.styleable.SectionSeekBar_section_select_radus, (mRadius * 1.5f).toInt()).toFloat()
mSelectColor = attrs.getColor(R.styleable.SectionSeekBar_section_select_colorr, Color.BLUE)
mUnselectColor = attrs.getColor(R.styleable.SectionSeekBar_section_unselect_colro, Color.GRAY)
sectionCount = attrs.getInteger(R.styleable.SectionSeekBar_section_section_count, 5)
mCurPosition = attrs.getInteger(R.styleable.SectionSeekBar_section_cur_position, 0)
mLineWidth = attrs.getDimensionPixelSize(R.styleable.SectionSeekBar_section_line_width, dp2px(1f)).toFloat()
attrs.recycle()
// 初始化画笔
mLinePaint
mSectionPaint
if (BuildConfig.DEBUG) {
mOnSectionChangeListener = object : OnSectionChangeListener{
override fun onCurrentSectionChange(curPos: Int, oldPos: Int) {
Log.d(SectionSeekBar::class.java.simpleName,"curPos : ${curPos} oldPos : ${oldPos}")
}
}
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
val heightSpecSize = MeasureSpec.getSize(heightMeasureSpec)
if (heightMode == MeasureSpec.AT_MOST) {
val mHeight = paddingTop + paddingBottom + 2 * mSelectRadius
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mHeight.toInt())
}
}
private var mLastX = 0f
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (canDrag) {
when(event?.action) {
MotionEvent.ACTION_DOWN -> {
mLastX = event?.x
}
MotionEvent.ACTION_MOVE -> {
mLastX = event?.x
invalidate()
}
MotionEvent.ACTION_UP -> {
/**
* 计算当前 up 事件所在的点
*/
mLastX = calcDstX(event?.x)
// 动画过渡 增强体验
smoothToTarget(event?.x,mLastX)
// invalidate()
}
}
return true
} else {
return super.onTouchEvent(event)
}
}
private fun smoothToTarget(x: Float, lastX: Float) {
ValueAnimator.ofFloat(x,lastX)
.apply {
duration = 300
addUpdateListener {
mLastX = (it.animatedValue as Float)
postInvalidateOnAnimation()
}
start()
}
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
// 取消动画
}
/**
* 计算当前点 x 坐标 距离 那个section 坐标绝对值最近 并返回
* section 点 圆心 x坐标
*/
private fun calcDstX(x: Float): Float {
val maxX = width - paddingRight - mSelectRadius
val minX = paddingLeft + mSelectRadius
val targetX = Math.max(minX,Math.min(x,maxX))
val sectionWidth = (width - paddingLeft - paddingRight - 2 * mSelectRadius) / (sectionCount - 1)
val sectionRound = Math.round((targetX - minX) / sectionWidth)
Log.d(SectionSeekBar::class.java.simpleName,"sectionRound : ${sectionRound} sectionWidth : ${sectionWidth} targetX : ${targetX}")
val calcX = Math.min(sectionWidth * sectionRound + minX,maxX)
val oldPos = mCurPosition
// 判断是否当前section选中改变
mCurPosition = (calcX / sectionWidth).toInt()
if (oldPos != mCurPosition) {
mOnSectionChangeListener?.onCurrentSectionChange(mCurPosition,oldPos)
}
return calcX
}
override fun onDraw(canvas: Canvas?) {
drawBg(canvas)
drawSection(canvas)
drawProgress(canvas)
}
/**
* 画圆圈
*/
private fun drawSection(canvas: Canvas?) {
val sectionWidth = (width - paddingLeft - paddingRight - 2 * mSelectRadius) / (sectionCount - 1)
val cy = paddingTop.toFloat() + mSelectRadius
var cx = 0f
var startX = paddingLeft.toFloat() + mSelectRadius
for (index in 0..sectionCount - 1) {
cx = index * sectionWidth.toFloat() + startX
if (cx <= mLastX) {
mSectionPaint.color = mSelectColor
} else {
mSectionPaint.color = mUnselectColor
}
canvas?.drawCircle(cx, cy, mRadius, mSectionPaint)
}
}
/**
* 画进度
*/
private fun drawProgress(canvas: Canvas?) {
mLinePaint.color = mSelectColor
val maxX = width - paddingRight - mSelectRadius
val minX = paddingLeft + mSelectRadius
val targetX = Math.max(minX,Math.min(mLastX,maxX))
val rect = RectF(minX, paddingTop + mSelectRadius, targetX, paddingTop + mSelectRadius + mLineWidth)
canvas?.drawRect(rect, mLinePaint)
val cy = paddingTop.toFloat() + mSelectRadius
// 绘制当前进度所在的园
if (mLastX >= minX) {
mSectionPaint.color = mSelectColor
canvas?.drawCircle(targetX,cy,mSelectRadius,mSectionPaint)
}
Log.d(SectionSeekBar::class.java.simpleName,"mLastx : ${mLastX}")
}
/**
* 画默认进度条
*/
private fun drawBg(canvas: Canvas?) {
mLinePaint.color = mUnselectColor
val rect = RectF(paddingLeft + mSelectRadius, paddingTop + mSelectRadius, width - paddingRight - mSelectRadius, paddingTop + mSelectRadius + mLineWidth)
canvas?.drawRect(rect, mLinePaint)
}
interface OnSectionChangeListener{
fun onCurrentSectionChange(curPos : Int, oldPos : Int)
}
}
| mit | bb4bf5a08b3102a3129c11dfd8f0f2c4 | 29.711382 | 160 | 0.572234 | 4.806531 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/toml/TomlStringValueInsertionHandler.kt | 1 | 1866 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.toml
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.toml.lang.psi.TomlElementTypes
import org.toml.lang.psi.TomlKeyValue
import org.toml.lang.psi.TomlLiteral
import org.toml.lang.psi.TomlValue
import org.toml.lang.psi.ext.elementType
/** Inserts `=` between key and value if missed and wraps inserted string with quotes if needed */
class TomlStringValueInsertionHandler(private val keyValue: TomlKeyValue) : InsertHandler<LookupElement> {
override fun handleInsert(context: InsertionContext, item: LookupElement) {
var startOffset = context.startOffset
val value = context.getElementOfType<TomlValue>()
val hasEq = keyValue.children.any { it.elementType == TomlElementTypes.EQ }
val hasQuotes =
value != null && (value !is TomlLiteral || value.firstChild.elementType != TomlElementTypes.NUMBER)
if (!hasEq) {
context.document.insertString(startOffset - if (hasQuotes) 1 else 0, "= ")
PsiDocumentManager.getInstance(context.project).commitDocument(context.document)
startOffset += 2
}
if (!hasQuotes) {
context.document.insertString(startOffset, "\"")
context.document.insertString(context.selectionEndOffset, "\"")
}
}
}
inline fun <reified T : PsiElement> InsertionContext.getElementOfType(strict: Boolean = false): T? =
PsiTreeUtil.findElementOfClassAtOffset(file, tailOffset - 1, T::class.java, strict)
| mit | b743c99ca0489f032d08339225afe948 | 37.875 | 111 | 0.729368 | 4.464115 | false | false | false | false |
Ribesg/anko | dsl/static/src/common/viewChildrenSequences.kt | 1 | 3829 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.anko
import android.view.*
import java.util.*
inline fun ViewGroup.forEachChild(f: (View) -> Unit) {
for (i in 0..childCount - 1) {
f(getChildAt(i))
}
}
inline fun ViewGroup.forEachChildWithIndex(f: (Int, View) -> Unit) {
for (i in 0..childCount - 1) {
f(i, getChildAt(i))
}
}
inline fun ViewGroup.firstChild(predicate: (View) -> Boolean): View {
for (i in 0..childCount - 1) {
val child = getChildAt(i)
if (predicate(child)) {
return child
}
}
throw NoSuchElementException("No element matching predicate was found.")
}
inline fun ViewGroup.firstChildOrNull(predicate: (View) -> Boolean): View? {
for (i in 0..childCount - 1) {
val child = getChildAt(i)
if (predicate(child)) {
return child
}
}
return null
}
fun View.childrenSequence(): Sequence<View> = ViewChildrenSequence(this)
fun View.childrenRecursiveSequence(): Sequence<View> = ViewChildrenRecursiveSequence(this)
private class ViewChildrenSequence(private val view: View) : Sequence<View> {
override fun iterator(): Iterator<View> {
if (view !is ViewGroup) return emptyList<View>().iterator()
return ViewIterator(view)
}
private class ViewIterator(private val view: ViewGroup) : Iterator<View> {
private var index = 0
private val count = view.childCount
override fun next(): View {
if (!hasNext()) throw NoSuchElementException()
return view.getChildAt(index++)
}
override fun hasNext(): Boolean {
checkCount()
return index < count
}
private fun checkCount() {
if (count != view.childCount) throw ConcurrentModificationException()
}
}
}
private class ViewChildrenRecursiveSequence(private val view: View) : Sequence<View> {
override fun iterator() = RecursiveViewIterator(view)
private class RecursiveViewIterator(private val view: View) : Iterator<View> {
private val sequences = arrayListOf(sequenceOf(view))
private var itemIterator: Iterator<View>? = null
override fun next(): View {
initItemIterator()
val iterator = itemIterator ?: throw NoSuchElementException()
val view = iterator.next()
if (view is ViewGroup && view.childCount > 0) {
sequences.add(view.childrenSequence())
}
return view
}
override fun hasNext(): Boolean {
initItemIterator()
val iterator = itemIterator ?: return false
return iterator.hasNext()
}
private fun initItemIterator() {
val seqs = sequences
val iterator = itemIterator
if (iterator == null || (!iterator.hasNext() && seqs.isNotEmpty())) {
itemIterator = seqs.removeLast()?.iterator()
} else {
itemIterator = null
}
}
@Suppress("NOTHING_TO_INLINE")
private inline fun <T: Any> MutableList<T>.removeLast(): T? {
if (isEmpty()) return null
return removeAt(size - 1)
}
}
}
| apache-2.0 | 2f0538834ed994b77bf1d51343cfe3d0 | 29.388889 | 90 | 0.616871 | 4.646845 | false | false | false | false |
android/health-samples | health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/navigation/DrawerItem.kt | 1 | 2251 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthconnectsample.presentation.navigation
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.healthconnectsample.presentation.theme.HealthConnectTheme
/**
* An item in the side navigation drawer.
*/
@Composable
fun DrawerItem(
item: Screen,
selected: Boolean,
onItemClick: (Screen) -> Unit
) {
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { onItemClick(item) })
.height(48.dp)
.padding(start = 16.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(item.titleId),
style = MaterialTheme.typography.h5,
color = if (selected) {
MaterialTheme.colors.primary
} else {
MaterialTheme.colors.onBackground
}
)
}
}
@Preview
@Composable
fun DrawerItemPreview() {
HealthConnectTheme {
DrawerItem(
item = Screen.ExerciseSessions,
selected = true,
onItemClick = {}
)
}
}
| apache-2.0 | e22b6eedb19026d4681643c25fcb1ff4 | 30.263889 | 76 | 0.698801 | 4.565923 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/Namespace.kt | 1 | 5426 | package org.wikipedia.page
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.language.AppLanguageLookUpTable
import org.wikipedia.model.EnumCode
import org.wikipedia.model.EnumCodeMap
import org.wikipedia.staticdata.*
import java.util.*
/** An enumeration describing the different possible namespace codes. Do not attempt to use this
* class to preserve URL path information such as Talk: or User: or localization.
* @see [Wikipedia:Namespace](https://en.wikipedia.org/wiki/Wikipedia:Namespace)
* @see [Extension default namespaces](https://www.mediawiki.org/wiki/Extension_default_namespaces)
* @see [Manual:Namespace](https://www.mediawiki.org/wiki/Manual:Namespace.Built-in_namespaces)
* @see [Namespaces reported by API](https://en.wikipedia.org/w/api.php?action=query&meta=siteinfo&siprop=namespaces|namespacealiases)
*/
@Suppress("unused")
enum class Namespace(private val code: Int) : EnumCode {
MEDIA(-2),
SPECIAL(-1) {
override fun talk(): Boolean {
return false
}
},
MAIN(0),
TALK(1),
USER(2),
USER_TALK(3),
PROJECT(4),
PROJECT_TALK(5),
FILE(6),
FILE_TALK(7),
MEDIAWIKI(8),
MEDIAWIKI_TALK(9),
TEMPLATE(10),
TEMPLATE_TALK(11),
HELP(12),
HELP_TALK(13),
CATEGORY(14),
CATEGORY_TALK(15),
THREAD(90),
THREAD_TALK(91),
SUMMARY(92),
SUMMARY_TALK(93),
PORTAL(100),
PORTAL_TALK(101),
PROPERTY(102),
PROPERTY_TALK(103),
TYPE(104),
TYPE_TALK(105),
FORM(106),
FORM_TALK(107),
BOOK(108),
BOOK_TALK(109),
FORUM(110),
FORUM_TALK(111),
DRAFT(118),
DRAFT_TALK(119),
USER_GROUP(160),
ACL(162),
FILTER(170),
FILTER_TALK(171),
USER_WIKI(200),
USER_WIKI_TALK(201),
USER_PROFILE(202),
USER_PROFILE_TALK(203),
ANNOTATION(248),
ANNOTATION_TALK(249),
PAGE(250),
PAGE_TALK(251),
INDEX(252),
INDEX_TALK(253),
MATH(262),
MATH_TALK(263),
WIDGET(274),
WIDGET_TALK(275),
JS_APPLET(280),
JS_APPLET_TALK(281),
POLL(300),
POLL_TALK(301),
COURSE(350),
COURSE_TALK(351),
MAPS_LAYER(420),
MAPS_LAYER_TALK(421),
QUIZ(430),
QUIZ_TALK(431),
EDUCATION_PROGRAM(446),
EDUCATION_PROGRAM_TALK(447),
BOILERPLATE(450),
BOILERPLATE_TALK(451),
CAMPAIGN(460),
CAMPAIGN_TALK(461),
SCHEMA(470),
SCHEMA_TALK(471),
JSON_CONFIG(482),
JSON_CONFIG_TALK(483),
GRAPH(484),
GRAPH_TALK(485),
JSON_DATA(486),
JSON_DATA_TALK(487),
NOVA_RESOURCE(488),
NOVA_RESOURCE_TALK(489),
GW_TOOLSET(490),
GW_TOOLSET_TALK(491),
BLOG(500),
BLOG_TALK(501),
USER_BOX(600),
USER_BOX_TALK(601),
LINK(700),
LINK_TALK(701),
TIMED_TEXT(710),
TIMED_TEXT_TALK(711),
GIT_ACCESS_ROOT(730),
GIT_ACCESS_ROOT_TALK(731),
INTERPRETATION(800),
INTERPRETATION_TALK(801),
MUSTACHE(806),
MUSTACHE_TALK(807),
JADE(810),
JADE_TALK(811),
R(814),
R_TALK(815),
MODULE(828),
MODULE_TALK(829),
SECURE_POLL(830),
SECURE_POLL_TALK(831),
COMMENT_STREAM(844),
COMMENT_STREAM_TALK(845),
CN_BANNER(866),
CN_BANNER_TALK(867),
GRAM(1024),
GRAM_TALK(1025),
TRANSLATIONS(1198),
TRANSLATIONS_TALK(1199),
GADGET(2300),
GADGET_TALK(2301),
GADGET_DEFINITION(2302),
GADGET_DEFINITION_TALK(2303),
TOPIC(2600);
override fun code(): Int {
return code
}
fun special(): Boolean {
return this === SPECIAL
}
fun user(): Boolean {
return this === USER
}
fun userTalk(): Boolean {
return this === USER_TALK
}
fun main(): Boolean {
return this === MAIN
}
fun file(): Boolean {
return this === FILE
}
open fun talk(): Boolean {
return code and TALK_MASK == TALK_MASK
}
companion object {
private const val TALK_MASK = 0x1
private val MAP = EnumCodeMap(Namespace::class.java)
@JvmStatic
fun fromLegacyString(wiki: WikiSite, name: String?): Namespace {
if (FileAliasData.valueFor(wiki.languageCode).equals(name, true) ||
FileAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) {
return FILE
}
if (SpecialAliasData.valueFor(wiki.languageCode).equals(name, true) ||
SpecialAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) {
return SPECIAL
}
if (TalkAliasData.valueFor(wiki.languageCode).equals(name, true) ||
TalkAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) {
return TALK
}
if (UserAliasData.valueFor(wiki.languageCode).equals(name, true) ||
UserAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) {
return USER
}
return if (UserTalkAliasData.valueFor(wiki.languageCode).equals(name, true) ||
UserTalkAliasData.valueFor(AppLanguageLookUpTable.FALLBACK_LANGUAGE_CODE).equals(name, true)) {
USER_TALK
} else MAIN
}
@JvmStatic
fun of(code: Int): Namespace {
return MAP[code]
}
}
}
| apache-2.0 | e4398c28ed91e02708289185d8a371d5 | 25.861386 | 134 | 0.60763 | 3.653872 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/edit/richtext/SuperscriptSpanEx.kt | 1 | 581 | package org.wikipedia.edit.richtext
import android.text.TextPaint
import android.text.style.MetricAffectingSpan
class SuperscriptSpanEx(override var start: Int, override var syntaxRule: SyntaxRule) :
MetricAffectingSpan(), SpanExtents {
override var end = 0
override fun updateDrawState(tp: TextPaint) {
tp.textSize = tp.textSize * 0.8f
tp.baselineShift += (tp.ascent() / 4).toInt()
}
override fun updateMeasureState(tp: TextPaint) {
tp.textSize = tp.textSize * 0.8f
tp.baselineShift += (tp.ascent() / 4).toInt()
}
}
| apache-2.0 | ae09c33200708113917ea2c7ed89d45d | 29.578947 | 87 | 0.681583 | 3.952381 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/adapter/ParcelableUserListsAdapter.kt | 1 | 5072 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <mail@vanit.as>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.bumptech.glide.RequestManager
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.contains
import de.vanita5.twittnuker.R
import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter
import de.vanita5.twittnuker.adapter.iface.ILoadMoreSupportAdapter.Companion.ITEM_VIEW_TYPE_LOAD_INDICATOR
import de.vanita5.twittnuker.adapter.iface.IUserListsAdapter
import de.vanita5.twittnuker.constant.nameFirstKey
import de.vanita5.twittnuker.model.ParcelableUserList
import de.vanita5.twittnuker.view.holder.LoadIndicatorViewHolder
import de.vanita5.twittnuker.view.holder.UserListViewHolder
class ParcelableUserListsAdapter(
context: Context, requestManager: RequestManager
) : LoadMoreSupportAdapter<RecyclerView.ViewHolder>(context, requestManager), IUserListsAdapter<List<ParcelableUserList>> {
override val showAccountsColor: Boolean = false
override val nameFirst: Boolean = preferences[nameFirstKey]
override var userListClickListener: IUserListsAdapter.UserListClickListener? = null
private val inflater: LayoutInflater = LayoutInflater.from(context)
private var data: List<ParcelableUserList>? = null
fun getData(): List<ParcelableUserList>? {
return data
}
override fun setData(data: List<ParcelableUserList>?): Boolean {
this.data = data
notifyDataSetChanged()
return true
}
private fun bindUserList(holder: UserListViewHolder, position: Int) {
holder.display(getUserList(position)!!)
}
override fun getItemCount(): Int {
val position = loadMoreIndicatorPosition
var count = userListsCount
if (position and ILoadMoreSupportAdapter.START != 0L) {
count++
}
if (position and ILoadMoreSupportAdapter.END != 0L) {
count++
}
return count
}
override fun getUserList(position: Int): ParcelableUserList? {
if (position == userListsCount) return null
return data!![position]
}
override fun getUserListId(position: Int): String? {
if (position == userListsCount) return null
return data!![position].id
}
override val userListsCount: Int
get() {
if (data == null) return 0
return data!!.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
ITEM_VIEW_TYPE_USER_LIST -> {
return createUserListViewHolder(this, inflater, parent)
}
ITEM_VIEW_TYPE_LOAD_INDICATOR -> {
val view = inflater.inflate(R.layout.list_item_load_indicator, parent, false)
return LoadIndicatorViewHolder(view)
}
}
throw IllegalStateException("Unknown view type " + viewType)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder.itemViewType) {
ITEM_VIEW_TYPE_USER_LIST -> {
bindUserList(holder as UserListViewHolder, position)
}
}
}
override fun getItemViewType(position: Int): Int {
if (position == 0 && ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition) {
return ITEM_VIEW_TYPE_LOAD_INDICATOR
}
if (position == userListsCount) {
return ITEM_VIEW_TYPE_LOAD_INDICATOR
}
return ITEM_VIEW_TYPE_USER_LIST
}
companion object {
val ITEM_VIEW_TYPE_USER_LIST = 2
fun createUserListViewHolder(adapter: IUserListsAdapter<*>,
inflater: LayoutInflater,
parent: ViewGroup): UserListViewHolder {
val view = inflater.inflate(R.layout.list_item_user_list, parent, false)
val holder = UserListViewHolder(view, adapter)
holder.setOnClickListeners()
holder.setupViewOptions()
return holder
}
}
} | gpl-3.0 | 497c9d835e887b6802b4c82b4f384ce4 | 34.725352 | 123 | 0.682177 | 4.816714 | false | false | false | false |
Popalay/Cardme | presentation/src/main/kotlin/com/popalay/cardme/utils/extensions/CommonExt.kt | 1 | 4406 | package com.popalay.cardme.utils.extensions
import android.arch.lifecycle.ViewModelProvider
import android.arch.lifecycle.ViewModelProviders
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.databinding.ViewDataBinding
import android.net.Uri
import android.nfc.NdefMessage
import android.nfc.NdefRecord
import android.support.annotation.LayoutRes
import android.support.annotation.StringRes
import android.support.customtabs.CustomTabsIntent
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.support.v4.app.ShareCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.ViewGroup
import com.popalay.cardme.R
import com.popalay.cardme.presentation.base.BaseViewModel
fun FragmentActivity.currentFragment() = supportFragmentManager.fragments?.filter { it.isVisible }?.firstOrNull()
inline fun <reified T : Fragment> AppCompatActivity.findFragmentByType() = supportFragmentManager.fragments
?.filter { it is T }
?.map { it as T }
?.firstOrNull()
fun FragmentActivity.openShareChooser(@StringRes title: Int, text: String) {
val intent = ShareCompat.IntentBuilder.from(this)
.setChooserTitle(title)
.setType("text/plain")
.setText(text)
.createChooserIntent()
if (intent.resolveActivity(this.packageManager) != null) {
this.startActivity(intent)
}
}
fun FragmentActivity.shareUsingNfc(@StringRes title: Int, text: String) {
val targetShareIntents = mutableListOf<Intent>()
val shareIntent = Intent()
shareIntent.action = Intent.ACTION_SEND
shareIntent.type = "text/plain"
val resInfos = packageManager.queryIntentActivities(shareIntent, 0)
if (!resInfos.isEmpty()) {
for (resInfo in resInfos) {
val packageName = resInfo.activityInfo.packageName
if (packageName.contains("nfc")) {
val intent = Intent()
intent.component = ComponentName(packageName, resInfo.activityInfo.name)
intent.action = Intent.ACTION_SEND
intent.type = "text/plain"
intent.putExtra(Intent.EXTRA_TEXT, text)
intent.`package` = packageName
targetShareIntents.add(intent)
}
}
if (!targetShareIntents.isEmpty()) {
val chooserIntent = Intent.createChooser(targetShareIntents.removeAt(0), getString(title))
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetShareIntents.toTypedArray())
startActivity(chooserIntent)
}
}
}
fun <T : ViewDataBinding> FragmentActivity.getDataBinding(@LayoutRes layoutId: Int
): T = DataBindingUtil.setContentView<T>(this, layoutId)
fun <T : ViewDataBinding> Fragment.getDataBinding(
inflater: LayoutInflater?,
@LayoutRes layoutId: Int,
container: ViewGroup?
): T = DataBindingUtil.inflate(inflater, layoutId, container, false)
inline fun <reified T : BaseViewModel> FragmentActivity.getViewModel(
factory: ViewModelProvider.Factory = ViewModelProviders.DefaultFactory(application)
): T = ViewModelProviders.of(this, factory).get(T::class.java)
inline fun <reified T : BaseViewModel> Fragment.getViewModel(
factory: ViewModelProvider.Factory = ViewModelProviders.DefaultFactory(activity.application)
): T = ViewModelProviders.of(this, factory).get(T::class.java)
fun Context.createNdefMessage(byteArray: ByteArray): NdefMessage {
return NdefMessage(arrayOf(NdefRecord.createMime("application/" + packageName, byteArray),
NdefRecord.createApplicationRecord(packageName)))
}
fun Fragment.openShareChooser(@StringRes title: Int, text: String) = activity.openShareChooser(title, text)
fun Context.openLink(url: Uri) {
val builder = CustomTabsIntent.Builder()
builder.setToolbarColor(ContextCompat.getColor(this, R.color.primary))
val customTabsIntent = builder.build()
customTabsIntent.launchUrl(this, url)
}
fun Context.openLink(url: String) = openLink(Uri.parse(url))
fun Boolean.ifTrue(block: () -> Unit) {
if (this) {
block()
}
}
fun Boolean.ifFalse(block: () -> Unit) {
if (!this) {
block()
}
} | apache-2.0 | 631d6d8a1330cdc65cdceaeb350d86c6 | 37.321739 | 113 | 0.724921 | 4.55636 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/androidTest/java/com/stripe/android/paymentsheet/utils/MockPaymentMethodsFactory.kt | 1 | 2169 | package com.stripe.android.paymentsheet.utils
import com.stripe.android.paymentsheet.forms.PaymentMethodRequirements
import com.stripe.android.ui.core.R
import com.stripe.android.ui.core.elements.LayoutSpec
import com.stripe.android.ui.core.forms.resources.LpmRepository
object MockPaymentMethodsFactory {
fun create(): List<LpmRepository.SupportedPaymentMethod> {
return listOf(
mockPaymentMethod(
code = "card",
displayNameResource = R.string.stripe_paymentsheet_payment_method_card,
iconResource = R.drawable.stripe_ic_paymentsheet_pm_card,
tintIconOnSelection = true
),
mockPaymentMethod(
code = "klarna",
displayNameResource = R.string.stripe_paymentsheet_payment_method_klarna,
iconResource = R.drawable.stripe_ic_paymentsheet_pm_klarna
),
mockPaymentMethod(
code = "affirm",
displayNameResource = R.string.stripe_paymentsheet_payment_method_affirm,
iconResource = R.drawable.stripe_ic_paymentsheet_pm_affirm
),
mockPaymentMethod(
code = "paypal",
displayNameResource = R.string.stripe_paymentsheet_payment_method_paypal,
iconResource = R.drawable.stripe_ic_paymentsheet_pm_paypal
)
)
}
private fun mockPaymentMethod(
code: String,
displayNameResource: Int,
iconResource: Int,
tintIconOnSelection: Boolean = false
): LpmRepository.SupportedPaymentMethod {
return LpmRepository.SupportedPaymentMethod(
code,
requiresMandate = false,
displayNameResource = displayNameResource,
iconResource = iconResource,
tintIconOnSelection = tintIconOnSelection,
requirement = PaymentMethodRequirements(
piRequirements = emptySet(),
siRequirements = emptySet(),
confirmPMFromCustomer = true
),
formSpec = LayoutSpec(items = emptyList())
)
}
}
| mit | 3928d8fc9f5be3eecfb28a7699e67bac | 37.732143 | 89 | 0.617796 | 5.491139 | false | false | false | false |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/presentation/ui/sharing/fragments/EditPrivateShareFragment.kt | 2 | 18776 | /**
* ownCloud Android client application
*
* @author masensio
* @author David A. Velasco
* @author Christian Schabesberger
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http:></http:>//www.gnu.org/licenses/>.
*/
package com.owncloud.android.presentation.ui.sharing.fragments
import android.accounts.Account
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import androidx.appcompat.widget.SwitchCompat
import androidx.core.view.isVisible
import androidx.fragment.app.DialogFragment
import com.owncloud.android.R
import com.owncloud.android.databinding.EditShareLayoutBinding
import com.owncloud.android.datamodel.OCFile
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.domain.utils.Event.EventObserver
import com.owncloud.android.extensions.parseError
import com.owncloud.android.lib.resources.shares.RemoteShare
import com.owncloud.android.lib.resources.shares.SharePermissionsBuilder
import com.owncloud.android.presentation.UIResult
import com.owncloud.android.presentation.viewmodels.sharing.OCShareViewModel
import com.owncloud.android.utils.PreferenceUtils
import org.koin.androidx.viewmodel.ext.android.viewModel
import org.koin.core.parameter.parametersOf
import timber.log.Timber
/**
* Required empty public constructor
*/
class EditPrivateShareFragment : DialogFragment() {
/** Share to show & edit, received as a parameter in construction time */
private var share: OCShare? = null
/** File bound to share, received as a parameter in construction time */
private var file: OCFile? = null
/** OC account holding the shared file, received as a parameter in construction time */
private var account: Account? = null
/**
* Reference to parent listener
*/
private var listener: ShareFragmentListener? = null
/** Listener for changes on privilege checkboxes */
private var onPrivilegeChangeListener: CompoundButton.OnCheckedChangeListener? = null
private val ocShareViewModel: OCShareViewModel by viewModel {
parametersOf(
file?.remotePath,
account?.name
)
}
private var _binding: EditShareLayoutBinding? = null
private val binding get() = _binding!!
/**
* {@inheritDoc}
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.v("onCreate")
if (arguments != null) {
file = arguments?.getParcelable(ARG_FILE)
account = arguments?.getParcelable(ARG_ACCOUNT)
share = savedInstanceState?.getParcelable(ARG_SHARE) ?: arguments?.getParcelable(ARG_SHARE)
Timber.d("Share has id ${share?.id} remoteId ${share?.remoteId}")
}
setStyle(STYLE_NO_TITLE, 0)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
Timber.v("onActivityCreated")
// To observe the changes in a just updated share
refreshPrivateShare(share?.remoteId!!)
observePrivateShareToEdit()
observePrivateShareEdition()
}
/**
* {@inheritDoc}
*/
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = EditShareLayoutBinding.inflate(inflater, container, false)
return binding.root.apply {
// Allow or disallow touches with other visible windows
filterTouchesWhenObscured = PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(context)
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.editShareTitle.text = resources.getString(R.string.share_with_edit_title, share?.sharedWithDisplayName)
// Setup layout
refreshUiFromState()
binding.closeButton.setOnClickListener { dismiss() }
}
override fun onAttach(context: Context) {
super.onAttach(context)
try {
listener = activity as ShareFragmentListener?
} catch (e: IllegalStateException) {
throw IllegalStateException(requireActivity().toString() + " must implement OnShareFragmentInteractionListener")
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
/**
* Updates the UI with the current permissions in the edited [RemoteShare]
*
*/
private fun refreshUiFromState() {
setPermissionsListening(false)
val sharePermissions = share!!.permissions
binding.canShareSwitch.isChecked = sharePermissions and RemoteShare.SHARE_PERMISSION_FLAG > 0
val anyUpdatePermission = RemoteShare.CREATE_PERMISSION_FLAG or
RemoteShare.UPDATE_PERMISSION_FLAG or
RemoteShare.DELETE_PERMISSION_FLAG
val canEdit = sharePermissions and anyUpdatePermission > 0
binding.canEditSwitch.isChecked = canEdit
if (file?.isFolder == true) {
/// TODO change areEditOptionsAvailable in order to delete !isFederated
// from checking when iOS is ready
binding.canEditCreateCheckBox.apply {
isChecked = sharePermissions and RemoteShare.CREATE_PERMISSION_FLAG > 0
isVisible = canEdit
}
binding.canEditChangeCheckBox.apply {
isChecked = sharePermissions and RemoteShare.UPDATE_PERMISSION_FLAG > 0
isVisible = canEdit
}
binding.canEditDeleteCheckBox.apply {
isChecked = sharePermissions and RemoteShare.DELETE_PERMISSION_FLAG > 0
isVisible = canEdit
}
}
setPermissionsListening(true)
}
/**
* Binds or unbinds listener for user actions to enable or disable a permission on the edited share
* to the views receiving the user events.
*
* @param enable When 'true', listener is bound to view; when 'false', it is unbound.
*/
private fun setPermissionsListening(enable: Boolean) {
if (enable && onPrivilegeChangeListener == null) {
onPrivilegeChangeListener = OnPrivilegeChangeListener()
}
val changeListener = if (enable) onPrivilegeChangeListener else null
binding.canShareSwitch.setOnCheckedChangeListener(changeListener)
binding.canEditSwitch.setOnCheckedChangeListener(changeListener)
if (file?.isFolder == true) {
binding.canEditCreateCheckBox.setOnCheckedChangeListener(changeListener)
binding.canEditChangeCheckBox.setOnCheckedChangeListener(changeListener)
binding.canEditDeleteCheckBox.setOnCheckedChangeListener(changeListener)
}
}
/**
* Listener for user actions that enable or disable a privilege
*/
private inner class OnPrivilegeChangeListener : CompoundButton.OnCheckedChangeListener {
/**
* Called by every [SwitchCompat] and [CheckBox] in the fragment to update
* the state of its associated permission.
*
* @param compound [CompoundButton] toggled by the user
* @param isChecked New switch state.
*/
override fun onCheckedChanged(compound: CompoundButton, isChecked: Boolean) {
if (!isResumed) {
// very important, setCheched(...) is called automatically during
// Fragment recreation on device rotations
return
}
/// else, getView() cannot be NULL
var subordinate: CompoundButton
when (compound.id) {
R.id.canShareSwitch -> {
Timber.v("canShareCheckBox toggled to $isChecked")
updatePermissionsToShare()
}
R.id.canEditSwitch -> {
Timber.v("canEditCheckBox toggled to $isChecked")
/// sync subordinate CheckBoxes
val isFederated = share?.shareType == ShareType.FEDERATED
if (file?.isFolder == true) {
if (isChecked) {
if (!isFederated) {
/// not federated shares -> enable all the subpermisions
for (i in sSubordinateCheckBoxIds.indices) {
//noinspection ConstantConditions, prevented in the method beginning
subordinate = view!!.findViewById(sSubordinateCheckBoxIds[i])
if (!isFederated) { // TODO delete when iOS is ready
subordinate.visibility = View.VISIBLE
}
if (!subordinate.isChecked && !file!!.isSharedWithMe) { // see (1)
toggleDisablingListener(subordinate)
}
}
} else {
/// federated share -> enable delete subpermission, as server side; TODO why?
//noinspection ConstantConditions, prevented in the method beginning
subordinate = binding.canEditDeleteCheckBox
if (!subordinate.isChecked) {
toggleDisablingListener(subordinate)
}
}
} else {
for (i in sSubordinateCheckBoxIds.indices) {
//noinspection ConstantConditions, prevented in the method beginning
subordinate = view!!.findViewById(sSubordinateCheckBoxIds[i])
subordinate.visibility = View.GONE
if (subordinate.isChecked) {
toggleDisablingListener(subordinate)
}
}
}
}
if (!(file?.isFolder == true && isChecked && file?.isSharedWithMe == true) || // see (1)
isFederated
) {
updatePermissionsToShare()
}
}
R.id.canEditCreateCheckBox -> {
Timber.v("canEditCreateCheckBox toggled to $isChecked")
syncCanEditSwitch(compound, isChecked)
updatePermissionsToShare()
}
R.id.canEditChangeCheckBox -> {
Timber.v("canEditChangeCheckBox toggled to $isChecked")
syncCanEditSwitch(compound, isChecked)
updatePermissionsToShare()
}
R.id.canEditDeleteCheckBox -> {
Timber.v("canEditDeleteCheckBox toggled to $isChecked")
syncCanEditSwitch(compound, isChecked)
updatePermissionsToShare()
}
} // updatePermissionsToShare() // see (1)
// (1) These modifications result in an exceptional UI behaviour for the case
// where the switch 'can edit' is enabled for a *reshared folder*; if the same
// behaviour was applied than for owned folder, and the user did not have full
// permissions to update the folder, an error would be reported by the server
// and the children checkboxes would be automatically hidden again
}
/**
* Sync value of "can edit" [SwitchCompat] according to a change in one of its subordinate checkboxes.
*
* If all the subordinates are disabled, "can edit" has to be disabled.
*
* If any subordinate is enabled, "can edit" has to be enabled.
*
* @param subordinateCheckBoxView Subordinate [CheckBox] that was changed.
* @param isChecked 'true' iif subordinateCheckBoxView was checked.
*/
private fun syncCanEditSwitch(subordinateCheckBoxView: View, isChecked: Boolean) {
val canEditCompound = binding.canEditSwitch
if (isChecked) {
if (!canEditCompound.isChecked) {
toggleDisablingListener(canEditCompound)
}
} else {
var allDisabled = true
run {
var i = 0
while (allDisabled && i < sSubordinateCheckBoxIds.size) {
allDisabled =
allDisabled and (sSubordinateCheckBoxIds[i] == subordinateCheckBoxView.id || !(view?.findViewById<View>(
sSubordinateCheckBoxIds[i]
) as CheckBox).isChecked)
i++
}
}
if (canEditCompound.isChecked && allDisabled) {
toggleDisablingListener(canEditCompound)
for (i in sSubordinateCheckBoxIds.indices) {
view?.findViewById<View>(sSubordinateCheckBoxIds[i])?.visibility = View.GONE
}
}
}
}
/**
* Toggle value of received [CompoundButton] granting that its change listener is not called.
*
* @param compound [CompoundButton] (switch or checkBox) to toggle without reporting to
* the change listener
*/
private fun toggleDisablingListener(compound: CompoundButton) {
compound.setOnCheckedChangeListener(null)
compound.toggle()
compound.setOnCheckedChangeListener(this)
}
}
private fun observePrivateShareToEdit() {
ocShareViewModel.privateShare.observe(
this,
EventObserver { uiResult ->
when (uiResult) {
is UIResult.Success -> {
updateShare(uiResult.data)
}
is UIResult.Error -> {}
is UIResult.Loading -> {}
}
}
)
}
private fun observePrivateShareEdition() {
ocShareViewModel.privateShareEditionStatus.observe(
this,
EventObserver { uiResult ->
when (uiResult) {
is UIResult.Error -> {
showError(getString(R.string.update_link_file_error), uiResult.error)
listener?.dismissLoading()
}
is UIResult.Loading -> {
listener?.showLoading()
}
is UIResult.Success -> {}
}
}
)
}
/**
* Updates the permissions of the [RemoteShare] according to the values set in the UI
*/
private fun updatePermissionsToShare() {
binding.privateShareErrorMessage.isVisible = false
val sharePermissionsBuilder = SharePermissionsBuilder().apply {
setSharePermission(binding.canShareSwitch.isChecked)
if (file?.isFolder == true) {
setUpdatePermission(binding.canEditChangeCheckBox.isChecked)
setCreatePermission(binding.canEditCreateCheckBox.isChecked)
setDeletePermission(binding.canEditDeleteCheckBox.isChecked)
} else {
setUpdatePermission(binding.canEditSwitch.isChecked)
}
}
val permissions = sharePermissionsBuilder.build()
ocShareViewModel.updatePrivateShare(share?.remoteId!!, permissions, account?.name!!)
}
private fun refreshPrivateShare(remoteId: String) {
ocShareViewModel.refreshPrivateShare(remoteId)
}
/**
* Updates the UI after the result of an update operation on the edited [RemoteShare] permissions.
*
*/
private fun updateShare(updatedShare: OCShare?) {
share = updatedShare
refreshUiFromState()
}
/**
* Show error when updating the private share, if any
*/
private fun showError(genericErrorMessage: String, throwable: Throwable?) {
binding.privateShareErrorMessage.apply {
text = throwable?.parseError(genericErrorMessage, resources)
isVisible = true
}
}
companion object {
/** The fragment initialization parameters */
private const val ARG_SHARE = "SHARE"
private const val ARG_FILE = "FILE"
private const val ARG_ACCOUNT = "ACCOUNT"
/** Ids of CheckBoxes depending on R.id.canEdit CheckBox */
private val sSubordinateCheckBoxIds =
intArrayOf(R.id.canEditCreateCheckBox, R.id.canEditChangeCheckBox, R.id.canEditDeleteCheckBox)
/**
* Public factory method to create new EditPrivateShareFragment instances.
*
* @param shareToEdit An [OCShare] to show and edit in the fragment
* @param sharedFile The [OCFile] bound to 'shareToEdit'
* @param account The ownCloud account holding 'sharedFile'
* @return A new instance of fragment EditPrivateShareFragment.
*/
fun newInstance(shareToEdit: OCShare, sharedFile: OCFile, account: Account): EditPrivateShareFragment {
val args = Bundle().apply {
putParcelable(ARG_SHARE, shareToEdit)
putParcelable(ARG_FILE, sharedFile)
putParcelable(ARG_ACCOUNT, account)
}
return EditPrivateShareFragment().apply { arguments = args }
}
}
}
| gpl-2.0 | 4ffa0e5bc7ea5cbb9b3ca146add1a160 | 38.861996 | 132 | 0.596858 | 5.784042 | false | false | false | false |
kittinunf/Fuel | fuel/src/main/kotlin/com/github/kittinunf/fuel/toolbox/HttpClient.kt | 1 | 13359 | package com.github.kittinunf.fuel.toolbox
import com.github.kittinunf.fuel.core.Client
import com.github.kittinunf.fuel.core.FuelError
import com.github.kittinunf.fuel.core.FuelManager
import com.github.kittinunf.fuel.core.HeaderName
import com.github.kittinunf.fuel.core.Headers
import com.github.kittinunf.fuel.core.Method
import com.github.kittinunf.fuel.core.Request
import com.github.kittinunf.fuel.core.Response
import com.github.kittinunf.fuel.core.requests.DefaultBody
import com.github.kittinunf.fuel.core.requests.isCancelled
import com.github.kittinunf.fuel.toolbox.extensions.forceMethod
import com.github.kittinunf.fuel.util.ProgressInputStream
import com.github.kittinunf.fuel.util.ProgressOutputStream
import com.github.kittinunf.fuel.util.decode
import java.io.ByteArrayInputStream
import java.io.IOException
import java.io.InputStream
import java.lang.ref.WeakReference
import java.net.HttpURLConnection
import java.net.Proxy
import javax.net.ssl.HttpsURLConnection
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.math.max
class HttpClient(
private val proxy: Proxy? = null,
var useHttpCache: Boolean = true,
var decodeContent: Boolean = true,
var hook: Client.Hook
) : Client {
override fun executeRequest(request: Request): Response {
return try {
doRequest(request)
} catch (ioe: IOException) {
hook.httpExchangeFailed(request, ioe)
throw FuelError.wrap(ioe, Response(request.url))
} catch (interrupted: InterruptedException) {
throw FuelError.wrap(interrupted, Response(request.url))
} finally {
// As per Android documentation, a connection that is not explicitly disconnected
// will be pooled and reused! So, don't close it as we need inputStream later!
// connection.disconnect()
}
}
@Throws(InterruptedException::class)
private fun ensureRequestActive(request: Request, connection: HttpURLConnection?) {
val cancelled = request.isCancelled
if (!cancelled && !Thread.currentThread().isInterrupted) {
return
}
// Flush all the pipes. This is necessary because we don't want the other end to wait for a timeout or hang.
// This interrupts the connection correctly and makes the connection available later. This does break any
// keep-alive on this particular connection
connection?.disconnect()
throw InterruptedException("[HttpClient] could not ensure Request was active: cancelled=$cancelled")
}
override suspend fun awaitRequest(request: Request): Response = suspendCoroutine { continuation ->
try {
continuation.resume(doRequest(request))
} catch (ioe: IOException) {
hook.httpExchangeFailed(request, ioe)
continuation.resumeWithException(FuelError.wrap(ioe, Response(request.url)))
} catch (interrupted: InterruptedException) {
continuation.resumeWithException(FuelError.wrap(interrupted, Response(request.url)))
}
}
@Throws(IOException::class, InterruptedException::class)
private fun doRequest(request: Request): Response {
val connection = establishConnection(request)
sendRequest(request, connection)
return retrieveResponse(request, connection)
}
@Throws(IOException::class, InterruptedException::class)
private fun sendRequest(request: Request, connection: HttpURLConnection) {
ensureRequestActive(request, connection)
connection.apply {
connectTimeout = max(request.executionOptions.timeoutInMillisecond, 0)
readTimeout = max(request.executionOptions.timeoutReadInMillisecond, 0)
if (this is HttpsURLConnection) {
sslSocketFactory = request.executionOptions.socketFactory
hostnameVerifier = request.executionOptions.hostnameVerifier
}
if (request.executionOptions.forceMethods) {
forceMethod(request.method)
// If setting method via reflection failed, invoke "coerceMethod"
// and set "X-HTTP-Method-Override" header
if (this.requestMethod !== request.method.value) {
this.requestMethod = coerceMethod(request.method).value
this.setRequestProperty("X-HTTP-Method-Override", request.method.value)
}
} else {
requestMethod = coerceMethod(request.method).value
if (request.method.value == "PATCH") {
setRequestProperty("X-HTTP-Method-Override", request.method.value)
}
}
doInput = true
useCaches = request.executionOptions.useHttpCache ?: useHttpCache
instanceFollowRedirects = false
request.headers.transformIterate(
{ key, values -> setRequestProperty(key, values) },
{ key, value -> addRequestProperty(key, value) }
)
// By default, the Android implementation of HttpURLConnection requests that servers use gzip compression
// and it automatically decompresses the data for callers of URLConnection.getInputStream().
// The Content-Encoding and Content-Length response headers are cleared in this case. Gzip compression can
// be disabled by setting the acceptable encodings in the request header:
//
// .header(Headers.ACCEPT_ENCODING, "identity")
//
// However, on the JVM, this behaviour might be different. Content-Encoding SHOULD NOT be used, in HTTP/1x
// to act as Transfer Encoding. In HTTP/2, Transfer-Encoding is not part of the Connection field and should
// not be injected here. HttpURLConnection is only HTTP/1x, whereas Java 9 introduces a new HttpClient for
// HTTP/2.
//
// This adds the TE header for HTTP/1 connections, and automatically decodes it using decodeTransfer.
// The TE (Accept Transfer Encoding) can only be one of these, should match decodeTransfer.
setRequestProperty(
Headers.ACCEPT_TRANSFER_ENCODING,
Headers.collapse(HeaderName(Headers.ACCEPT_TRANSFER_ENCODING), SUPPORTED_DECODING)
)
hook.preConnect(connection, request)
setDoOutput(connection, request.method)
setBodyIfDoOutput(connection, request)
}
// Ensure that we are connected after this point. Note that getOutputStream above will
// also connect and exchange HTTP messages.
connection.connect()
}
@Throws(IOException::class, InterruptedException::class)
private fun retrieveResponse(request: Request, connection: HttpURLConnection): Response {
ensureRequestActive(request, connection)
hook.postConnect(request)
val headers = Headers.from(connection.headerFields)
val transferEncoding = headers[Headers.TRANSFER_ENCODING].flatMap { it.split(',') }.map { it.trim() }
val contentEncoding = headers[Headers.CONTENT_ENCODING].lastOrNull()
var contentLength = headers[Headers.CONTENT_LENGTH].lastOrNull()?.toLong()
val shouldDecode = (request.executionOptions.decodeContent ?: decodeContent) && contentEncoding != null && contentEncoding != "identity"
if (shouldDecode) {
// `decodeContent` decodes the response, so the final response has no more `Content-Encoding`
headers.remove(Headers.CONTENT_ENCODING)
// URLConnection.getContentLength() returns the number of bytes transmitted and cannot be used to predict
// how many bytes can be read from URLConnection.getInputStream() for compressed streams. Therefore if the
// stream will be decoded, the length becomes unknown
//
headers.remove(Headers.CONTENT_LENGTH)
contentLength = null
}
// `decodeTransfer` decodes the response, so the final response has no more Transfer-Encoding
headers.remove(Headers.TRANSFER_ENCODING)
// [RFC 7230, 3.3.2](https://tools.ietf.org/html/rfc7230#section-3.3.2)
//
// When a message does not have a Transfer-Encoding header field, a
// Content-Length header field can provide the anticipated size, as a
// decimal number of octets, for a potential payload body.
//
// A sender MUST NOT send a Content-Length header field in any message
// that contains a Transfer-Encoding header field.
//
// [RFC 7230, 3.3.3](https://tools.ietf.org/html/rfc7230#section-3.3.3)
//
// Any 2xx (Successful) response to a CONNECT request implies that
// the connection will become a tunnel immediately after the empty
// line that concludes the header fields. A client MUST ignore any
// Content-Length or Transfer-Encoding header fields received in
// such a message.
//
if (transferEncoding.any { encoding -> encoding.isNotBlank() && encoding != "identity" }) {
headers.remove(Headers.CONTENT_LENGTH)
contentLength = -1
}
val contentStream = dataStream(request, connection)?.decode(transferEncoding) ?: ByteArrayInputStream(ByteArray(0))
val inputStream = if (shouldDecode && contentEncoding != null) contentStream.decode(contentEncoding) else contentStream
val cancellationConnection = WeakReference<HttpURLConnection>(connection)
val progressStream = ProgressInputStream(
inputStream, onProgress = { readBytes ->
request.executionOptions.responseProgress(readBytes, contentLength ?: readBytes)
ensureRequestActive(request, cancellationConnection.get())
}
)
// The input and output streams returned by connection are not buffered. In order to give consistent progress
// reporting, by means of flushing, the input stream here is buffered.
return Response(
url = request.url,
headers = headers,
contentLength = contentLength ?: -1,
statusCode = connection.responseCode,
responseMessage = connection.responseMessage.orEmpty(),
body = DefaultBody.from(
{ progressStream.buffered(FuelManager.progressBufferSize) },
{ contentLength ?: -1 }
)
)
}
private fun dataStream(request: Request, connection: HttpURLConnection): InputStream? = try {
hook.interpretResponseStream(request, connection.inputStream)?.buffered()
} catch (_: IOException) {
hook.interpretResponseStream(request, connection.errorStream)?.buffered()
}
private fun establishConnection(request: Request): HttpURLConnection {
val url = request.url
val connection = proxy?.let { url.openConnection(it) } ?: url.openConnection()
return connection as HttpURLConnection
}
private fun setBodyIfDoOutput(connection: HttpURLConnection, request: Request) {
val body = request.body
if (!connection.doOutput || body.isEmpty()) {
return
}
val contentLength = body.length
if (contentLength != null && contentLength != -1L) {
// The content has a known length, so no need to chunk
connection.setFixedLengthStreamingMode(contentLength.toLong())
} else {
// The content doesn't have a known length, so turn it into chunked
connection.setChunkedStreamingMode(4096)
}
val noProgressHandler = request.executionOptions.requestProgress.isNotSet()
val outputStream = if (noProgressHandler) {
// No need to report progress, let's just send the payload without buffering
connection.outputStream
} else {
// The input and output streams returned by connection are not buffered. In order to give consistent progress
// reporting, by means of flushing, the output stream here is buffered.
val totalBytes = if ((contentLength ?: -1L).toLong() > 0) { contentLength!!.toLong() } else { null }
ProgressOutputStream(
connection.outputStream,
onProgress = { writtenBytes ->
request.executionOptions.requestProgress(writtenBytes, totalBytes ?: writtenBytes)
ensureRequestActive(request, connection)
}
).buffered(FuelManager.progressBufferSize)
}
body.writeTo(outputStream)
connection.outputStream.flush()
}
private fun setDoOutput(connection: HttpURLConnection, method: Method) = when (method) {
Method.GET, Method.HEAD, Method.OPTIONS, Method.TRACE -> connection.doOutput = false
Method.DELETE, Method.POST, Method.PUT, Method.PATCH -> connection.doOutput = true
}
companion object {
private val SUPPORTED_DECODING = listOf("gzip", "deflate; q=0.5")
private fun coerceMethod(method: Method) = if (method == Method.PATCH) Method.POST else method
}
}
| mit | 9a343afa7ef51df46d07058f1d797a27 | 46.204947 | 144 | 0.664646 | 5.108604 | false | false | false | false |
TeamWizardry/LibrarianLib | modules/glitter/src/test/kotlin/com/teamwizardry/librarianlib/glitter/test/systems/ForwardFacingSystem.kt | 1 | 2271 | package com.teamwizardry.librarianlib.glitter.test.systems
import com.teamwizardry.librarianlib.glitter.bindings.ConstantBinding
import com.teamwizardry.librarianlib.glitter.modules.BasicPhysicsUpdateModule
import com.teamwizardry.librarianlib.glitter.modules.SpriteRenderModule
import net.minecraft.entity.Entity
import net.minecraft.util.Identifier
object ForwardFacingSystem : TestSystem(Identifier("liblib-glitter-test:forward_facing")) {
override fun configure() {
val position = bind(3)
val previousPosition = bind(3)
val velocity = bind(3)
val color = bind(4)
updateModules.add(
BasicPhysicsUpdateModule(
position = position,
previousPosition = previousPosition,
velocity = velocity,
enableCollision = true,
gravity = ConstantBinding(0.02),
bounciness = ConstantBinding(0.8),
friction = ConstantBinding(0.02),
damping = ConstantBinding(0.01)
)
)
renderModules.add(
SpriteRenderModule.build(
Identifier("minecraft", "textures/item/clay_ball.png"),
position
)
.previousPosition(previousPosition)
.color(color)
.size(0.2)
.facingVector(velocity)
.build()
)
}
override fun spawn(player: Entity) {
val eyePos = player.getCameraPosVec(1f)
val look = player.rotationVector
val spawnDistance = 2
val spawnVelocity = 0.2
this.addParticle(
200,
// position
eyePos.x + look.x * spawnDistance,
eyePos.y + look.y * spawnDistance,
eyePos.z + look.z * spawnDistance,
// previous position
eyePos.x + look.x * spawnDistance,
eyePos.y + look.y * spawnDistance,
eyePos.z + look.z * spawnDistance,
// velocity
look.x * spawnVelocity,
look.y * spawnVelocity,
look.z * spawnVelocity,
// color
Math.random(),
Math.random(),
Math.random(),
1.0
)
}
} | lgpl-3.0 | fd4014d31381b6d11965bb104737e898 | 31.457143 | 91 | 0.562748 | 4.991209 | false | false | false | false |
jorjoluiso/QuijoteLui | src/main/kotlin/com/quijotelui/model/RetencionDetalle.kt | 1 | 1111 | package com.quijotelui.model
import org.hibernate.annotations.Immutable
import java.math.BigDecimal
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table
@Entity
@Immutable
@Table(name = "v_ele_retenciones_detalle")
class RetencionDetalle {
@Id
@Column(name = "id")
var id : Long? = null
@Column(name = "codigo")
var codigo : String? = null
@Column(name = "numero")
var numero : String? = null
@Column(name = "tipo")
var tipo : String? = null
@Column(name = "codigo_sri")
var codigoSRI : String? = null
@Column(name = "base_imponible")
val baseImponible : BigDecimal? = null
@Column(name = "porcentaje")
val porcentaje : BigDecimal? = null
@Column(name = "valor_retenido")
val valorRetenido : BigDecimal? = null
@Column(name = "tipo_comprobante")
var tipoComprobante : String? = null
@Column(name = "numero_comprobante")
var numeroComprobante : String? = null
@Column(name = "fecha_comprobante")
var fechaComprobante : String? = null
} | gpl-3.0 | c8f350e8d530ad2656da8c03c1f0e0fb | 21.24 | 42 | 0.673267 | 3.583871 | false | false | false | false |
androidx/androidx | room/room-compiler/src/main/kotlin/androidx/room/parser/expansion/ProjectionExpander.kt | 3 | 10104 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.parser.expansion
import androidx.annotation.VisibleForTesting
import androidx.room.parser.ParsedQuery
import androidx.room.parser.SqlParser
import androidx.room.processor.QueryRewriter
import androidx.room.solver.query.result.PojoRowAdapter
import androidx.room.solver.query.result.QueryResultAdapter
import androidx.room.verifier.QueryResultInfo
import androidx.room.vo.EmbeddedField
import androidx.room.vo.Entity
import androidx.room.vo.EntityOrView
import androidx.room.vo.Field
import androidx.room.vo.Pojo
import androidx.room.vo.columnNames
import java.util.Locale
/**
* Interprets and rewrites SQL queries in the context of the provided entities and views such that
* star projection (select *) turn into explicit column lists and embedded fields are re-named to
* avoid conflicts in the response data set.
*/
class ProjectionExpander(
private val tables: List<EntityOrView>
) : QueryRewriter {
private class IdentifierMap<V> : HashMap<String, V>() {
override fun put(key: String, value: V): V? {
return super.put(key.lowercase(Locale.ENGLISH), value)
}
override fun get(key: String): V? {
return super.get(key.lowercase(Locale.ENGLISH))
}
}
/**
* Rewrites the specified [query] in the context of the provided [pojo]. Expanding its start
* projection ('SELECT *') and converting its named binding templates to positional
* templates (i.e. ':VVV' to '?').
*/
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
fun interpret(
query: ParsedQuery,
pojo: Pojo?
) = interpret(
query = ExpandableSqlParser.parse(query.original).also {
it.resultInfo = query.resultInfo
},
pojo = pojo
)
override fun rewrite(
query: ParsedQuery,
resultAdapter: QueryResultAdapter
): ParsedQuery {
if (resultAdapter.rowAdapters.isEmpty()) {
return query
}
// Don't know how to expand when multiple POJO types are created from the same row.
if (resultAdapter.rowAdapters.size > 1) {
return query
}
val rowAdapter = resultAdapter.rowAdapters.single()
return if (rowAdapter is PojoRowAdapter) {
interpret(
query = ExpandableSqlParser.parse(query.original),
pojo = rowAdapter.pojo
).let {
val reParsed = SqlParser.parse(it)
if (reParsed.errors.isEmpty()) {
reParsed
} else {
query // return original, expansion somewhat failed
}
}
} else {
query
}
}
private fun interpret(
query: ExpandableParsedQuery,
pojo: Pojo?
): String {
val queriedTableNames = query.tables.map { it.name }
return query.sections.joinToString("") { section ->
when (section) {
is ExpandableSection.Text -> section.text
is ExpandableSection.BindVar -> "?"
is ExpandableSection.Newline -> "\n"
is ExpandableSection.Projection -> {
if (pojo == null) {
section.text
} else {
interpretProjection(query, section, pojo, queriedTableNames)
}
}
}
}
}
private fun interpretProjection(
query: ExpandableParsedQuery,
section: ExpandableSection.Projection,
pojo: Pojo,
queriedTableNames: List<String>
): String {
val aliasToName = query.tables
.map { (name, alias) -> alias to name }
.toMap(IdentifierMap())
val nameToAlias = query.tables
.groupBy { it.name.lowercase(Locale.ENGLISH) }
.filter { (_, pairs) -> pairs.size == 1 }
.map { (name, pairs) -> name to pairs.first().alias }
.toMap(IdentifierMap())
return when (section) {
is ExpandableSection.Projection.All -> {
expand(
pojo = pojo,
ignoredColumnNames = query.explicitColumns,
// The columns come directly from the specified table.
// We should not prepend the prefix-dot to the columns.
shallow = findEntityOrView(pojo)?.tableName in queriedTableNames,
nameToAlias = nameToAlias,
resultInfo = query.resultInfo
)
}
is ExpandableSection.Projection.Table -> {
val embedded = findEmbeddedField(pojo, section.tableAlias)
if (embedded != null) {
expandEmbeddedField(
embedded = embedded,
table = findEntityOrView(embedded.pojo),
shallow = false,
tableToAlias = nameToAlias
).joinToString(", ")
} else {
val tableName =
aliasToName[section.tableAlias] ?: section.tableAlias
val table = tables.find { it.tableName == tableName }
pojo.fields.filter { field ->
field.parent == null &&
field.columnName !in query.explicitColumns &&
table?.columnNames?.contains(field.columnName) == true
}.joinToString(", ") { field ->
"`${section.tableAlias}`.`${field.columnName}`"
}
}
}
}
}
private fun findEntityOrView(pojo: Pojo): EntityOrView? {
return tables.find { it.typeName == pojo.typeName }
}
private fun findEmbeddedField(
pojo: Pojo,
tableAlias: String
): EmbeddedField? {
// Try to find by the prefix.
val matchByPrefix = pojo.embeddedFields.find { it.prefix == tableAlias }
if (matchByPrefix != null) {
return matchByPrefix
}
// Try to find by the table name.
return pojo.embeddedFields.find {
it.prefix.isEmpty() &&
findEntityOrView(it.pojo)?.tableName == tableAlias
}
}
private fun expand(
pojo: Pojo,
ignoredColumnNames: List<String>,
shallow: Boolean,
nameToAlias: Map<String, String>,
resultInfo: QueryResultInfo?
): String {
val table = findEntityOrView(pojo)
return (
pojo.embeddedFields.flatMap {
expandEmbeddedField(it, findEntityOrView(it.pojo), shallow, nameToAlias)
} + pojo.fields.filter { field ->
field.parent == null &&
field.columnName !in ignoredColumnNames &&
(resultInfo == null || resultInfo.hasColumn(field.columnName))
}.map { field ->
if (table != null && table is Entity) {
// Should not happen when defining a view
val tableAlias = nameToAlias[table.tableName.lowercase(Locale.ENGLISH)]
?: table.tableName
"`$tableAlias`.`${field.columnName}` AS `${field.columnName}`"
} else {
"`${field.columnName}`"
}
}
).joinToString(", ")
}
private fun QueryResultInfo.hasColumn(columnName: String): Boolean {
return columns.any { column -> column.name == columnName }
}
private fun expandEmbeddedField(
embedded: EmbeddedField,
table: EntityOrView?,
shallow: Boolean,
tableToAlias: Map<String, String>
): List<String> {
val pojo = embedded.pojo
return if (table != null) {
if (embedded.prefix.isNotEmpty()) {
table.fields.map { field ->
if (shallow) {
"`${embedded.prefix}${field.columnName}`"
} else {
"`${embedded.prefix}`.`${field.columnName}` " +
"AS `${embedded.prefix}${field.columnName}`"
}
}
} else {
table.fields.map { field ->
if (shallow) {
"`${field.columnName}`"
} else {
val tableAlias = tableToAlias[table.tableName] ?: table.tableName
"`$tableAlias`.`${field.columnName}` AS `${field.columnName}`"
}
}
}
} else {
if (!shallow &&
embedded.prefix.isNotEmpty() &&
embedded.prefix in tableToAlias.values
) {
pojo.fields.map { field ->
"`${embedded.prefix}`.`${field.columnNameWithoutPrefix(embedded.prefix)}` " +
"AS `${field.columnName}`"
}
} else {
pojo.fields.map { field ->
"`${field.columnName}`"
}
}
}
}
private fun Field.columnNameWithoutPrefix(prefix: String): String {
return if (columnName.startsWith(prefix)) {
columnName.substring(prefix.length)
} else {
columnName
}
}
}
| apache-2.0 | e6f2e2a6c737da2c74fca2f893590e8c | 36.010989 | 98 | 0.54226 | 5.219008 | false | false | false | false |
androidx/androidx | appcompat/appcompat/src/androidTest/java/androidx/appcompat/app/NightModeRtlTestUtilsRegressionTestCase.kt | 3 | 3580 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.appcompat.app
import android.content.res.Configuration
import android.text.TextUtils
import androidx.appcompat.app.NightModeCustomAttachBaseContextActivity.CUSTOM_FONT_SCALE
import androidx.appcompat.app.NightModeCustomAttachBaseContextActivity.CUSTOM_LOCALE
import androidx.appcompat.testutils.NightModeActivityTestRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.Locale
/**
* This is one approach to customizing Activity configuration that's used in google3.
* <p>
*
*/
@SdkSuppress(minSdkVersion = 16)
@MediumTest
@RunWith(AndroidJUnit4::class)
class NightModeRtlTestUtilsRegressionTestCase {
private var restoreConfig: (() -> Unit)? = null
@get:Rule
val activityRule = NightModeActivityTestRule(
NightModeCustomAttachBaseContextActivity::class.java,
initialTouchMode = false,
launchActivity = false
)
@Suppress("DEPRECATION")
@Before
fun setup() {
// Duplicated from the Google Calendar app's RtlTestUtils.java
val context = InstrumentationRegistry.getInstrumentation().targetContext
val resources = context.resources
val locale = CUSTOM_LOCALE
val configuration = resources.configuration
// Preserve initial state for later.
val initialConfig = Configuration(configuration)
val initialLocale = Locale.getDefault()
restoreConfig = {
Locale.setDefault(initialLocale)
resources.updateConfiguration(initialConfig, resources.displayMetrics)
}
// Set up the custom state.
configuration.fontScale = CUSTOM_FONT_SCALE
configuration.setLayoutDirection(locale)
configuration.setLocale(locale)
Locale.setDefault(locale)
resources.updateConfiguration(configuration, resources.displayMetrics)
// Launch the activity last.
activityRule.launchActivity(null)
}
@After
fun teardown() {
// Restore the initial state.
restoreConfig?.invoke()
}
@Test
@Suppress("DEPRECATION")
fun testLocaleIsMaintained() {
// Check that the custom configuration properties are maintained
val config = activityRule.activity.resources.configuration
assertEquals(CUSTOM_LOCALE, config.locale)
assertEquals(TextUtils.getLayoutDirectionFromLocale(CUSTOM_LOCALE), config.layoutDirection)
}
@Test
fun testFontScaleIsMaintained() {
// Check that the custom configuration properties are maintained
val config = activityRule.activity.resources.configuration
assertEquals(CUSTOM_FONT_SCALE, config.fontScale)
}
}
| apache-2.0 | aad70702947b81952303a16b5733f6db | 33.757282 | 99 | 0.735754 | 4.877384 | false | true | false | false |
coffeemakr/OST | lib/sbb/src/main/java/ch/unstable/lib/sbb/auth/AuthInterceptor.kt | 1 | 2278 | package ch.unstable.lib.sbb.auth
import android.util.Base64
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.Util.UTF_8
import java.text.SimpleDateFormat
import java.util.*
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
class AuthInterceptor(private val dateSource: DateSource) : Interceptor {
constructor() : this(DefaultDateSource())
private val userAgent = run {
val versionName = "10.6.0"
val androidVersion = "9"
val deviceName = "Google;Android SDK built for x86"
"SBBmobile/flavorprodRelease-$versionName-RELEASE Android/$androidVersion ($deviceName)"
}
private val token = UUID.randomUUID().toString()
private val macKey: SecretKeySpec = SecretKeySpec(Keys.macKey.toByteArray(UTF_8), "HmacSHA1")
private fun createSignature(date: String, path: String): String {
return Mac.getInstance("HmacSHA1").also {
it.init(macKey)
it.update(path.toByteArray(UTF_8))
it.update(date.toByteArray(UTF_8))
}.doFinal().let { Base64.encodeToString(it, Base64.NO_WRAP) }
}
fun createNewRequest(original: Request): Request {
val date = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(dateSource.currentDate)
val url = original.url()
val signature = createSignature(date, url.encodedPath())
// for unknown reasons the path needs to be url-encoded again AFTER calculating the
// signature..
val doubleEncodedUrl = original.url().newBuilder()
.encodedPath("/")
.also {
url.encodedPathSegments().forEach {segment ->
it.addPathSegment(segment)
}
}.build()
return original.newBuilder()
.url(doubleEncodedUrl)
.addHeader("X-API-AUTHORIZATION", signature)
.addHeader("X-API-DATE", date)
.addHeader("X-APP-TOKEN", token)
.addHeader("User-Agent", userAgent)
.build()
}
override fun intercept(chain: Interceptor.Chain): Response {
val request = createNewRequest(chain.request())
return chain.proceed(request)
}
}
| gpl-3.0 | 848c3c518f119f7a1d6b3b61d3ee7bc8 | 33 | 97 | 0.63345 | 4.510891 | false | false | false | false |
google/android-auto-companion-android | trustagent/tests/unit/src/com/google/android/libraries/car/trustagent/AssociationManagerMissingBluetoothPermissionsTest.kt | 1 | 3859 | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent
import android.Manifest.permission
import android.app.Activity
import android.content.Context
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.rule.GrantPermissionRule
import com.google.android.libraries.car.trustagent.testutils.Base64CryptoHelper
import com.google.common.truth.Truth.assertThat
import com.google.common.util.concurrent.MoreExecutors.directExecutor
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Collection of unit tests for [AssociationManager] where Bluetooth permissions are not granted.
*/
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class AssociationManagerMissingBluetoothPermissionsTest {
// Grant only non-Bluetooth permissions.
@get:Rule
val grantPermissionRule: GrantPermissionRule =
GrantPermissionRule.grant(
permission.ACCESS_FINE_LOCATION,
permission.ACCESS_BACKGROUND_LOCATION,
)
private val testDispatcher = UnconfinedTestDispatcher()
private val context = ApplicationProvider.getApplicationContext<Context>()
private lateinit var database: ConnectedCarDatabase
private lateinit var bleManager: FakeBleManager
private lateinit var associationManager: AssociationManager
private lateinit var associationCallback: AssociationManager.AssociationCallback
@Before
fun setUp() {
// Using directExecutor to ensure that all operations happen on the main thread and allows for
// tests to wait until the operations are done before continuing. Without this, operations can
// leak and interfere between tests. See b/153095973 for details.
database =
Room.inMemoryDatabaseBuilder(context, ConnectedCarDatabase::class.java)
.allowMainThreadQueries()
.setQueryExecutor(directExecutor())
.build()
val associatedCarManager = AssociatedCarManager(context, database, Base64CryptoHelper())
bleManager = spy(FakeBleManager())
associationCallback = mock()
associationManager =
AssociationManager(context, associatedCarManager, bleManager).apply {
registerAssociationCallback(associationCallback)
coroutineContext = testDispatcher
}
}
@After
fun after() {
database.close()
}
@Test
fun startSppDiscovery_returnsFalse() {
bleManager.isEnabled = true
assertThat(associationManager.startSppDiscovery()).isFalse()
assertThat(associationManager.isSppDiscoveryStarted).isFalse()
}
@Test
fun startCdmDiscovery_returnsFalse() {
associationManager.isSppEnabled = false
val discoveryRequest = DiscoveryRequest.Builder(Activity()).build()
assertThat(associationManager.startCdmDiscovery(discoveryRequest, mock())).isFalse()
}
@Test
fun associate_notifiesCallbackOfFailure() {
associationManager.associate(mock<DiscoveredCar>())
verify(associationCallback).onAssociationFailed()
}
}
| apache-2.0 | d317406c074208514eabdee1458807df | 34.40367 | 98 | 0.783364 | 5.031291 | false | true | false | false |
EmmyLua/IntelliJ-EmmyLua | src/main/java/com/tang/intellij/lua/debugger/emmy/value/LuaXValue.kt | 2 | 6458 | /*
* Copyright (c) 2017. tangzx(love.tangzx@qq.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.debugger.emmy.value
import com.intellij.icons.AllIcons
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.*
import com.tang.intellij.lua.debugger.LuaXBoolPresentation
import com.tang.intellij.lua.debugger.LuaXNumberPresentation
import com.tang.intellij.lua.debugger.LuaXStringPresentation
import com.tang.intellij.lua.debugger.emmy.EmmyDebugStackFrame
import com.tang.intellij.lua.debugger.emmy.LuaValueType
import com.tang.intellij.lua.debugger.emmy.VariableValue
import com.tang.intellij.lua.lang.LuaIcons
import java.util.*
abstract class LuaXValue(val value: VariableValue) : XValue() {
companion object {
fun create(v: VariableValue, frame: EmmyDebugStackFrame): LuaXValue {
return when(v.valueTypeValue) {
LuaValueType.TSTRING -> StringXValue(v)
LuaValueType.TNUMBER -> NumberXValue(v)
LuaValueType.TBOOLEAN -> BoolXValue(v)
LuaValueType.TUSERDATA,
LuaValueType.TTABLE -> TableXValue(v, frame)
LuaValueType.GROUP -> GroupXValue(v, frame)
else -> AnyXValue(v)
}
}
}
val name: String get() {
return value.nameValue
}
var parent: LuaXValue? = null
}
private object VariableComparator : Comparator<VariableValue> {
override fun compare(o1: VariableValue, o2: VariableValue): Int {
val w1 = if (o1.fake) 0 else 1
val w2 = if (o2.fake) 0 else 1
if (w1 != w2)
return w1.compareTo(w2)
return o1.nameValue.compareTo(o2.nameValue)
}
}
class StringXValue(v: VariableValue) : LuaXValue(v) {
override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) {
xValueNode.setPresentation(null, LuaXStringPresentation(value.value), false)
}
}
class NumberXValue(v: VariableValue) : LuaXValue(v) {
override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) {
xValueNode.setPresentation(null, LuaXNumberPresentation(value.value), false)
}
}
class BoolXValue(val v: VariableValue) : LuaXValue(v) {
override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) {
xValueNode.setPresentation(null, LuaXBoolPresentation(v.value), false)
}
}
class AnyXValue(val v: VariableValue) : LuaXValue(v) {
override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) {
xValueNode.setPresentation(null, v.valueTypeName, v.value, false)
}
}
class GroupXValue(v: VariableValue, val frame: EmmyDebugStackFrame) : LuaXValue(v) {
private val children = mutableListOf<LuaXValue>()
init {
value.children?.
sortedWith(VariableComparator)?.
forEach {
children.add(create(it, frame))
}
}
override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) {
xValueNode.setPresentation(AllIcons.Nodes.UpLevel, value.valueTypeName, value.value, true)
}
override fun computeChildren(node: XCompositeNode) {
val cl = XValueChildrenList()
children.forEach {
it.parent = this
cl.add(it.name, it)
}
node.addChildren(cl, true)
}
}
class TableXValue(v: VariableValue, val frame: EmmyDebugStackFrame) : LuaXValue(v) {
private val children = mutableListOf<LuaXValue>()
init {
value.children?.
sortedWith(VariableComparator)?.
forEach {
children.add(create(it, frame))
}
}
override fun computePresentation(xValueNode: XValueNode, place: XValuePlace) {
var icon = AllIcons.Json.Object
if (value.valueTypeName == "C#") {
icon = LuaIcons.CSHARP
}
else if (value.valueTypeName == "C++") {
icon = LuaIcons.CPP
}
xValueNode.setPresentation(icon, value.valueTypeName, value.value, true)
}
override fun computeChildren(node: XCompositeNode) {
val ev = this.frame.evaluator
if (ev != null) {
ev.eval(evalExpr, value.cacheId, object : XDebuggerEvaluator.XEvaluationCallback {
override fun errorOccurred(err: String) {
node.setErrorMessage(err)
}
override fun evaluated(value: XValue) {
if (value is TableXValue) {
val cl = XValueChildrenList()
children.clear()
children.addAll(value.children)
children.forEach {
it.parent = this@TableXValue
cl.add(it.name, it)
}
node.addChildren(cl, true)
}
else { // todo: table is nil?
node.setErrorMessage("nil")
}
}
}, 2)
}
else super.computeChildren(node)
}
private val evalExpr: String
get() {
var name = name
val properties = ArrayList<String>()
var parent = this.parent
while (parent != null) {
if (!parent.value.fake) {
properties.add(name)
name = parent.name
}
parent = parent.parent
}
val sb = StringBuilder(name)
for (i in properties.indices.reversed()) {
val parentName = properties[i]
if (parentName.startsWith("["))
sb.append(parentName)
else
sb.append(String.format("[\"%s\"]", parentName))
}
return sb.toString()
}
} | apache-2.0 | 3cf08ee91921826ef514c50c95009b47 | 33.540107 | 98 | 0.605141 | 4.622763 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | wordpress-shortcodes/src/main/java/org/wordpress/aztec/plugins/shortcodes/VideoShortcodePlugin.kt | 1 | 4304 | package org.wordpress.aztec.plugins.shortcodes
import org.wordpress.aztec.plugins.shortcodes.extensions.ATTRIBUTE_VIDEOPRESS_HIDDEN_ID
import org.wordpress.aztec.plugins.shortcodes.extensions.ATTRIBUTE_VIDEOPRESS_HIDDEN_SRC
import org.wordpress.aztec.plugins.html2visual.IHtmlPreprocessor
import org.wordpress.aztec.plugins.shortcodes.utils.GutenbergUtils
import org.wordpress.aztec.plugins.visual2html.IHtmlPostprocessor
class VideoShortcodePlugin : IHtmlPreprocessor, IHtmlPostprocessor {
private val TAG = "video"
private val TAG_VIDEOPRESS_SHORTCODE = "wpvideo"
override fun beforeHtmlProcessed(source: String): String {
if (GutenbergUtils.contentContainsGutenbergBlocks(source)) return source
var newSource = source.replace(Regex("(?<!\\[)\\[$TAG([^\\]]*)\\](?!\\])"), "<$TAG$1 />")
newSource = newSource.replace(Regex("(?<!\\[)\\[$TAG_VIDEOPRESS_SHORTCODE([^\\]]*)\\](?!\\])"), { it -> fromVideoPressShortCodeToHTML(it) })
return newSource
}
override fun onHtmlProcessed(source: String): String {
if (GutenbergUtils.contentContainsGutenbergBlocks(source)) {
// From https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video
// > Tag omission None, both the starting and ending tag are mandatory.
return StringBuilder(source)
.replace(Regex("(<$TAG[^>]*?)(\\s*/>)"), "\$1></$TAG>")
}
return StringBuilder(source)
.replace(Regex("<$TAG([^>]*(?<! )) */>"), { it -> fromHTMLToShortcode(it) })
.replace(Regex("<$TAG([^>]*(?<! )) *></$TAG>"), { it -> fromHTMLToShortcode(it) })
}
/**
* This function is used to convert VideoPress shortcode to HTML video.
* Called by `beforeHtmlProcessed`.
*
* For example, a shortcode like the following
* `[wpvideo OcobLTqC w=640 h=400 autoplay=true html5only=true3]` will be converted to
* `<video videopress_hidden_id=OcobLTqC w=640 h=400 autoplay=true html5only=true3>
*/
private fun fromVideoPressShortCodeToHTML(source: MatchResult): String {
val match = source.groupValues.get(1)
val splittedMatch = match.split(" ")
val attributesBuilder = StringBuilder()
attributesBuilder.append("<$TAG ")
splittedMatch.forEach {
if (!it.isBlank()) {
if (it.contains('=')) {
attributesBuilder.append(it)
} else {
// This is the videopress ID
attributesBuilder.append("$ATTRIBUTE_VIDEOPRESS_HIDDEN_ID=" + it)
}
attributesBuilder.append(' ')
}
}
attributesBuilder.append(" />")
return attributesBuilder.toString()
}
/**
* This function is used to convert HTML video tag to the correct video shortcode.
* At the moment standard WordPress `video` shortcodes and VideoPress `wpvideo` shortcodes are supported.
*/
private fun fromHTMLToShortcode(source: MatchResult): String {
val match = source.groupValues.get(1)
val splittedMatch = match.split(" ")
val attributesBuilder = StringBuilder()
var isVideoPress = false
splittedMatch.forEach {
if (!it.isBlank()) {
if (it.contains(ATTRIBUTE_VIDEOPRESS_HIDDEN_ID)) {
// This is the videopress ID attribute
val splitted = it.split("=")
if (splitted.size == 2) {
// just make sure there is a correct ID
attributesBuilder.append(splitted[1].replace("\"", ""))
isVideoPress = true
}
} else if (it.contains(ATTRIBUTE_VIDEOPRESS_HIDDEN_SRC)) {
// nope - do nothing. It's just used to keep a reference to the real src of the video,
// and use it to play the video in the apps
} else {
attributesBuilder.append(it)
}
attributesBuilder.append(' ')
}
}
val shotcodeTag = if (isVideoPress) TAG_VIDEOPRESS_SHORTCODE else TAG
return "[$shotcodeTag " + attributesBuilder.toString().trim() + "]"
}
}
| mpl-2.0 | 5e43e4b51330e35f14669a393c0a4a33 | 43.371134 | 148 | 0.594796 | 4.618026 | false | false | false | false |
hpedrorodrigues/GZMD | app/src/main/kotlin/com/hpedrorodrigues/gzmd/constant/PreferenceKey.kt | 1 | 899 | /*
* Copyright 2016 Pedro Rodrigues
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hpedrorodrigues.gzmd.constant
object PreferenceKey {
val ASK_TO_EXIT = "close_app"
val ENABLE_AUTO_SCROLL = "enable_auto_scroll"
val NIGHT_MODE = "night_mode"
val KEEP_SCREEN_ON = "keep_screen_on"
val SCROLL_SPEED = "scroll_speed"
val TEXT_SIZE = "text_size"
} | apache-2.0 | b3eaee9b69dc0c2c0e943fd6542af53b | 32.333333 | 75 | 0.718576 | 3.84188 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/lectures/adapter/LectureListSelectionAdapter.kt | 1 | 2049 | package de.tum.`in`.tumcampusapp.component.tumui.lectures.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.CheckBox
import android.widget.CompoundButton
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.tumui.calendar.CalendarController
import de.tum.`in`.tumcampusapp.component.tumui.calendar.model.CalendarItem
import de.tum.`in`.tumcampusapp.utils.Utils
import java.lang.Long.parseLong
class LectureListSelectionAdapter(
context: Context,
private val calendarItems: List<CalendarItem>,
private val appWidgetId: Int
) : BaseAdapter(), CompoundButton.OnCheckedChangeListener {
private val calendarController: CalendarController = CalendarController(context)
private val inflater: LayoutInflater = LayoutInflater.from(context)
override fun onCheckedChanged(buttonView: CompoundButton, isChecked: Boolean) {
// save new preferences
Utils.logv("Widget asked to change ${buttonView.text} to $isChecked")
if (isChecked) {
calendarController.deleteLectureFromBlacklist(this.appWidgetId, buttonView.text as String)
} else {
calendarController.addLectureToBlacklist(this.appWidgetId, buttonView.text as String)
}
}
override fun getCount() = calendarItems.size
override fun getItem(position: Int) = calendarItems[position]
override fun getItemId(position: Int) = parseLong(calendarItems[position].nr)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view: View = convertView ?: inflater.inflate(R.layout.list_timetable_configure_item, parent, false)
val checkBox = view.findViewById<CheckBox>(R.id.timetable_configure_item)
checkBox.isChecked = !calendarItems[position].blacklisted
checkBox.text = calendarItems[position].title
checkBox.setOnCheckedChangeListener(this)
return view
}
}
| gpl-3.0 | f3440cc1bd73cbf83df1f57749cdcda2 | 38.403846 | 111 | 0.756467 | 4.710345 | false | false | false | false |
jk1/pmd-kotlin | src/test/resources/org/jetbrains/pmdkotlin/ignoreIdentifiersAndLiteralsTest/IgnoreIdentifiers2.kt | 1 | 389 | fun sum(a : Int, b : Int): Int {
return a + b
}
fun factorial20() : Int {
var res = 1
for (n in (1..20)) {
res *= n
}
return res
// it's another comment
}
fun my(first : Double, second : Char, f : Int) {
var third = 2 * f;
var forth = 3 * first;
val fifth = 100 * 9 * 3423 * 123 * 324;
var sixth = second;
second = 'a';
return;
} | apache-2.0 | 5fb0f4b5eb4e90d8a9caf006ed86027a | 15.956522 | 48 | 0.491003 | 3.039063 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt | 2 | 4879 | package info.nightscout.androidaps.plugins.constraints.versionChecker
import android.content.Context
import android.net.ConnectivityManager
import info.nightscout.androidaps.BuildConfig
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.utils.SP
import org.slf4j.LoggerFactory
import java.io.IOException
import java.net.URL
import java.util.concurrent.TimeUnit
// check network connection
fun isConnected(): Boolean {
val connMgr = MainApp.instance().applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
return connMgr.activeNetworkInfo?.isConnected ?: false
}
private val log = LoggerFactory.getLogger(L.CORE)
fun triggerCheckVersion() {
if (!SP.contains(R.string.key_last_time_this_version_detected)) {
// On a new installation, set it as 30 days old in order to warn that there is a new version.
SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30))
}
// If we are good, only check once every day.
if (System.currentTimeMillis() > SP.getLong(R.string.key_last_time_this_version_detected, 0) + CHECK_EVERY) {
checkVersion()
}
}
private fun checkVersion() = if (isConnected()) {
Thread {
try {
val version: String? = findVersion(URL("https://raw.githubusercontent.com/MilosKozak/AndroidAPS/master/app/build.gradle").readText())
compareWithCurrentVersion(version, BuildConfig.VERSION_NAME)
} catch (e: IOException) {
log.debug("Github master version check error: $e")
}
}.start()
} else
log.debug("Github master version no checked. No connectivity")
fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) {
val newVersionElements = newVersion.toNumberList()
val currentVersionElements = currentVersion.toNumberList()
if (newVersionElements == null || newVersionElements.isEmpty()) {
onVersionNotDetectable()
return
}
if (currentVersionElements == null || currentVersionElements.isEmpty()) {
// current version scrambled?!
onNewVersionDetected(currentVersion, newVersion)
return
}
newVersionElements.take(3).forEachIndexed { i, newElem ->
val currElem: Int = currentVersionElements.getOrNull(i)
?: return onNewVersionDetected(currentVersion, newVersion)
(newElem - currElem).let {
when {
it > 0 -> return onNewVersionDetected(currentVersion, newVersion)
it < 0 -> return onOlderVersionDetected()
it == 0 -> Unit
}
}
}
onSameVersionDetected()
}
private fun onOlderVersionDetected() {
log.debug("Version newer than master. Are you developer?")
SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis())
}
fun onSameVersionDetected() {
SP.putLong(R.string.key_last_time_this_version_detected, System.currentTimeMillis())
}
fun onVersionNotDetectable() {
log.debug("fetch failed")
}
fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
val now = System.currentTimeMillis()
if (now > SP.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
log.debug("Version ${currentVersion} outdated. Found $newVersion")
val notification = Notification(Notification.NEWVERSIONDETECTED, String.format(MainApp.gs(R.string.versionavailable), newVersion.toString()), Notification.LOW)
RxBus.send(EventNewNotification(notification))
SP.putLong(R.string.key_last_versionchecker_warning, now)
}
}
@Deprecated(replaceWith = ReplaceWith("numericVersionPart()"), message = "Will not work if RCs have another index number in it.")
fun String.versionStrip() = this.mapNotNull {
when (it) {
in '0'..'9' -> it
'.' -> it
else -> null
}
}.joinToString(separator = "")
fun String.numericVersionPart(): String =
"(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1) ?: ""
fun String?.toNumberList() =
this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }
fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
val CHECK_EVERY = TimeUnit.DAYS.toMillis(1)
val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
| agpl-3.0 | b3252e7dce2ebc8d32fbbf9c0f751a90 | 37.722222 | 167 | 0.699324 | 4.333037 | false | false | false | false |
westnordost/osmagent | app/src/main/java/de/westnordost/streetcomplete/view/StreetSideSelectPuzzle.kt | 1 | 5017 | package de.westnordost.streetcomplete.view
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Shader
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RelativeLayout
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.util.BitmapUtil
import kotlinx.android.synthetic.main.side_select_puzzle.view.*
class StreetSideSelectPuzzle @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0)
: FrameLayout(context, attrs, defStyleAttr) {
var listener: ((isRight:Boolean) -> Unit)? = null
set(value) {
field = value
leftSide.setOnClickListener { listener?.invoke(false) }
rightSide.setOnClickListener { listener?.invoke(true) }
}
private var leftImageResId: Int = 0
private var rightImageResId: Int = 0
private var isLeftImageSet: Boolean = false
private var isRightImageSet: Boolean = false
private var onlyShowingOneSide: Boolean = false
init {
LayoutInflater.from(context).inflate(R.layout.side_select_puzzle, this, true)
addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
val width = Math.min(bottom - top, right - left)
val height = Math.max(bottom - top, right - left)
val params = rotateContainer.layoutParams
if(width != params.width || height != params.height) {
params.width = width
params.height = height
rotateContainer.layoutParams = params
}
val streetWidth = if (onlyShowingOneSide) width else width / 2
if (!isLeftImageSet && leftImageResId != 0) {
setStreetDrawable(leftImageResId, streetWidth, leftSideImage, true)
isLeftImageSet = true
}
if (!isRightImageSet && rightImageResId != 0) {
setStreetDrawable(rightImageResId, streetWidth, rightSideImage, false)
isRightImageSet = true
}
}
}
fun setStreetRotation(rotation: Float) {
rotateContainer.rotation = rotation
val scale = Math.abs(Math.cos(rotation * Math.PI / 180)).toFloat()
rotateContainer.scaleX = 1 + scale * 2 / 3f
rotateContainer.scaleY = 1 + scale * 2 / 3f
}
fun setLeftSideImageResource(resId: Int) {
leftImageResId = resId
}
fun setRightSideImageResource(resId: Int) {
rightImageResId = resId
}
fun replaceLeftSideImageResource(resId: Int) {
leftImageResId = resId
replaceAnimated(resId, leftSideImage, true)
}
fun replaceRightSideImageResource(resId: Int) {
rightImageResId = resId
replaceAnimated(resId, rightSideImage, false)
}
fun showOnlyRightSide() {
isRightImageSet = false
onlyShowingOneSide = true
val params = RelativeLayout.LayoutParams(0, 0)
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
strut.layoutParams = params
}
fun showOnlyLeftSide() {
isLeftImageSet = false
onlyShowingOneSide = true
val params = RelativeLayout.LayoutParams(0, 0)
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
strut.layoutParams = params
}
fun showBothSides() {
isRightImageSet = false
isLeftImageSet = isRightImageSet
onlyShowingOneSide = false
val params = RelativeLayout.LayoutParams(0, 0)
params.addRule(RelativeLayout.CENTER_HORIZONTAL)
strut.layoutParams = params
}
private fun replaceAnimated(resId: Int, imgView: ImageView, flip180Degrees: Boolean) {
val width = if (onlyShowingOneSide) rotateContainer.width else rotateContainer.width / 2
setStreetDrawable(resId, width, imgView, flip180Degrees)
(imgView.parent as View).bringToFront()
imgView.scaleX = 3f
imgView.scaleY = 3f
imgView.animate().scaleX(1f).scaleY(1f)
}
private fun setStreetDrawable(resId: Int, width: Int, imageView: ImageView, flip180Degrees: Boolean) {
val drawable = scaleToWidth(BitmapUtil.asBitmapDrawable(resources, resId), width, flip180Degrees)
drawable.tileModeY = Shader.TileMode.REPEAT
imageView.setImageDrawable(drawable)
}
private fun scaleToWidth(drawable: BitmapDrawable, width: Int, flip180Degrees: Boolean): BitmapDrawable {
val m = Matrix()
val scale = width.toFloat() / drawable.intrinsicWidth
m.postScale(scale, scale)
if (flip180Degrees) m.postRotate(180f)
val bitmap = Bitmap.createBitmap(
drawable.bitmap, 0, 0,
drawable.intrinsicWidth, drawable.intrinsicHeight, m, true
)
return BitmapDrawable(resources, bitmap)
}
}
| gpl-3.0 | 4579a34e9922da2d28dc889c2d69e911 | 34.58156 | 109 | 0.668726 | 4.769011 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/magic_links/MagicLinkPresenter.kt | 2 | 1365 | package org.stepik.android.presentation.magic_links
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepik.android.domain.magic_links.interactor.MagicLinkInteractor
import ru.nobird.android.presentation.base.PresenterBase
import javax.inject.Inject
class MagicLinkPresenter
@Inject
constructor(
private val magicLinkInteractor: MagicLinkInteractor,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : PresenterBase<MagicLinkView>() {
private var state: MagicLinkView.State = MagicLinkView.State.Idle
set(value) {
field = value
view?.setState(value)
}
fun onData(url: String) {
if (state != MagicLinkView.State.Idle) return
state = MagicLinkView.State.Loading
compositeDisposable += magicLinkInteractor
.createMagicLink(url)
.observeOn(mainScheduler)
.subscribeOn(backgroundScheduler)
.subscribeBy(
onSuccess = { state = MagicLinkView.State.Success(it.url) },
onError = { state = MagicLinkView.State.Success(url) }
)
}
} | apache-2.0 | f66b198b9a3d0b0de2ff7efd694a0a01 | 32.317073 | 76 | 0.710623 | 4.875 | false | false | false | false |
Commit451/GitLabAndroid | app/src/main/java/com/commit451/gitlab/model/api/Todo.kt | 2 | 1464 | package com.commit451.gitlab.model.api
import android.os.Parcelable
import androidx.annotation.StringDef
import com.squareup.moshi.Json
import kotlinx.android.parcel.Parcelize
import java.util.Date
/**
* Todos. Not processing Target, since it is different depending on what the type is, which
* makes it not play nice with any automated json parsing
*/
@Parcelize
data class Todo(
@Json(name = "id")
var id: String? = null,
@Json(name = "project")
var project: Project? = null,
@Json(name = "author")
var author: User? = null,
@Json(name = "action_name")
var actionName: String? = null,
@Json(name = "target_type")
@TargetType
@get:TargetType
var targetType: String? = null,
@Json(name = "target_url")
var targetUrl: String? = null,
@Json(name = "body")
var body: String? = null,
@Json(name = "state")
@State
@get:State
var state: String? = null,
@Json(name = "created_at")
var createdAt: Date? = null
) : Parcelable {
companion object {
const val TARGET_ISSUE = "Issue"
const val TARGET_MERGE_REQUEST = "MergeRequest"
const val STATE_PENDING = "pending"
const val STATE_DONE = "done"
}
@StringDef(TARGET_ISSUE, TARGET_MERGE_REQUEST)
@Retention(AnnotationRetention.SOURCE)
annotation class TargetType
@StringDef(STATE_PENDING, STATE_DONE)
@Retention(AnnotationRetention.SOURCE)
annotation class State
}
| apache-2.0 | 715bc41e5c698bc2586facf1650f087b | 26.111111 | 91 | 0.662568 | 3.763496 | false | false | false | false |
divinespear/jpa-schema-gradle-plugin | src/main/kotlin/io/github/divinespear/plugin/plugin.kt | 1 | 2062 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package io.github.divinespear.plugin
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaLibraryPlugin
import org.gradle.kotlin.dsl.*
class JpaSchemaGenerationPlugin : Plugin<Project> {
companion object {
private const val SPRING_VERSION = "[5.0,6.0)"
private val SPRING_DEPENDENCIES = listOf(
"org.springframework:spring-orm:${SPRING_VERSION}",
"org.springframework:spring-context:${SPRING_VERSION}",
"org.springframework:spring-aspects:${SPRING_VERSION}"
)
}
override fun apply(project: Project) {
project.run {
plugins.apply(JavaLibraryPlugin::class)
configurations {
register(CONFIGURATION_NAME)
}
dependencies {
SPRING_DEPENDENCIES.forEach {
CONFIGURATION_NAME(it)
}
}
extensions.create<JpaSchemaGenerationExtension>(EXTENSION_NAME).apply {
defaultOutputDirectory = project.buildDir.resolve("generated-schema")
targets = project.container(JpaSchemaGenerationProperties::class)
}
tasks {
register(PLUGIN_NAME, JpaSchemaGenerationTask::class) {
group = "help"
dependsOn(project.tasks.getByPath("classes"))
}
}
}
}
}
| apache-2.0 | b9401dd008dc5cdfdb5f2452e71feffc | 31.21875 | 77 | 0.703201 | 4.359408 | false | false | false | false |
Exaltead/SceneClassifier | SceneClassifier/app/src/main/java/com/exaltead/sceneclassifier/extraction/constants.kt | 1 | 351 | package com.exaltead.sceneclassifier.extraction
import android.media.AudioFormat
import android.media.AudioFormat.CHANNEL_IN_MONO
const val SAMPLING_RATE = 44100
const val SAMPLE_DURATION = 1
const val SAMPLE_MAX_LENGHT = SAMPLING_RATE * SAMPLE_DURATION
const val CHANNELS = CHANNEL_IN_MONO
const val AUDIO_ENCODING = AudioFormat.ENCODING_PCM_FLOAT
| gpl-3.0 | a717b2401b667672b2945fb7190eac27 | 34.1 | 61 | 0.820513 | 3.734043 | false | false | false | false |
itsmortoncornelius/example-wifi-direct | app/src/main/java/de/handler/mobile/wifivideo/WifiP2pDeviceRecyclerViewAdapter.kt | 1 | 1657 | package de.handler.mobile.wifivideo
import android.net.wifi.p2p.WifiP2pDevice
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import de.handler.mobile.wifivideo.DeviceListFragment.OnListFragmentInteractionListener
class WifiP2pDeviceRecyclerViewAdapter(private val listener: OnListFragmentInteractionListener?) : RecyclerView.Adapter<WifiP2pDeviceRecyclerViewAdapter.ViewHolder>() {
var values: List<WifiP2pDevice>? = null
get() = field
set(values) {
field = values
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_device, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItem(values?.get(position))
holder.view.setOnClickListener {
holder.item?.let { it1 -> listener?.onListFragmentInteraction(it1) }
}
}
override fun getItemCount(): Int {
return if (values == null) return 0 else { values!!.size }
}
inner class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
private val deviceNameTextView: TextView = view.findViewById<View>(R.id.id) as TextView
private val deviceAddressTextView: TextView = view.findViewById<View>(R.id.content) as TextView
var item: WifiP2pDevice? = null
fun bindItem(wifiP2pDevice: WifiP2pDevice?) {
item = wifiP2pDevice
deviceNameTextView.text = wifiP2pDevice?.deviceName
deviceAddressTextView.text = wifiP2pDevice?.deviceAddress
}
}
}
| apache-2.0 | 189c81f4886a09b8e90ba263983c1212 | 32.816327 | 168 | 0.777912 | 3.844548 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/activities/HistoryBrowseActivity.kt | 1 | 17892 | package info.nightscout.androidaps.activities
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.google.android.material.datepicker.MaterialDatePicker
import com.jjoe64.graphview.GraphView
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.fragments.HistoryBrowserData
import info.nightscout.androidaps.databinding.ActivityHistorybrowseBinding
import info.nightscout.androidaps.events.EventAutosensCalculationFinished
import info.nightscout.androidaps.events.EventCustomCalculationFinished
import info.nightscout.androidaps.events.EventRefreshOverview
import info.nightscout.androidaps.events.EventScale
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.extensions.toVisibilityKeepSpace
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.BuildHelper
import info.nightscout.androidaps.plugins.general.overview.OverviewMenus
import info.nightscout.androidaps.plugins.general.overview.events.EventUpdateOverviewGraph
import info.nightscout.androidaps.plugins.general.overview.graphData.GraphData
import info.nightscout.androidaps.plugins.iob.iobCobCalculator.events.EventIobCalculationProgress
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DefaultValueHelper
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.workflow.CalculationWorkflow
import info.nightscout.shared.logging.LTag
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import java.util.*
import javax.inject.Inject
import kotlin.math.min
class HistoryBrowseActivity : NoSplashAppCompatActivity() {
@Inject lateinit var historyBrowserData: HistoryBrowserData
@Inject lateinit var injector: HasAndroidInjector
@Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var defaultValueHelper: DefaultValueHelper
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var buildHelper: BuildHelper
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var overviewMenus: OverviewMenus
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var context: Context
@Inject lateinit var calculationWorkflow: CalculationWorkflow
private val disposable = CompositeDisposable()
private val secondaryGraphs = ArrayList<GraphView>()
private val secondaryGraphsLabel = ArrayList<TextView>()
private var axisWidth: Int = 0
private var rangeToDisplay = 24 // for graph
// private var start: Long = 0
private lateinit var binding: ActivityHistorybrowseBinding
private var destroyed = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHistorybrowseBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.left.setOnClickListener {
adjustTimeRange(historyBrowserData.overviewData.fromTime - T.hours(rangeToDisplay.toLong()).msecs())
loadAll("onClickLeft")
}
binding.right.setOnClickListener {
adjustTimeRange(historyBrowserData.overviewData.fromTime + T.hours(rangeToDisplay.toLong()).msecs())
loadAll("onClickRight")
}
binding.end.setOnClickListener {
setTime(dateUtil.now())
loadAll("onClickEnd")
}
binding.zoom.setOnClickListener {
var hours = rangeToDisplay + 6
hours = if (hours > 24) 6 else hours
rxBus.send(EventScale(hours))
}
binding.zoom.setOnLongClickListener {
Calendar.getInstance().also { calendar ->
calendar.timeInMillis = historyBrowserData.overviewData.fromTime
calendar[Calendar.MILLISECOND] = 0
calendar[Calendar.SECOND] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] = 0
setTime(calendar.timeInMillis)
}
loadAll("onLongClickZoom")
true
}
binding.date.setOnClickListener {
MaterialDatePicker.Builder.datePicker()
.setSelection(dateUtil.timeStampToUtcDateMillis(historyBrowserData.overviewData.fromTime))
.setTheme(R.style.DatePicker)
.build()
.apply {
addOnPositiveButtonClickListener { selection ->
setTime(dateUtil.mergeUtcDateToTimestamp(historyBrowserData.overviewData.fromTime, selection))
binding.date.text = dateUtil.dateAndTimeString(historyBrowserData.overviewData.fromTime)
loadAll("onClickDate")
}
}
.show(supportFragmentManager, "history_date_picker")
}
val dm = DisplayMetrics()
@Suppress("DEPRECATION")
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R)
display?.getRealMetrics(dm)
else
windowManager.defaultDisplay.getMetrics(dm)
axisWidth = if (dm.densityDpi <= 120) 3 else if (dm.densityDpi <= 160) 10 else if (dm.densityDpi <= 320) 35 else if (dm.densityDpi <= 420) 50 else if (dm.densityDpi <= 560) 70 else 80
binding.bgGraph.gridLabelRenderer?.gridColor = rh.gac(this, R.attr.graphGrid)
binding.bgGraph.gridLabelRenderer?.reloadStyles()
binding.bgGraph.gridLabelRenderer?.labelVerticalWidth = axisWidth
overviewMenus.setupChartMenu(context, binding.chartMenuButton)
prepareGraphsIfNeeded(overviewMenus.setting.size)
savedInstanceState?.let { bundle ->
rangeToDisplay = bundle.getInt("rangeToDisplay", 0)
historyBrowserData.overviewData.fromTime = bundle.getLong("start", 0)
historyBrowserData.overviewData.toTime = bundle.getLong("end", 0)
}
}
override fun onPause() {
super.onPause()
disposable.clear()
calculationWorkflow.stopCalculation(CalculationWorkflow.HISTORY_CALCULATION, "onPause")
}
@Synchronized
override fun onDestroy() {
destroyed = true
super.onDestroy()
}
override fun onResume() {
super.onResume()
disposable += rxBus
.toObservable(EventAutosensCalculationFinished::class.java)
.observeOn(aapsSchedulers.io)
.subscribe({
// catch only events from iobCobCalculator
if (it.cause is EventCustomCalculationFinished)
refreshLoop("EventAutosensCalculationFinished")
}, fabricPrivacy::logException)
disposable += rxBus
.toObservable(EventIobCalculationProgress::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updateCalcProgress(it.pass.finalPercent(it.progressPct)) }, fabricPrivacy::logException)
disposable += rxBus
.toObservable(EventUpdateOverviewGraph::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({ updateGUI("EventRefreshOverview") }, fabricPrivacy::logException)
disposable += rxBus
.toObservable(EventScale::class.java)
.observeOn(aapsSchedulers.main)
.subscribe({
rangeToDisplay = it.hours
setTime(historyBrowserData.overviewData.fromTime)
loadAll("rangeChange")
}, fabricPrivacy::logException)
updateCalcProgress(100)
if (historyBrowserData.overviewData.fromTime == 0L) {
// set start of current day
setTime(dateUtil.now())
loadAll("onResume")
} else {
updateGUI("onResume")
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putInt("rangeToDisplay", rangeToDisplay)
outState.putLong("start", historyBrowserData.overviewData.fromTime)
outState.putLong("end", historyBrowserData.overviewData.toTime)
}
private fun prepareGraphsIfNeeded(numOfGraphs: Int) {
if (numOfGraphs != secondaryGraphs.size - 1) {
//aapsLogger.debug("New secondary graph count ${numOfGraphs-1}")
// rebuild needed
secondaryGraphs.clear()
secondaryGraphsLabel.clear()
binding.iobGraph.removeAllViews()
for (i in 1 until numOfGraphs) {
val relativeLayout = RelativeLayout(this)
relativeLayout.layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
val graph = GraphView(this)
graph.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, rh.dpToPx(100)).also { it.setMargins(0, rh.dpToPx(15), 0, rh.dpToPx(10)) }
graph.gridLabelRenderer?.gridColor = rh.gac(R.attr.graphGrid)
graph.gridLabelRenderer?.reloadStyles()
graph.gridLabelRenderer?.isHorizontalLabelsVisible = false
graph.gridLabelRenderer?.labelVerticalWidth = axisWidth
graph.gridLabelRenderer?.numVerticalLabels = 3
graph.viewport.backgroundColor = rh.gac(this, R.attr.viewPortBackgroundColor)
relativeLayout.addView(graph)
val label = TextView(this)
val layoutParams = RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).also { it.setMargins(rh.dpToPx(30), rh.dpToPx(25), 0, 0) }
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
label.layoutParams = layoutParams
relativeLayout.addView(label)
secondaryGraphsLabel.add(label)
binding.iobGraph.addView(relativeLayout)
secondaryGraphs.add(graph)
}
}
}
@Suppress("SameParameterValue")
private fun loadAll(from: String) {
updateDate()
runCalculation(from)
}
private fun setTime(start: Long) {
GregorianCalendar().also { calendar ->
calendar.timeInMillis = start
calendar[Calendar.MILLISECOND] = 0
calendar[Calendar.SECOND] = 0
calendar[Calendar.MINUTE] = 0
calendar[Calendar.HOUR_OF_DAY] -= (calendar[Calendar.HOUR_OF_DAY] % rangeToDisplay)
adjustTimeRange(calendar.timeInMillis)
}
}
private fun adjustTimeRange(start: Long) {
historyBrowserData.overviewData.fromTime = start
historyBrowserData.overviewData.toTime = historyBrowserData.overviewData.fromTime + T.hours(rangeToDisplay.toLong()).msecs()
historyBrowserData.overviewData.endTime = historyBrowserData.overviewData.toTime
}
private fun runCalculation(from: String) {
calculationWorkflow.runCalculation(
CalculationWorkflow.HISTORY_CALCULATION,
historyBrowserData.iobCobCalculator,
historyBrowserData.overviewData,
from,
historyBrowserData.overviewData.toTime,
bgDataReload = true,
limitDataToOldestAvailable = false,
cause = EventCustomCalculationFinished(),
runLoop = false
)
}
@Volatile
var runningRefresh = false
@Suppress("SameParameterValue")
private fun refreshLoop(from: String) {
if (runningRefresh) return
runningRefresh = true
rxBus.send(EventRefreshOverview(from))
aapsLogger.debug(LTag.UI, "refreshLoop finished")
runningRefresh = false
}
private fun updateDate() {
binding.date.text = dateUtil.dateAndTimeString(historyBrowserData.overviewData.fromTime)
binding.zoom.text = rangeToDisplay.toString()
}
@Suppress("UNUSED_PARAMETER")
@SuppressLint("SetTextI18n")
fun updateGUI(from: String) {
aapsLogger.debug(LTag.UI, "updateGui $from")
updateDate()
val pump = activePlugin.activePump
val graphData = GraphData(injector, binding.bgGraph, historyBrowserData.overviewData)
val menuChartSettings = overviewMenus.setting
graphData.addInRangeArea(historyBrowserData.overviewData.fromTime, historyBrowserData.overviewData.endTime, defaultValueHelper.determineLowLine(), defaultValueHelper.determineHighLine())
graphData.addBgReadings(menuChartSettings[0][OverviewMenus.CharType.PRE.ordinal], context)
if (buildHelper.isDev()) graphData.addBucketedData()
graphData.addTreatments(context)
graphData.addEps(context, 0.95)
if (menuChartSettings[0][OverviewMenus.CharType.TREAT.ordinal])
graphData.addTherapyEvents()
if (menuChartSettings[0][OverviewMenus.CharType.ACT.ordinal])
graphData.addActivity(0.8)
if (pump.pumpDescription.isTempBasalCapable && menuChartSettings[0][OverviewMenus.CharType.BAS.ordinal])
graphData.addBasals()
graphData.addTargetLine()
graphData.addNowLine(dateUtil.now())
// set manual x bounds to have nice steps
graphData.setNumVerticalLabels()
graphData.formatAxis(historyBrowserData.overviewData.fromTime, historyBrowserData.overviewData.endTime)
graphData.performUpdate()
// 2nd graphs
prepareGraphsIfNeeded(menuChartSettings.size)
val secondaryGraphsData: ArrayList<GraphData> = ArrayList()
val now = System.currentTimeMillis()
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
val secondGraphData = GraphData(injector, secondaryGraphs[g], historyBrowserData.overviewData)
var useABSForScale = false
var useIobForScale = false
var useCobForScale = false
var useDevForScale = false
var useRatioForScale = false
var useDSForScale = false
var useBGIForScale = false
when {
menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] -> useABSForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] -> useIobForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] -> useCobForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] -> useDevForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] -> useBGIForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] -> useRatioForScale = true
menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] -> useDSForScale = true
}
val alignDevBgiScale = menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] && menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]
if (menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal]) secondGraphData.addAbsIob(useABSForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal]) secondGraphData.addIob(useIobForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal]) secondGraphData.addCob(useCobForScale, if (useCobForScale) 1.0 else 0.5)
if (menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal]) secondGraphData.addDeviations(useDevForScale, 1.0)
if (menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal]) secondGraphData.addMinusBGI(useBGIForScale, if (alignDevBgiScale) 1.0 else 0.8)
if (menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal]) secondGraphData.addRatio(useRatioForScale, if (useRatioForScale) 1.0 else 0.8)
if (menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal] && buildHelper.isDev()) secondGraphData.addDeviationSlope(useDSForScale, 1.0)
// set manual x bounds to have nice steps
secondGraphData.formatAxis(historyBrowserData.overviewData.fromTime, historyBrowserData.overviewData.endTime)
secondGraphData.addNowLine(now)
secondaryGraphsData.add(secondGraphData)
}
for (g in 0 until min(secondaryGraphs.size, menuChartSettings.size + 1)) {
secondaryGraphsLabel[g].text = overviewMenus.enabledTypes(g + 1)
secondaryGraphs[g].visibility = (
menuChartSettings[g + 1][OverviewMenus.CharType.ABS.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.IOB.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.COB.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.DEV.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.BGI.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.SEN.ordinal] ||
menuChartSettings[g + 1][OverviewMenus.CharType.DEVSLOPE.ordinal]
).toVisibility()
secondaryGraphsData[g].performUpdate()
}
}
private fun updateCalcProgress(percent: Int) {
binding.progressBar.progress = percent
binding.progressBar.visibility = (percent != 100).toVisibilityKeepSpace()
}
}
| agpl-3.0 | 72be9c1f119fee63db0c40104fc3eb63 | 47.356757 | 195 | 0.681031 | 5.21025 | false | false | false | false |
MKA-Nigeria/MKAN-Report-Android | videos_module/src/main/java/com/abdulmujibaliu/koutube/adapters/VideoTabsAdapter.kt | 1 | 976 | package com.abdulmujibaliu.koutube.adapters
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import com.abdulmujibaliu.koutube.fragments.playlists.PlaylistsFragment
import com.abdulmujibaliu.koutube.fragments.videos.VideosFragment
/**
* Created by abdulmujibaliu on 10/15/17.
*/
class VideoTabsAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
override fun getCount(): Int {
return 2
}
val fragments : List<Fragment> = listOf(VideosFragment.newInstance(), PlaylistsFragment.newInstance())
override fun getItem(position: Int): Fragment {
return if (position == 0) {
fragments[0]
} else {
fragments[1]
}
}
override fun getPageTitle(position: Int): String {
return if(position == 0){
"VIDEOS"
}else{
"PLAYLISTS"
}
}
} | mit | f4534d9d2d37a649dddc8c7417b3665a | 26.138889 | 106 | 0.680328 | 4.497696 | false | false | false | false |
auth0/Auth0.Android | auth0/src/test/java/com/auth0/android/util/AuthenticationAPIMockServer.kt | 1 | 5102 | package com.auth0.android.util
import okhttp3.mockwebserver.MockResponse
import java.nio.file.Files
import java.nio.file.Paths
internal class AuthenticationAPIMockServer : APIMockServer() {
fun willReturnSuccessfulChangePassword(): AuthenticationAPIMockServer {
server.enqueue(responseWithJSON("NOT REALLY A JSON", 200))
return this
}
fun willReturnSuccessfulPasswordlessStart(): AuthenticationAPIMockServer {
val json = """{
"phone+number": "+1098098098"
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnSuccessfulSignUp(): AuthenticationAPIMockServer {
val json = """{
"_id": "gjsmgdkjs72jljsf2dsdhh",
"email": "support@auth0.com",
"email_verified": false,
"username": "support"
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnSuccessfulEmptyBody(): AuthenticationAPIMockServer {
server.enqueue(responseEmpty(200))
return this
}
fun willReturnSuccessfulLogin(idToken: String = ID_TOKEN): AuthenticationAPIMockServer {
val json = """{
"refresh_token": "$REFRESH_TOKEN",
"id_token": "$idToken",
"access_token": "$ACCESS_TOKEN",
"token_type": "$BEARER",
"expires_in": 86000
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnSuccessfulLoginWithRecoveryCode(): AuthenticationAPIMockServer {
val json = """{
"refresh_token": "$REFRESH_TOKEN",
"id_token": "$ID_TOKEN",
"access_token": "$ACCESS_TOKEN",
"token_type": "$BEARER",
"expires_in": 86000,
"recovery_code": "654321"
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnInvalidRequest(): AuthenticationAPIMockServer {
val json = """{
"error": "invalid_request",
"error_description": "a random error"
}"""
server.enqueue(responseWithJSON(json, 400))
return this
}
fun willReturnEmptyJsonWebKeys(): AuthenticationAPIMockServer {
val json = """{
"keys": []
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnValidJsonWebKeys(): AuthenticationAPIMockServer {
try {
val encoded = Files.readAllBytes(Paths.get("src/test/resources/rsa_jwks.json"))
val json = String(encoded)
server.enqueue(responseWithJSON(json, 200))
} catch (ignored: Exception) {
println("File parsing error")
}
return this
}
fun willReturnUserInfo(): AuthenticationAPIMockServer {
val json = """{
"email": "p@p.xom",
"email_verified": false,
"picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png",
"user_id": "auth0|53b995f8bce68d9fc900099c",
"name": "p@p.xom",
"nickname": "p",
"identities": [
{
"user_id": "53b995f8bce68d9fc900099c",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"created_at": "2014-07-06T18:33:49.005Z",
"username": "p",
"updated_at": "2015-09-30T19:43:48.499Z"
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnPlainTextUnauthorized(): AuthenticationAPIMockServer {
server.enqueue(responseWithPlainText("Unauthorized", 401))
return this
}
fun willReturnTokens(): AuthenticationAPIMockServer {
val json = """{
"access_token": "$ACCESS_TOKEN",
"refresh_token": "$REFRESH_TOKEN",
"id_token": "$ID_TOKEN",
"token_type": "Bearer",
"expires_in": 86000
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
fun willReturnSuccessfulMFAChallenge(): AuthenticationAPIMockServer {
val json = """{
"challenge_type":"oob",
"binding_method":"prompt",
"oob_code": "abcdefg"
}"""
server.enqueue(responseWithJSON(json, 200))
return this
}
private fun responseEmpty(statusCode: Int): MockResponse {
return MockResponse()
.setResponseCode(statusCode)
}
private fun responseWithPlainText(statusMessage: String, statusCode: Int): MockResponse {
return MockResponse()
.setResponseCode(statusCode)
.addHeader("Content-Type", "text/plain")
.setBody(statusMessage)
}
companion object {
const val REFRESH_TOKEN = "REFRESH_TOKEN"
const val ID_TOKEN = "ID_TOKEN"
const val ACCESS_TOKEN = "ACCESS_TOKEN"
private const val BEARER = "BEARER"
}
} | mit | b88399e6d582b82ef28864ce6cf75469 | 30.89375 | 178 | 0.587809 | 4.52305 | false | false | false | false |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/BranchedFoldingUtils.kt | 3 | 11446 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.branchedTransformations
import org.jetbrains.kotlin.cfg.WhenChecker
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.intentions.branches
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
object BranchedFoldingUtils {
private fun getFoldableBranchedAssignment(branch: KtExpression?): KtBinaryExpression? {
fun checkAssignment(expression: KtBinaryExpression): Boolean {
if (expression.operationToken !in KtTokens.ALL_ASSIGNMENTS) return false
val left = expression.left as? KtNameReferenceExpression ?: return false
if (expression.right == null) return false
val parent = expression.parent
if (parent is KtBlockExpression) {
return !KtPsiUtil.checkVariableDeclarationInBlock(parent, left.text)
}
return true
}
return (branch?.lastBlockStatementOrThis() as? KtBinaryExpression)?.takeIf(::checkAssignment)
}
fun getFoldableBranchedReturn(branch: KtExpression?): KtReturnExpression? =
(branch?.lastBlockStatementOrThis() as? KtReturnExpression)?.takeIf {
it.returnedExpression != null &&
it.returnedExpression !is KtLambdaExpression &&
it.getTargetLabel() == null
}
private fun KtBinaryExpression.checkAssignmentsMatch(
other: KtBinaryExpression,
leftType: KotlinType,
rightTypeConstructor: TypeConstructor
): Boolean {
val left = this.left ?: return false
val otherLeft = other.left ?: return false
if (left.text != otherLeft.text || operationToken != other.operationToken ||
left.mainReference?.resolve() != otherLeft.mainReference?.resolve()
) return false
val rightType = other.rightType() ?: return false
return rightType.constructor == rightTypeConstructor || (operationToken == KtTokens.EQ && rightType.isSubtypeOf(leftType))
}
private fun KtBinaryExpression.rightType(): KotlinType? {
val right = this.right ?: return null
val context = this.analyze()
val diagnostics = context.diagnostics
fun hasTypeMismatchError(e: KtExpression) = diagnostics.forElement(e).any { it.factory == Errors.TYPE_MISMATCH }
if (hasTypeMismatchError(this) || hasTypeMismatchError(right)) return null
return right.getType(context)
}
internal fun getFoldableAssignmentNumber(expression: KtExpression?): Int {
expression ?: return -1
val assignments = linkedSetOf<KtBinaryExpression>()
fun collectAssignmentsAndCheck(e: KtExpression?): Boolean = when (e) {
is KtWhenExpression -> {
val entries = e.entries
!e.hasMissingCases() && entries.isNotEmpty() && entries.all { entry ->
val assignment = getFoldableBranchedAssignment(entry.expression)?.run { assignments.add(this) }
assignment != null || collectAssignmentsAndCheck(entry.expression?.lastBlockStatementOrThis())
}
}
is KtIfExpression -> {
val branches = e.branches
val elseBranch = branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else`
branches.size > 1 && elseBranch != null && branches.all { branch ->
val assignment = getFoldableBranchedAssignment(branch)?.run { assignments.add(this) }
assignment != null || collectAssignmentsAndCheck(branch?.lastBlockStatementOrThis())
}
}
is KtTryExpression -> {
e.tryBlockAndCatchBodies().all {
val assignment = getFoldableBranchedAssignment(it)?.run { assignments.add(this) }
assignment != null || collectAssignmentsAndCheck(it?.lastBlockStatementOrThis())
}
}
is KtCallExpression -> {
e.analyze().getType(e)?.isNothing() ?: false
}
is KtBreakExpression, is KtContinueExpression,
is KtThrowExpression, is KtReturnExpression -> true
else -> false
}
if (!collectAssignmentsAndCheck(expression)) return -1
val firstAssignment = assignments.firstOrNull { !it.right.isNullExpression() } ?: assignments.firstOrNull() ?: return 0
val leftType = firstAssignment.left?.let { it.getType(it.analyze(BodyResolveMode.PARTIAL)) } ?: return 0
val rightTypeConstructor = firstAssignment.rightType()?.constructor ?: return -1
if (assignments.any { !firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor) }) {
return -1
}
if (expression.anyDescendantOfType<KtBinaryExpression>(
predicate = {
if (it.operationToken in KtTokens.ALL_ASSIGNMENTS)
if (it.getNonStrictParentOfType<KtFinallySection>() != null)
firstAssignment.checkAssignmentsMatch(it, leftType, rightTypeConstructor)
else
it !in assignments
else
false
}
)
) {
return -1
}
return assignments.size
}
private fun getFoldableReturns(branches: List<KtExpression?>): List<KtReturnExpression>? =
branches.fold<KtExpression?, MutableList<KtReturnExpression>?>(mutableListOf()) { prevList, branch ->
if (prevList == null) return@fold null
val foldableBranchedReturn = getFoldableBranchedReturn(branch)
if (foldableBranchedReturn != null) {
prevList.add(foldableBranchedReturn)
} else {
val currReturns = getFoldableReturns(branch?.lastBlockStatementOrThis()) ?: return@fold null
prevList += currReturns
}
prevList
}
internal fun getFoldableReturns(expression: KtExpression?): List<KtReturnExpression>? = when (expression) {
is KtWhenExpression -> {
val entries = expression.entries
when {
expression.hasMissingCases() -> null
entries.isEmpty() -> null
else -> getFoldableReturns(entries.map { it.expression })
}
}
is KtIfExpression -> {
val branches = expression.branches
when {
branches.isEmpty() -> null
branches.lastOrNull()?.getStrictParentOfType<KtIfExpression>()?.`else` == null -> null
else -> getFoldableReturns(branches)
}
}
is KtTryExpression -> {
if (expression.finallyBlock?.finalExpression?.let { getFoldableReturns(listOf(it)) }?.isNotEmpty() == true)
null
else
getFoldableReturns(expression.tryBlockAndCatchBodies())
}
is KtCallExpression -> {
if (expression.analyze().getType(expression)?.isNothing() == true) emptyList() else null
}
is KtBreakExpression, is KtContinueExpression, is KtThrowExpression -> emptyList()
else -> null
}
private fun getFoldableReturnNumber(expression: KtExpression?) = getFoldableReturns(expression)?.size ?: -1
fun canFoldToReturn(expression: KtExpression?): Boolean = getFoldableReturnNumber(expression) > 0
fun tryFoldToAssignment(expression: KtExpression) {
var lhs: KtExpression? = null
var op: String? = null
val psiFactory = KtPsiFactory(expression)
fun KtBinaryExpression.replaceWithRHS() {
if (lhs == null || op == null) {
lhs = left!!.copy() as KtExpression
op = operationReference.text
}
val rhs = right!!
if (rhs is KtLambdaExpression && this.parent !is KtBlockExpression) {
replace(psiFactory.createSingleStatementBlock(rhs))
} else {
replace(rhs)
}
}
fun lift(e: KtExpression?) {
when (e) {
is KtWhenExpression -> e.entries.forEach { entry ->
getFoldableBranchedAssignment(entry.expression)?.replaceWithRHS() ?: lift(entry.expression?.lastBlockStatementOrThis())
}
is KtIfExpression -> e.branches.forEach { branch ->
getFoldableBranchedAssignment(branch)?.replaceWithRHS() ?: lift(branch?.lastBlockStatementOrThis())
}
is KtTryExpression -> e.tryBlockAndCatchBodies().forEach {
getFoldableBranchedAssignment(it)?.replaceWithRHS() ?: lift(it?.lastBlockStatementOrThis())
}
}
}
lift(expression)
if (lhs != null && op != null) {
expression.replace(psiFactory.createExpressionByPattern("$0 $1 $2", lhs!!, op!!, expression))
}
}
fun foldToReturn(expression: KtExpression): KtExpression {
fun KtReturnExpression.replaceWithReturned() {
replace(returnedExpression!!)
}
fun lift(e: KtExpression?) {
when (e) {
is KtWhenExpression -> e.entries.forEach { entry ->
val entryExpr = entry.expression
getFoldableBranchedReturn(entryExpr)?.replaceWithReturned() ?: lift(entryExpr?.lastBlockStatementOrThis())
}
is KtIfExpression -> e.branches.forEach { branch ->
getFoldableBranchedReturn(branch)?.replaceWithReturned() ?: lift(branch?.lastBlockStatementOrThis())
}
is KtTryExpression -> e.tryBlockAndCatchBodies().forEach {
getFoldableBranchedReturn(it)?.replaceWithReturned() ?: lift(it?.lastBlockStatementOrThis())
}
}
}
lift(expression)
return expression.replaced(KtPsiFactory(expression).createExpressionByPattern("return $0", expression))
}
private fun KtTryExpression.tryBlockAndCatchBodies(): List<KtExpression?> = listOf(tryBlock) + catchClauses.map { it.catchBody }
private fun KtWhenExpression.hasMissingCases(): Boolean =
!KtPsiUtil.checkWhenExpressionHasSingleElse(this) && WhenChecker.getMissingCases(this, safeAnalyzeNonSourceRootCode()).isNotEmpty()
}
| apache-2.0 | 153bce8520c5543ffde3c1eee136022b | 46.493776 | 158 | 0.632099 | 5.774975 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/graphic/Hsv.kt | 1 | 1539 | package com.acornui.graphic
import kotlinx.serialization.*
import kotlinx.serialization.builtins.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlin.math.abs
/**
* Hue saturation value
*/
@Serializable(with = HsvSerializer::class)
data class Hsv(
val h: Double = 0.0,
val s: Double = 0.0,
val v: Double = 0.0,
val a: Double = 1.0
) {
fun toRgb(): Color {
val r: Double
val g: Double
val b: Double
val c = v * s
val x = c * (1.0 - abs((h / 60.0) % 2.0 - 1.0))
val m = v - c
when {
h < 60.0 -> {
r = c + m
g = x + m
b = 0.0 + m
}
h < 120.0 -> {
r = x + m
g = c + m
b = 0.0 + m
}
h < 180.0 -> {
r = 0.0 + m
g = c + m
b = x + m
}
h < 240.0 -> {
r = 0.0 + m
g = x + m
b = c + m
}
h < 300.0 -> {
r = x + m
g = 0.0 + m
b = c + m
}
else -> {
r = c + m
g = 0.0 + m
b = x + m
}
}
return Color(r, g, b, a)
}
}
@Serializer(forClass = Hsv::class)
object HsvSerializer : KSerializer<Hsv> {
override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("Hsv", PrimitiveKind.STRING)
override fun serialize(encoder: Encoder, value: Hsv) {
encoder.encodeSerializableValue(ListSerializer(Double.serializer()), listOf(value.h, value.s, value.v, value.a))
}
override fun deserialize(decoder: Decoder): Hsv {
val values = decoder.decodeSerializableValue(ListSerializer(Double.serializer()))
return Hsv(values[0], values[1], values[2], values[3])
}
} | apache-2.0 | 25c0c9b0a7ab5e0108f93d4210694618 | 19.263158 | 114 | 0.575699 | 2.763016 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/cards/quickstart/QuickStartCardViewHolder.kt | 1 | 5925 | package org.wordpress.android.ui.mysite.cards.quickstart
import android.animation.ObjectAnimator
import android.content.res.ColorStateList
import android.graphics.Paint
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import androidx.appcompat.widget.PopupMenu
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.google.android.material.textview.MaterialTextView
import org.wordpress.android.R
import org.wordpress.android.databinding.MySiteCardToolbarBinding
import org.wordpress.android.databinding.NewQuickStartTaskTypeItemBinding
import org.wordpress.android.databinding.QuickStartCardBinding
import org.wordpress.android.databinding.QuickStartTaskTypeItemBinding
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.CUSTOMIZE
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.GET_TO_KNOW_APP
import org.wordpress.android.fluxc.store.QuickStartStore.QuickStartTaskType.GROW
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickStartCard
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Card.QuickStartCard.QuickStartTaskTypeItem
import org.wordpress.android.ui.mysite.MySiteCardAndItemViewHolder
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.ui.utils.UiHelpers
import org.wordpress.android.util.extensions.setVisible
import org.wordpress.android.util.extensions.viewBinding
const val PERCENT_HUNDRED = 100
class QuickStartCardViewHolder(
parent: ViewGroup,
private val uiHelpers: UiHelpers
) : MySiteCardAndItemViewHolder<QuickStartCardBinding>(parent.viewBinding(QuickStartCardBinding::inflate)) {
fun bind(card: QuickStartCard) = with(binding) {
mySiteCardToolbar.update(card)
quickStartCustomize.update(CUSTOMIZE, card.taskTypeItems)
quickStartGrow.update(GROW, card.taskTypeItems)
quickStartGetToKnowApp.update(GET_TO_KNOW_APP, card.taskTypeItems, card.onRemoveMenuItemClick)
}
private fun MySiteCardToolbarBinding.update(card: QuickStartCard) {
if (!card.toolbarVisible) {
mySiteCardToolbar.visibility = View.GONE
return
}
mySiteCardToolbarTitle.text = uiHelpers.getTextOfUiString(itemView.context, card.title)
mySiteCardToolbarMore.isVisible = card.moreMenuVisible
mySiteCardToolbarMore.setOnClickListener {
showQuickStartCardMenu(
card.onRemoveMenuItemClick,
mySiteCardToolbarMore
)
}
}
private fun showQuickStartCardMenu(onRemoveMenuItemClick: ListItemInteraction, anchor: View) {
val quickStartPopupMenu = PopupMenu(itemView.context, anchor)
quickStartPopupMenu.setOnMenuItemClickListener {
onRemoveMenuItemClick.click()
return@setOnMenuItemClickListener true
}
quickStartPopupMenu.inflate(R.menu.quick_start_card_menu)
quickStartPopupMenu.show()
}
private fun QuickStartTaskTypeItemBinding.update(
taskType: QuickStartTaskType,
taskTypeItems: List<QuickStartTaskTypeItem>
) {
val hasItemOfTaskType = taskTypeItems.any { it.quickStartTaskType == taskType }
itemRoot.setVisible(hasItemOfTaskType)
if (!hasItemOfTaskType) return
val item = taskTypeItems.first { it.quickStartTaskType == taskType }
with(itemTitle) {
text = uiHelpers.getTextOfUiString(itemView.context, item.title)
isEnabled = item.titleEnabled
paintFlags(item)
}
itemSubtitle.text = uiHelpers.getTextOfUiString(itemView.context, item.subtitle)
itemProgress.update(item)
itemRoot.setOnClickListener { item.onClick.click() }
}
private fun NewQuickStartTaskTypeItemBinding.update(
taskType: QuickStartTaskType,
taskTypeItems: List<QuickStartTaskTypeItem>,
onRemoveMenuItemClick: ListItemInteraction
) {
val hasItemOfTaskType = taskTypeItems.any { it.quickStartTaskType == taskType }
quickStartItemRoot.setVisible(hasItemOfTaskType)
if (!hasItemOfTaskType) return
val item = taskTypeItems.first { it.quickStartTaskType == taskType }
with(quickStartItemTitle) {
text = uiHelpers.getTextOfUiString(itemView.context, item.title)
isEnabled = item.titleEnabled
}
quickStartItemSubtitle.text = uiHelpers.getTextOfUiString(itemView.context, item.subtitle)
quickStartItemProgress.update(item)
showCompletedIconIfNeeded(item.progress)
quickStartItemRoot.setOnClickListener { item.onClick.click() }
quickStartItemMoreIcon.setOnClickListener {
showQuickStartCardMenu(
onRemoveMenuItemClick,
quickStartItemMoreIcon
)
}
}
private fun NewQuickStartTaskTypeItemBinding.showCompletedIconIfNeeded(progress: Int) {
quickStartTaskCompletedIcon.setVisible(progress == PERCENT_HUNDRED)
}
private fun MaterialTextView.paintFlags(item: QuickStartTaskTypeItem) {
paintFlags = if (item.strikeThroughTitle) {
paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
} else {
paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}
}
private fun ProgressBar.update(item: QuickStartTaskTypeItem) {
ObjectAnimator.ofInt(this, PROGRESS, item.progress).setDuration(PROGRESS_ANIMATION_DURATION).start()
val progressIndicatorColor = ContextCompat.getColor(itemView.context, item.progressColor)
progressTintList = ColorStateList.valueOf(progressIndicatorColor)
}
companion object {
private const val PROGRESS = "progress"
private const val PROGRESS_ANIMATION_DURATION = 600L
}
}
| gpl-2.0 | 5e191211dccf69a576f4d1f29e501951 | 43.216418 | 108 | 0.743797 | 5.243363 | false | false | false | false |
mdaniel/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentUtil.kt | 3 | 5659 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.vcs.log.impl
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.util.NlsContexts
import com.intellij.openapi.vcs.changes.ui.ChangesViewContentManager
import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.ui.content.Content
import com.intellij.ui.content.ContentManager
import com.intellij.ui.content.TabDescriptor
import com.intellij.ui.content.TabGroupId
import com.intellij.util.Consumer
import com.intellij.util.ContentUtilEx
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.concurrency.annotations.RequiresEdt
import com.intellij.vcs.log.VcsLogBundle
import com.intellij.vcs.log.VcsLogUi
import com.intellij.vcs.log.impl.VcsLogManager.VcsLogUiFactory
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogPanel
import com.intellij.vcs.log.ui.VcsLogUiEx
import org.jetbrains.annotations.ApiStatus
import java.util.function.Function
import java.util.function.Supplier
import javax.swing.JComponent
/**
* Utility methods to operate VCS Log tabs as [Content]s of the [ContentManager] of the VCS toolwindow.
*/
object VcsLogContentUtil {
private fun getLogUi(c: JComponent): VcsLogUiEx? {
val uis = VcsLogPanel.getLogUis(c)
require(uis.size <= 1) { "Component $c has more than one log ui: $uis" }
return uis.singleOrNull()
}
internal fun selectLogUi(project: Project, logUi: VcsLogUi, requestFocus: Boolean = true): Boolean {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return false
val manager = toolWindow.contentManager
val component = ContentUtilEx.findContentComponent(manager) { c -> getLogUi(c)?.id == logUi.id } ?: return false
if (!toolWindow.isVisible) {
toolWindow.activate(null)
}
return ContentUtilEx.selectContent(manager, component, requestFocus)
}
fun getId(content: Content): String? {
return getLogUi(content.component)?.id
}
@JvmStatic
fun <U : VcsLogUiEx> openLogTab(project: Project,
logManager: VcsLogManager,
tabGroupId: TabGroupId,
tabDisplayName: Function<U, @NlsContexts.TabTitle String>,
factory: VcsLogUiFactory<out U>,
focus: Boolean): U {
val logUi = logManager.createLogUi(factory, VcsLogTabLocation.TOOL_WINDOW)
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID)
?: throw IllegalStateException("Could not find tool window for id ${ChangesViewContentManager.TOOLWINDOW_ID}")
ContentUtilEx.addTabbedContent(toolWindow.contentManager, tabGroupId,
TabDescriptor(VcsLogPanel(logManager, logUi), Supplier { tabDisplayName.apply(logUi) }, logUi), focus)
if (focus) {
toolWindow.activate(null)
}
return logUi
}
fun closeLogTab(manager: ContentManager, tabId: String): Boolean {
return ContentUtilEx.closeContentTab(manager) { c: JComponent ->
getLogUi(c)?.id == tabId
}
}
@JvmStatic
fun runInMainLog(project: Project, consumer: Consumer<in MainVcsLogUi>) {
val window = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID)
if (window == null || !selectMainLog(window.contentManager)) {
showLogIsNotAvailableMessage(project)
return
}
val runConsumer = Runnable { VcsLogContentProvider.getInstance(project)!!.executeOnMainUiCreated(consumer) }
if (!window.isVisible) {
window.activate(runConsumer)
}
else {
runConsumer.run()
}
}
@RequiresEdt
fun showLogIsNotAvailableMessage(project: Project) {
VcsBalloonProblemNotifier.showOverChangesView(project, VcsLogBundle.message("vcs.log.is.not.available"), MessageType.WARNING)
}
internal fun findMainLog(cm: ContentManager): Content? {
// here tab name is used instead of log ui id to select the correct tab
// it's done this way since main log ui may not be created when this method is called
return cm.contents.find { VcsLogContentProvider.TAB_NAME == it.tabName }
}
private fun selectMainLog(cm: ContentManager): Boolean {
val mainContent = findMainLog(cm) ?: return false
cm.setSelectedContent(mainContent)
return true
}
fun selectMainLog(project: Project): Boolean {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return false
return selectMainLog(toolWindow.contentManager)
}
@JvmStatic
fun updateLogUiName(project: Project, ui: VcsLogUi) {
val toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ChangesViewContentManager.TOOLWINDOW_ID) ?: return
val manager = toolWindow.contentManager
val component = ContentUtilEx.findContentComponent(manager) { c: JComponent -> ui === getLogUi(c) } ?: return
ContentUtilEx.updateTabbedContentDisplayName(manager, component)
}
@ApiStatus.ScheduledForRemoval
@Deprecated("use VcsProjectLog#runWhenLogIsReady(Project, Consumer) instead.")
@JvmStatic
@RequiresBackgroundThread
fun getOrCreateLog(project: Project): VcsLogManager? {
VcsProjectLog.ensureLogCreated(project)
return VcsProjectLog.getInstance(project).logManager
}
} | apache-2.0 | aaf760e64001e2905f998db13ed2f25c | 41.238806 | 137 | 0.74112 | 4.657613 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/code-insight/api/src/org/jetbrains/kotlin/idea/codeinsight/api/classic/quickfixes/QuickFixesPsiBasedFactory.kt | 5 | 2784 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.psi.PsiElement
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
abstract class QuickFixesPsiBasedFactory<PSI : PsiElement>(
private val classTag: KClass<PSI>,
private val suitabilityChecker: PsiElementSuitabilityChecker<PSI>,
) : QuickFixFactory {
fun createQuickFix(psiElement: PsiElement): List<IntentionAction> {
checkIfPsiElementIsSupported(psiElement)
@Suppress("UNCHECKED_CAST")
return doCreateQuickFix(psiElement as PSI)
}
private fun checkIfPsiElementIsSupported(psiElement: PsiElement) {
if (!psiElement::class.isSubclassOf(classTag)) {
throw InvalidPsiElementTypeException(
expectedPsiType = psiElement::class,
actualPsiType = classTag,
factoryName = this::class.toString()
)
}
@Suppress("UNCHECKED_CAST")
if (!suitabilityChecker.isSupported(psiElement as PSI)) {
throw UnsupportedPsiElementException(psiElement, this::class.toString())
}
}
protected abstract fun doCreateQuickFix(psiElement: PSI): List<IntentionAction>
}
inline fun <reified PSI : PsiElement> quickFixesPsiBasedFactory(
suitabilityChecker: PsiElementSuitabilityChecker<PSI> = PsiElementSuitabilityCheckers.ALWAYS_SUITABLE,
crossinline createQuickFix: (PSI) -> List<IntentionAction>,
): QuickFixesPsiBasedFactory<PSI> {
return object : QuickFixesPsiBasedFactory<PSI>(PSI::class, suitabilityChecker) {
override fun doCreateQuickFix(psiElement: PSI): List<IntentionAction> = createQuickFix(psiElement)
}
}
inline fun <reified PSI : PsiElement, reified PSI2 : PsiElement> QuickFixesPsiBasedFactory<PSI>.coMap(
suitabilityChecker: PsiElementSuitabilityChecker<PSI2> = PsiElementSuitabilityCheckers.ALWAYS_SUITABLE,
crossinline map: (PSI2) -> PSI?
): QuickFixesPsiBasedFactory<PSI2> {
return quickFixesPsiBasedFactory(suitabilityChecker) { psiElement ->
val newPsi = map(psiElement) ?: return@quickFixesPsiBasedFactory emptyList()
createQuickFix(newPsi)
}
}
class InvalidPsiElementTypeException(
expectedPsiType: KClass<out PsiElement>,
actualPsiType: KClass<out PsiElement>,
factoryName: String,
) : Exception("PsiElement with type $expectedPsiType is expected but $actualPsiType found for $factoryName")
class UnsupportedPsiElementException(
psiElement: PsiElement,
factoryName: String
) : Exception("PsiElement $psiElement is unsopported for $factoryName")
| apache-2.0 | 17de27bdc5e68a3b0ba0a88ae95f631a | 39.941176 | 120 | 0.74533 | 5.184358 | false | false | false | false |
ingokegel/intellij-community | platform/build-scripts/groovy/org/jetbrains/intellij/build/impl/BuildContextImpl.kt | 1 | 14006 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceJavaStaticMethodWithKotlinAnalog")
package org.jetbrains.intellij.build.impl
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.Strings
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
import io.opentelemetry.api.trace.Span
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import org.jetbrains.intellij.build.*
import org.jetbrains.intellij.build.dependencies.BuildDependenciesCommunityRoot
import org.jetbrains.intellij.build.dependencies.DependenciesProperties
import org.jetbrains.jps.model.JpsModel
import org.jetbrains.jps.model.JpsProject
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.module.JpsModule
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.util.JpsPathUtil
import java.nio.file.Files
import java.nio.file.Path
import java.util.concurrent.ConcurrentLinkedQueue
class BuildContextImpl private constructor(private val compilationContext: CompilationContextImpl,
override val productProperties: ProductProperties,
override val windowsDistributionCustomizer: WindowsDistributionCustomizer?,
override val linuxDistributionCustomizer: LinuxDistributionCustomizer?,
override val macDistributionCustomizer: MacDistributionCustomizer?,
override val proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY,
private val distFiles: ConcurrentLinkedQueue<Map.Entry<Path, String>>) : BuildContext {
override val fullBuildNumber: String
get() = "${applicationInfo.productCode}-$buildNumber"
override val systemSelector: String
get() = productProperties.getSystemSelector(applicationInfo, buildNumber)
override val buildNumber: String = options.buildNumber ?: readSnapshotBuildNumber(paths.communityHomeDir)
override val xBootClassPathJarNames: List<String>
get() = productProperties.xBootClassPathJarNames
override var bootClassPathJarNames = persistentListOf("util.jar", "util_rt.jar")
override val applicationInfo: ApplicationInfoProperties = ApplicationInfoPropertiesImpl(project, productProperties, options).patch(this)
private var builtinModulesData: BuiltinModulesFileData? = null
init {
@Suppress("DEPRECATION")
if (productProperties.productCode == null) {
productProperties.productCode = applicationInfo.productCode
}
check(!systemSelector.contains(' ')) {
"System selector must not contain spaces: $systemSelector"
}
options.buildStepsToSkip.addAll(productProperties.incompatibleBuildSteps)
if (!options.buildStepsToSkip.isEmpty()) {
Span.current().addEvent("build steps to be skipped", Attributes.of(
AttributeKey.stringArrayKey("stepsToSkip"), options.buildStepsToSkip.toImmutableList()
))
}
}
companion object {
@JvmStatic
@JvmOverloads
fun createContext(communityHome: BuildDependenciesCommunityRoot,
projectHome: Path,
productProperties: ProductProperties,
proprietaryBuildTools: ProprietaryBuildTools = ProprietaryBuildTools.DUMMY,
options: BuildOptions = BuildOptions()): BuildContextImpl {
val projectHomeAsString = FileUtilRt.toSystemIndependentName(projectHome.toString())
val windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeAsString)
val linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeAsString)
val macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeAsString)
val compilationContext = CompilationContextImpl.create(
communityHome = communityHome,
projectHome = projectHome,
buildOutputRootEvaluator = createBuildOutputRootEvaluator(projectHome, productProperties, options),
options = options
)
return BuildContextImpl(compilationContext = compilationContext,
productProperties = productProperties,
windowsDistributionCustomizer = windowsDistributionCustomizer,
linuxDistributionCustomizer = linuxDistributionCustomizer,
macDistributionCustomizer = macDistributionCustomizer,
proprietaryBuildTools = proprietaryBuildTools,
distFiles = ConcurrentLinkedQueue())
}
}
override var builtinModule: BuiltinModulesFileData?
get() {
if (options.buildStepsToSkip.contains(BuildOptions.PROVIDED_MODULES_LIST_STEP)) {
return null
}
return builtinModulesData ?: throw IllegalStateException("builtinModulesData is not set. " +
"Make sure `BuildTasksImpl.buildProvidedModuleList` was called before")
}
set(value) {
check(builtinModulesData == null) { "builtinModulesData was already set" }
builtinModulesData = value
}
override fun addDistFile(file: Map.Entry<Path, String>) {
messages.debug("$file requested to be added to app resources")
distFiles.add(file)
}
override fun getDistFiles(): Collection<Map.Entry<Path, String>> {
return java.util.List.copyOf(distFiles)
}
override fun findApplicationInfoModule(): JpsModule {
return findRequiredModule(productProperties.applicationInfoModule)
}
override val options: BuildOptions
get() = compilationContext.options
@Suppress("SSBasedInspection")
override val messages: BuildMessages
get() = compilationContext.messages
override val dependenciesProperties: DependenciesProperties
get() = compilationContext.dependenciesProperties
override val paths: BuildPaths
get() = compilationContext.paths
override val bundledRuntime: BundledRuntime
get() = compilationContext.bundledRuntime
override val project: JpsProject
get() = compilationContext.project
override val projectModel: JpsModel
get() = compilationContext.projectModel
override val compilationData: JpsCompilationData
get() = compilationContext.compilationData
override val stableJavaExecutable: Path
get() = compilationContext.stableJavaExecutable
override val stableJdkHome: Path
get() = compilationContext.stableJdkHome
override val projectOutputDirectory: Path
get() = compilationContext.projectOutputDirectory
override fun findRequiredModule(name: String): JpsModule {
return compilationContext.findRequiredModule(name)
}
override fun findModule(name: String): JpsModule? {
return compilationContext.findModule(name)
}
override fun getOldModuleName(newName: String): String? {
return compilationContext.getOldModuleName(newName)
}
override fun getModuleOutputDir(module: JpsModule): Path {
return compilationContext.getModuleOutputDir(module)
}
override fun getModuleTestsOutputPath(module: JpsModule): String {
return compilationContext.getModuleTestsOutputPath(module)
}
override fun getModuleRuntimeClasspath(module: JpsModule, forTests: Boolean): List<String> {
return compilationContext.getModuleRuntimeClasspath(module, forTests)
}
override fun notifyArtifactBuilt(artifactPath: Path) {
compilationContext.notifyArtifactWasBuilt(artifactPath)
}
override fun notifyArtifactWasBuilt(artifactPath: Path) {
compilationContext.notifyArtifactWasBuilt(artifactPath)
}
override fun findFileInModuleSources(moduleName: String, relativePath: String): Path? {
for (info in getSourceRootsWithPrefixes(findRequiredModule(moduleName))) {
if (relativePath.startsWith(info.second)) {
val result = info.first.resolve(Strings.trimStart(Strings.trimStart(relativePath, info.second), "/"))
if (Files.exists(result)) {
return result
}
}
}
return null
}
override fun signFiles(files: List<Path>, options: Map<String, String>) {
if (proprietaryBuildTools.signTool == null) {
Span.current().addEvent("files won't be signed", Attributes.of(
AttributeKey.stringArrayKey("files"), files.map(Path::toString),
AttributeKey.stringKey("reason"), "sign tool isn't defined")
)
}
else {
proprietaryBuildTools.signTool.signFiles(files, this, options)
}
}
override fun executeStep(stepMessage: String, stepId: String, step: Runnable): Boolean {
if (options.buildStepsToSkip.contains(stepId)) {
Span.current().addEvent("skip step", Attributes.of(AttributeKey.stringKey("name"), stepMessage))
}
else {
messages.block(stepMessage, step::run)
}
return true
}
override fun shouldBuildDistributions(): Boolean {
return options.targetOs.lowercase() != BuildOptions.OS_NONE
}
override fun shouldBuildDistributionForOS(os: OsFamily, arch: JvmArchitecture): Boolean {
return shouldBuildDistributions()
&& listOf(BuildOptions.OS_ALL, os.osId).contains(options.targetOs.lowercase())
&& (options.targetArch == null || options.targetArch == arch)
}
override fun createCopyForProduct(productProperties: ProductProperties, projectHomeForCustomizers: Path): BuildContext {
val projectHomeForCustomizersAsString = FileUtilRt.toSystemIndependentName(projectHomeForCustomizers.toString())
/**
* FIXME compiled classes are assumed to be already fetched in the FIXME from [CompilationContextImpl.prepareForBuild], please change them together
*/
val options = BuildOptions()
options.useCompiledClassesFromProjectOutput = true
val compilationContextCopy = compilationContext.createCopy(
messages = messages,
options = options,
buildOutputRootEvaluator = createBuildOutputRootEvaluator(paths.projectHome, productProperties, options)
)
val copy = BuildContextImpl(
compilationContext = compilationContextCopy,
productProperties = productProperties,
windowsDistributionCustomizer = productProperties.createWindowsCustomizer(projectHomeForCustomizersAsString),
linuxDistributionCustomizer = productProperties.createLinuxCustomizer(projectHomeForCustomizersAsString),
macDistributionCustomizer = productProperties.createMacCustomizer(projectHomeForCustomizersAsString),
proprietaryBuildTools = proprietaryBuildTools,
distFiles = ConcurrentLinkedQueue()
)
@Suppress("DEPRECATION") val productCode = productProperties.productCode
copy.paths.artifactDir = paths.artifactDir.resolve(productCode!!)
copy.paths.artifacts = "${paths.artifacts}/$productCode"
copy.compilationContext.prepareForBuild()
return copy
}
override fun includeBreakGenLibraries() = isJavaSupportedInProduct
private val isJavaSupportedInProduct: Boolean
get() = productProperties.productLayout.bundledPluginModules.contains("intellij.java.plugin")
override fun patchInspectScript(path: Path) {
//todo[nik] use placeholder in inspect.sh/inspect.bat file instead
Files.writeString(path, Files.readString(path).replace(" inspect ", " ${productProperties.inspectCommandName} "))
}
override fun getAdditionalJvmArguments(os: OsFamily): List<String> {
val jvmArgs: MutableList<String> = ArrayList()
val classLoader = productProperties.classLoader
if (classLoader != null) {
jvmArgs.add("-Djava.system.class.loader=$classLoader")
}
jvmArgs.add("-Didea.vendor.name=${applicationInfo.shortCompanyName}")
jvmArgs.add("-Didea.paths.selector=$systemSelector")
if (productProperties.platformPrefix != null) {
jvmArgs.add("-Didea.platform.prefix=${productProperties.platformPrefix}")
}
jvmArgs.addAll(productProperties.additionalIdeJvmArguments)
if (productProperties.useSplash) {
@Suppress("SpellCheckingInspection")
jvmArgs.add("-Dsplash=true")
}
jvmArgs.addAll(getCommandLineArgumentsForOpenPackages(this, os))
return jvmArgs
}
}
private fun createBuildOutputRootEvaluator(projectHome: Path,
productProperties: ProductProperties,
buildOptions: BuildOptions): (JpsProject) -> Path {
return { project ->
val appInfo = ApplicationInfoPropertiesImpl(project = project,
productProperties = productProperties,
buildOptions = buildOptions)
projectHome.resolve("out/${productProperties.getOutputDirectoryName(appInfo)}")
}
}
private fun getSourceRootsWithPrefixes(module: JpsModule): Sequence<Pair<Path, String>> {
return module.sourceRoots.asSequence()
.filter { root: JpsModuleSourceRoot ->
JavaModuleSourceRootTypes.PRODUCTION.contains(root.rootType)
}
.map { moduleSourceRoot: JpsModuleSourceRoot ->
var prefix: String
val properties = moduleSourceRoot.properties
prefix = if (properties is JavaSourceRootProperties) {
properties.packagePrefix.replace(".", "/")
}
else {
(properties as JavaResourceRootProperties).relativeOutputPath
}
if (!prefix.endsWith("/")) {
prefix += "/"
}
Pair(Path.of(JpsPathUtil.urlToPath(moduleSourceRoot.url)), prefix.trimStart('/'))
}
}
private fun readSnapshotBuildNumber(communityHome: BuildDependenciesCommunityRoot): String {
return Files.readString(communityHome.communityRoot.resolve("build.txt")).trim { it <= ' ' }
}
| apache-2.0 | 7ff65afdfdb0dc2179d00bb1980a56c0 | 43.322785 | 151 | 0.728402 | 5.728425 | false | false | false | false |
sys1yagi/longest-streak-android | app/src/main/java/com/sys1yagi/longeststreakandroid/tool/LongestStreakCounter.kt | 1 | 1928 | package com.sys1yagi.longeststreakandroid.tool
import android.util.Log
import com.sys1yagi.longeststreakandroid.db.OrmaDatabase
import com.sys1yagi.longeststreakandroid.model.Event
import java.util.*
class LongestStreakCounter {
val a = Calendar.getInstance()
val b = Calendar.getInstance()
fun count(database: OrmaDatabase, now: Long, zoneId: String): Int {
var streaksBegin = TimeKeeper.day(now, zoneId)
var count = 0
database.selectFromEventLog()
.orderByCreatedAtDesc()
.toList()
.forEach {
System.out.println("${it.type}")
when (it.type) {
Event.Type.PUSH, Event.Type.ISSUES, Event.Type.PULL_REQUEST -> {
val day = TimeKeeper.day(it.createdAt, zoneId)
if ((streaksBegin == day && count == 0)
|| isMatchYesterday(streaksBegin, day)
) {
count++
streaksBegin = day
} else if (streaksBegin != day ) {
return count
}
}
}
}
return count
}
fun isMatchYesterday(today: Long, day: Long): Boolean {
if (today - 1 == day) {
return true
}
var t = today.toInt()
a.set(Calendar.YEAR, t / 10000)
t = t % 10000
a.set(Calendar.MONTH, t / 100 - 1)
t = t % 100
a.set(Calendar.DAY_OF_MONTH, t)
var d = day.toInt()
b.set(Calendar.YEAR, d / 10000)
d = d % 10000
b.set(Calendar.MONTH, d / 100 - 1)
d = d % 100
b.set(Calendar.DAY_OF_MONTH, d)
a.add(Calendar.DAY_OF_MONTH, -1)
return a.equals(b)
}
}
| mit | 0134e0973f085451609854b44c435ad2 | 31.133333 | 88 | 0.475622 | 4.473318 | false | false | false | false |
leksak/kilobyte | src/main/kotlin/kilobyte/common/instruction/parametrizedroutines/ParametrizedInstructionRoutines.kt | 1 | 18467 | package kilobyte.common.instruction.parametrizedroutines
import com.google.common.base.Preconditions.checkArgument
import kilobyte.common.extensions.*
import kilobyte.common.hardware.RegisterFile
import kilobyte.common.instruction.DecompiledInstruction
import kilobyte.common.instruction.Format
import kilobyte.common.instruction.Instruction
import kilobyte.common.instruction.decomposedrepresentation.DecomposedRepresentation
import kilobyte.common.instruction.exceptions.IllegalCharactersInMnemonicException
import kilobyte.common.instruction.exceptions.MalformedMnemonicException
import kilobyte.common.instruction.mnemonic.iname
import kilobyte.common.instruction.mnemonic.standardizeMnemonic
import kilobyte.common.instruction.mnemonic.throwExceptionIfContainsIllegalCharacters
import kilobyte.common.instruction.mnemonic.throwIfIncorrectNumberOfCommas
import kilobyte.common.machinecode.*
import kilobyte.decompiler.MachineCodeDecoder
import java.util.*
val fieldNameToIndexMap = mapOf(
"rs" to 1,
"rt" to 2,
"rd" to 3,
"shamt" to 4,
"funct" to 5,
"offset" to 3,
"address" to 3,
"target" to 1,
"hint" to 2 // pseudo field
)
fun indexOf(fieldName: String): Int {
return fieldNameToIndexMap[fieldName]!!
}
val fieldNameToMethodCallMap: HashMap<String, (n: MachineCode) -> Int> = hashMapOf(
Pair("rs", MachineCode::rs),
Pair("rt", MachineCode::rt),
Pair("rd", MachineCode::rd),
Pair("shamt", MachineCode::shamt),
Pair("funct", MachineCode::funct),
Pair("offset", MachineCode::offset),
Pair("target", MachineCode::target),
Pair("address", MachineCode::offset),
Pair("hint", MachineCode::hint)
)
/**
* Hint-variable descriptions
* source: http://www.cs.cmu.edu/afs/cs/academic/class/15740-f97/public/doc/mips-isa.pdf
* page A-117
* Reference: MIPS-instruction with prefix 'PREF'
*/
enum class Hint(val value: Int) {
LOAD(0),
STORE(1),
LOAD_STREAMED(3),
STORE_STREAMED(5),
LOAD_RETAINED(6),
STORE_RETAINED(7);
companion object {
fun from(findValue: Int): Hint = values().first { it.value == findValue }
}
fun description(value: Int): String {
when (value) {
LOAD.value -> return "Data is expected to be loaded (not modified). " +
"Fetch data as if for a load"
STORE.value -> return "Data is expected to be stored or modified. " +
"Fetch data as if for a store."
LOAD_STREAMED.value -> return "Data is expected to be loaded (not " +
"modified) but not reused extensively; " +
"it will “stream” through cache. Fetch " +
"data as if for a load and place it in " +
"the cache so that it will not displace " +
"data prefetched as 'retained'."
STORE_STREAMED.value -> return "Data is expected to be stored or modified " +
"but not reused extensively; it will " +
"'stream' through cache. Fetch data as if " +
"for a store and place it in the cache so " +
"that it will not displace data " +
"prefetched as 'retained'."
LOAD_RETAINED.value -> return "Data is expected to be loaded (not " +
"modified) and reused extensively; it " +
"should be “retained” in the cache. Fetch " +
"data as if for a load and place it in the " +
"cache so that it will not be displaced by " +
"data prefetched as “streamed”"
STORE_RETAINED.value -> return "Data is expected to be stored or " +
"modified and reused extensively; it " +
"should be “retained” in the cache. " +
"Fetch data as if for a store and place " +
"it in the cache so that will not be " +
"displaced by data prefetched as “streamed”."
else -> return "Not yet defined."
}
}
}
/**
* This method creates objects implementing the ParametrizedInstructionRoutine
* by utilizing the given format to make assertions as to what manner 32-bit
* integers are to be interpreted and the given string as a template to
* pattern-match supplied mnemonics against.
*
* This method creates bi-directional parametrized routines for
* Instruction instantiation using the format of the instruction and a
* "abstract" String representation of the "mnemonic pattern", i.e.
*
* "iname rd, rs, rt" is the "abstract" "mnemonic pattern"
*
* This text will first provide one example of how to interpret two
* R-format instruction and an I-format instruction to showcase the
* similarities between how to represent them despite them having
* different "mnemonic patterns" to serve as a background for the
* abstraction for creating these patterns from String representations
* alone.
*
* Example 1 (R-format):
* =====================
*
* The "add" instruction is expressed on the form,
*
* iname rd, rs, rt (1.1)
*
* which means that for
*
* add $t1, $t2, $t3 (1.2)
*
* we get that rd=$t1, rs=$t2, and rt=$t3.
*
* Using the String representation of (1.1) we can determine the number of
* arguments. The correct number of commas can then be inferred to be the
* number of arguments minus one, i.e. (argc - 1) where argc is the
* argument count.
*
* From the Format we know the constituents of the Instruction when
* represented in its numerical form, for the R-format especially we
* have that it decomposes into the following fields,
*
* | 6 bits | 5 bits | 5 bits | 5 bits | 5 bits | 6 bits |
* |:-------:|:------:|:------:|:------:|:------:|:-------:|
* | op | rs | rt | rd | shamt | funct |
*
* Hence, when parsing (1.2) we assign the arguments into an integer
* array with 6 elements (all defaulting to zero) like so,
*
* arr = [op, $t2, $t3, $t1, 0, funct]
* ^
* |
* default value
*
* Note that the actual values for the opcode and funct field are
* retrieved elsewhere. Since the shamt parameter is not part of the
* "mnemonic pattern" then we know it to be zero.
*
* Important:
* ==========
*
* Derived from the mnemonic pattern we know what constraints need to be
* placed on the respective fields, in this example we have that shamt
* has to be 0, to wit we can evaluate the legality of a given numeric
* representation of the instruction. It is because of this property we
* present the two operations (instantiation from a string and a number)
* as a cohesive unit.
*
* As stated earlier, the "opcode" and "funct" field are accessible as
* delegates supplied by another object and with that the entire 32-bit number
* can be decompiled.
*
* Example 2 (R-format):
* =====================
*
* The "mult" instruction is expressed on the form,
*
* mult rs, rt, for an example "mult $t1, $t2"
*
* As in "Example 1" the text alone allows us to infer the expected
* argument count, which is two of course, and the appropriate number of
* commas. Combined with the fact that the instruction is in the R-format
* and the opcode and funct field is retrievable elsewhere we get that
*
* arr = [op, $t1, $t2, 0, 0, funct]
* ^ ^
* | |
* default values
*
* Example 3 (I-format):
* =====================
*
* All I-format instructions are decomposed into fields of the same
* length.
*
* An I-type instruction is determined uniquely by its opcode field.
*
* The opcode is the leftmost 6-bits of the instruction when
* represented as a 32-bit number.
*
* From the Format we know the constituents of the Instruction when
* represented in its numerical form. Specifically for the I-format we
* have that it decomposes into the following fields,
*
* | 6 bits | 5 bits | 5 bits | 16 bits |
* |:-------:|:------:|:------:|:-------:|
* | op | rs | rt | offset |
*
* I-format instructions are traditionally written on the form,
*
* iname rt, offset
*
* For an example,
*
* lw $t0, 24($s2)
*
* which is represented numerically as
*
* | op | rs | rt | offset |
* |:-------:|:------:|:------:|:-------:|
* | 0x23 | 18 | 8 | 24_{10} |
*
* meaning that rs=$s2, rt=$t0, and the offset=24.
*/
interface ParametrizedInstructionRoutine {
fun invoke(prototype: Instruction, machineCode: MachineCode): DecompiledInstruction
fun invoke(prototype: Instruction, mnemonicRepresentation: String): Instruction
}
fun from(format: Format, pattern: String): ParametrizedInstructionRoutine {
/*
* We standardize the pattern to ensure consistency not out of necessity.
* That way we do not have to worry about fudging up our definitions
* by writing say "iname rt,offset" instead of "iname rt, offset".
*/
val standardizedPattern = standardizeMnemonic(pattern)
/*
* We create an array of the tokens in the standardized array, in the
* above example we get that fields = ["iname", "rt", "offset"]
*/
val fields = standardizedPattern.tokenize()
return object : ParametrizedInstructionRoutine {
override fun invoke(prototype: Instruction,
mnemonicRepresentation: String): Instruction {
val standardizedMnemonic = standardizeMnemonic(mnemonicRepresentation)
throwExceptionIfContainsIllegalCharacters(standardizedMnemonic)
val expectedNumberOfCommas = standardizedPattern.countCommas()
throwIfIncorrectNumberOfCommas(expectedNumberOfCommas, mnemonicRepresentation)
val expectedNumberOfArguments = standardizedPattern.replace(",", "").split(" ").size - 1
throwIfIncorrectNumberOfArgs(expectedNumberOfArguments, standardizedMnemonic)
if (!isAllowedToContainParentheses(format) && standardizedMnemonic.containsParentheses()) {
throw IllegalCharactersInMnemonicException(standardizedMnemonic, "<parentheses>")
}
checkArgument(prototype.iname == standardizedMnemonic.iname())
/*
* For instructions expressed using the mnemonic-pattern "iname rd, rs, rt"
* we get that the contents of the tokens array will contain
* the _values_ of rd, rs, and rt, (and _not_ the string literals
* "rd", "rs, "rt") like so:
*
* tokens=[rd, rs, rt]
*
* however, the arguments rd, rs, rt do not appear in the same
* order as they have to when represented numerically so we
* use the "fields" array which tells us what values we are observing
* inside the "tokens" array together with "fieldNameToIndexMap"
* to place the values at the correct places.
*/
val tokens: Array<String> = standardizedMnemonic.tokenize()
val opcode = prototype.opcode
val n = IntArray(format.noOfFields)
n[0] = opcode
if (format == Format.R || prototype == Instruction.JALR) {
n[5] = prototype.funct!!
}
if (prototype.opcode == 1) {
assert(prototype.rt != null)
/* The prototype will have its rt field set whenever
* its opcode is equal to 1. This is the case for
* branch-instructions such as BLTZL, BGEZ but also
* trap instructions!
*
* For instance, BLTZL: op=1, rt=2
* BGEZ: op=1, rt=1
* TGEI: op=1, rt=8
*/
val index = indexOf("rt")
n[index] = prototype.rt!!
}
// TODO: Why? return value is not captured does this happen in-place?
formatMnemonic(tokens, n, prototype, fields)
if (prototype == Instruction.JAL) {
// The jump instruction (jal) specifies an absolute memory address
// (in bytes) to jump to, but is coded without its last two bits.
n[1] = (MachineCodeDecoder.decode(tokens[1]) shr 2).toInt()
}
val d = DecomposedRepresentation.fromIntArray(n, *format.lengths).asLong()
return prototype(standardizedMnemonic, d)
}
/**
* When in machineCode, we trust.
**/
override fun invoke(prototype: Instruction, machineCode: MachineCode): DecompiledInstruction {
val mnemonicRepresentation = formatMachineCodeToMnemonic(prototype,
machineCode,
fields)
val inst = prototype(mnemonicRepresentation, machineCode)
val errors = errorCheckPrototype(machineCode, format, fields)
if (errors.isNotEmpty()) {
return DecompiledInstruction.PartiallyValid(inst, errors)
}
return DecompiledInstruction.Valid(inst)
}
}
}
private fun shouldFieldBeZero(fieldName: String, fields: Array<String>): Boolean {
return !fields.contains(fieldName)
}
private fun fieldIsNotZero(fieldName: String, machineCode: MachineCode): Boolean {
return fieldNameToMethodCallMap[fieldName]!!.invoke(machineCode) != 0
}
private fun errorCheckPrototype(machineCode: MachineCode,
format: Format,
fields: Array<String>): ArrayList<String> {
val errors = ArrayList<String>()
when (format) {
Format.R -> {
// TODO: Can definitely be refactored
if (shouldFieldBeZero("shamt", fields) && fieldIsNotZero("shamt", machineCode)) {
errors.add("Expected shamt to be zero. Got ${machineCode.shamt()}")
}
if (shouldFieldBeZero("rd", fields) && fieldIsNotZero("rd", machineCode)) {
errors.add("Expected rd to be zero. Got ${machineCode.rd()}")
}
if (shouldFieldBeZero("rt", fields) && fieldIsNotZero("rt", machineCode)) {
errors.add("Expected rt to be zero. Got ${machineCode.rt()}")
}
if (shouldFieldBeZero("rs", fields) && fieldIsNotZero("rs", machineCode)) {
errors.add("Expected rs to be zero. Got ${machineCode.rs()}")
}
}
Format.I -> {
}
Format.J -> {
}
else -> {
throw IllegalStateException("Attempted to instantiate " +
"a instruction from an unknown format. Format: $format")
}
}
return errors
}
private fun formatMachineCodeToMnemonic(prototype: Instruction,
machineCode: MachineCode,
fields: Array<String>): String {
val iname = prototype.iname
var mnemonicRepresentation = "$iname "
for (i in fields.indices) {
// The fields are given in order, so we can just concatenate
// the strings.
when (fields[i]) {
"rd" -> mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rd())
"rt" -> mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rt())
"rs" -> mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rs())
"offset" -> mnemonicRepresentation += machineCode.offset().toString()
"target" -> mnemonicRepresentation += machineCode.target().toString()
"shamt" -> mnemonicRepresentation += machineCode.shamt().toString()
"address" -> {
mnemonicRepresentation += machineCode.offset().toString()
if (!fields.contains("rs") && iname != "lui") {
mnemonicRepresentation += "("
mnemonicRepresentation += RegisterFile.getMnemonic(machineCode.rs())
mnemonicRepresentation += ")"
}
}
"hint" -> {
mnemonicRepresentation += machineCode.hint().toString()
prototype.hint = Hint.from(machineCode.hint())
}
}
if (i != fields.indices.first && i != fields.indices.last) {
mnemonicRepresentation += ", "
}
}
return mnemonicRepresentation.trim()
}
private fun formatMnemonic(tokens: Array<String>, n: IntArray, prototype: Instruction, fields: Array<String>): Array<String> {
for (i in 1..tokens.size - 1) {
// from 1 so that we can skip the iname
val destinationIndex: Int = indexOf(fields[i])
when (fields[i]) {
"target" -> n[destinationIndex] = tokens[i].getOffset()
"offset" -> n[destinationIndex] = tokens[i].getOffset()
"address" -> {
n[destinationIndex] = tokens[i].getOffset()
n[indexOf("rs")] = RegisterFile.indexOf(tokens[i].getRegister())
}
"hint" -> {
val hint = tokens[i].getOffset()
n[destinationIndex] = hint
prototype.hint = Hint.from(hint)
}
"shamt" -> {
// Handles for instance the "19" in sll $s1, $t1, 19
n[destinationIndex] = tokens[i].toInt()
}
else -> n[destinationIndex] = RegisterFile.indexOf(tokens[i])
}
}
return tokens
}
fun isAllowedToContainParentheses(format: Format): Boolean {
return (format == Format.I)
}
/**
* Check if given String contains correct number of arguments. Arguments is
* how many parameters an instruction has been given.
* Example:
* add $t1, $t2, $t3 (3)
* jr $t1 (1)
* break (0)
*/
fun throwIfIncorrectNumberOfArgs(expectedArgc: Int, standardizedMnemonic: String) {
// -1 for the instruction name
val withoutCommas = standardizedMnemonic.removeCommas()
val actualArgc = withoutCommas.split(" ").size - 1
if (expectedArgc == actualArgc) {
return
}
val err = "Wrong number of arguments. Expected $expectedArgc arguments. Got: $actualArgc"
throw MalformedMnemonicException(standardizedMnemonic, err)
}
@JvmField val EXIT_PATTERN = from(Format.EXIT, "iname")
@JvmField val INAME = from(Format.R, "iname")
@JvmField val INAME_RS = from(Format.R, "iname rs")
@JvmField val INAME_RD = from(Format.R, "iname rd")
@JvmField val INAME_RS_RT = from(Format.R, "iname rs, rt")
@JvmField val INAME_RD_RS = from(Format.R, "iname rd, rs")
@JvmField val INAME_RD_RS_RT = from(Format.R, "iname rd, rs, rt")
@JvmField val INAME_RD_RT_SHAMT = from(Format.R, "iname rd, rt, shamt")
/**
* The difference between offset and address is that address will accept an
* syntax of N($REG) while offset will not. Offset can be referred as
* immediate-instruction-type like N whereas N is an number.
*/
@JvmField val INAME_RT_OFFSET = from(Format.I, "iname rt, offset")
@JvmField val INAME_RS_OFFSET = from(Format.I, "iname rs, offset")
@JvmField val INAME_RS_RT_OFFSET = from(Format.I, "iname rs, rt, offset")
@JvmField val INAME_RT_RS_OFFSET = from(Format.I, "iname rt, rs, offset")
@JvmField val INAME_RT_ADDRESS = from(Format.I, "iname rt, address")
@JvmField val INAME_HINT_ADDRESS = from(Format.I, "iname hint, address")
@JvmField val INAME_TARGET = from(Format.J, "iname target") | mit | 3cf2d339dee964034a14501bd164f31d | 37.594142 | 126 | 0.647531 | 4.134245 | false | false | false | false |