content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
// 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.ui.actions import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.ui.MessageType import com.intellij.openapi.util.NlsActions import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.vcs.ui.VcsBalloonProblemNotifier import com.intellij.testFramework.LightVirtualFile import com.intellij.util.text.DateFormatUtil import com.intellij.vcs.log.* import com.intellij.vcs.log.data.AbstractDataGetter.Companion.getCommitDetails import com.intellij.vcs.log.data.VcsLogData import com.intellij.vcs.log.data.index.IndexDiagnostic.getDiffFor import com.intellij.vcs.log.data.index.IndexDiagnostic.getFirstCommits import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.impl.VcsLogManager import com.intellij.vcs.log.impl.VcsProjectLog import java.util.* import java.util.function.Supplier abstract class IndexDiagnosticActionBase(dynamicText: Supplier<@NlsActions.ActionText String>) : DumbAwareAction(dynamicText) { override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT override fun update(e: AnActionEvent) { val project = e.project if (project == null) { e.presentation.isEnabledAndVisible = false return } val logManager = VcsProjectLog.getInstance(project).logManager if (logManager == null) { e.presentation.isEnabledAndVisible = false return } if (logManager.dataManager.index.dataGetter == null) { e.presentation.isEnabledAndVisible = false return } update(e, logManager) } override fun actionPerformed(e: AnActionEvent) { val project = e.project!! val logManager = VcsProjectLog.getInstance(project).logManager ?: return val dataGetter = logManager.dataManager.index.dataGetter ?: return val commitIds = getCommitsToCheck(e, logManager) if (commitIds.isEmpty()) return val report = ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable { val detailsList = logManager.dataManager.commitDetailsGetter.getCommitDetails(commitIds) return@ThrowableComputable dataGetter.getDiffFor(commitIds, detailsList) }, VcsLogBundle.message("vcs.log.index.diagnostic.progress.title"), false, project) if (report.isBlank()) { VcsBalloonProblemNotifier.showOverVersionControlView(project, VcsLogBundle.message("vcs.log.index.diagnostic.success.message", commitIds.size), MessageType.INFO) return } val reportFile = LightVirtualFile(VcsLogBundle.message("vcs.log.index.diagnostic.report.title", DateFormatUtil.formatDateTime(Date())), report.toString()) OpenFileDescriptor(project, reportFile, 0).navigate(true) } abstract fun update(e: AnActionEvent, logManager: VcsLogManager) abstract fun getCommitsToCheck(e: AnActionEvent, logManager: VcsLogManager): List<Int> } class CheckSelectedCommits : IndexDiagnosticActionBase(VcsLogBundle.messagePointer("vcs.log.index.diagnostic.selected.action.title")) { override fun update(e: AnActionEvent, logManager: VcsLogManager) { val selection = e.getData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION) if (selection == null) { e.presentation.isEnabledAndVisible = false return } val selectedCommits = getSelectedCommits(logManager.dataManager, selection, false) e.presentation.isVisible = true e.presentation.isEnabled = selectedCommits.isNotEmpty() } private fun getSelectedCommits(vcsLogData: VcsLogData, selection: VcsLogCommitSelection, reportNotIndexed: Boolean): List<Int> { val selectedCommits = selection.ids if (selectedCommits.isEmpty()) return emptyList() val selectedIndexedCommits = selectedCommits.filter { vcsLogData.index.isIndexed(it) } if (selectedIndexedCommits.isEmpty() && reportNotIndexed) { VcsBalloonProblemNotifier.showOverVersionControlView(vcsLogData.project, VcsLogBundle.message("vcs.log.index.diagnostic.selected.non.indexed.warning.message"), MessageType.WARNING) } return selectedIndexedCommits } override fun getCommitsToCheck(e: AnActionEvent, logManager: VcsLogManager): List<Int> { return getSelectedCommits(logManager.dataManager, e.getRequiredData(VcsLogDataKeys.VCS_LOG_COMMIT_SELECTION), true) } } class CheckOldCommits : IndexDiagnosticActionBase(VcsLogBundle.messagePointer("vcs.log.index.diagnostic.action.title")) { override fun update(e: AnActionEvent, logManager: VcsLogManager) { val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(logManager.dataManager.logProviders) if (rootsForIndexing.isEmpty()) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true e.presentation.isEnabled = logManager.dataManager.dataPack.isFull && rootsForIndexing.any { logManager.dataManager.index.isIndexed(it) } } override fun getCommitsToCheck(e: AnActionEvent, logManager: VcsLogManager): List<Int> { val indexedRoots = VcsLogPersistentIndex.getRootsForIndexing(logManager.dataManager.logProviders).filter { logManager.dataManager.index.isIndexed(it) } if (indexedRoots.isEmpty()) return emptyList() val dataPack = logManager.dataManager.dataPack if (!dataPack.isFull) return emptyList() return dataPack.getFirstCommits(logManager.dataManager.storage, indexedRoots) } }
platform/vcs-log/impl/src/com/intellij/vcs/log/ui/actions/IndexDiagnosticActions.kt
3158378630
fun main(args: Array<String>) { listOf(1.to<caret>Byte(), null).forEach { } }
plugins/kotlin/jvm-debugger/test/testData/sequence/psi/collection/positive/types/NullableByte.kt
854444820
class Bla : ImplementMe { override fun someF(s: String?, integer: Int) { } }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/SimpleFlexibleTypeAfter.1.kt
4030166389
class A { fun a() { (fun <caret>A.() { })() } }
plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedReceiverParameter/anonymousFunctionCall.kt
2152839575
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package example.dependency infix fun String.to(that: String) = this + that
plugins/kotlin/compiler-plugins/scripting-ide-services/testData/stringTo.kt
2375298749
package v_builders import util.TODO import java.util.* fun buildStringExample(): String { fun buildString(build: StringBuilder.() -> Unit): String { val stringBuilder = StringBuilder() stringBuilder.build() return stringBuilder.toString() } return buildString { this.append("Numbers: ") for (i in 1..10) { // 'this' can be omitted append(i) } } } fun todoTask37(): Nothing = TODO( """ Task 37. Uncomment the commented code and make it compile. Add and implement function 'buildMap' with one parameter (of type extension function) creating a new HashMap, building it and returning it as a result. """ ) fun task37(): Map<Int, String> { fun <K, V> buildMap(build: MutableMap<K, V>.() -> Unit): Map<K, V> { val map = HashMap<K, V>() map.build() return map } return buildMap { put(0, "0") for (i in 1..10) { put(i, "$i") } } }
src/v_builders/_37_StringAndMapBuilders.kt
3883860471
package douzifly.list.widget import android.animation.AnimatorSet import android.animation.ObjectAnimator import android.content.Context import android.graphics.Color import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.animation.AccelerateInterpolator import android.widget.LinearLayout import douzifly.list.R import java.util.* /** * Created by liuxiaoyuan on 2015/10/7. */ class ColorPicker(context: Context, attrs: AttributeSet) : LinearLayout(context, attrs) { companion object { fun getDimedColor(originColor: Int, dimFactor: Float = 0.94f): Int { val red = Color.red(originColor).toFloat() val green = Color.green(originColor).toFloat() val blue = Color.blue(originColor).toFloat() return Color.rgb((red * dimFactor).toInt(), (green * dimFactor).toInt(), (blue * dimFactor).toInt()) } } // 每一个颜色都是一个声音 val colors: Array<Long> = arrayOf( 0xff4285f4, // google blue 0xffec4536, // google brick red 0xfffbbd06, // google yellow 0xff34a852, // google green 0xffee468b, // pink 0xff3d7685, // steel blue 0xff572704, // chocolate 0xffe8d3a3 // tan ) inline fun randomColor(): Int = colors[Random(System.currentTimeMillis()).nextInt(colors.size)].toInt() var selectedColor: Int = colors[0].toInt() private set(color: Int) { field = color } var selectItem: Item? = null init { orientation = LinearLayout.HORIZONTAL setGravity(Gravity.CENTER_VERTICAL) colors.forEach { colorL -> val color = colorL.toInt() val view = LayoutInflater.from(context).inflate(R.layout.color_picker_item, this, false) val item = Item(view, color) addView(view) view.tag = item view.setOnClickListener { v -> val i = v.tag as Item setSelected(i) } } } fun setSelected(item: Item) { if (item == selectItem) { return } selectItem?.selected = false item.selected = true selectItem = item selectedColor = item.color } fun setSelected(color: Int) { val count = childCount for (i in 0..count-1) { val item = getChildAt(i).tag as Item if (color == item.color) { setSelected(item) break; } } } inner class Item( val view: View, val color: Int ) { init { view.setBackgroundColor(color) } var selected: Boolean = false set(value: Boolean) { if (field == value) return field = value updateUI() } private fun updateUI() { var scale = if (selected) 1.3f else 1.0f val animatorW = ObjectAnimator.ofFloat(view, "scaleX", scale) val animatorH = ObjectAnimator.ofFloat(view, "scaleY", scale) val animators = AnimatorSet() animators.playTogether(animatorH, animatorW) animators.setDuration(150) animators.interpolator = AccelerateInterpolator() animators.start() } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) if (childCount > 0) { val child0 = getChildAt(0) val h = child0.height * 1.6f setMeasuredDimension(widthMeasureSpec, View.MeasureSpec.makeMeasureSpec(h.toInt(), View.MeasureSpec.EXACTLY)) } } }
app/src/main/java/douzifly/list/widget/ColorPicker.kt
2507320645
// Copyright 2000-2021 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 mobi.hsz.idea.gitignore.indexing import com.intellij.openapi.util.Pair import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.VirtualFileManager import org.apache.commons.lang.builder.HashCodeBuilder import java.io.DataInput import java.io.DataOutput import java.io.IOException import java.io.Serializable /** * Entry containing information about the [VirtualFile] instance of the ignore file mapped with the collection * of ignore entries for better performance. Class is used for indexing. */ @Suppress("SerialVersionUIDInSerializableClass") class IgnoreEntryOccurrence(private val url: String, val items: List<Pair<String, Boolean>>) : Serializable { /** * Returns current [VirtualFile]. * * @return current file */ var file: VirtualFile? = null get() { if (field == null && url.isNotEmpty()) { field = VirtualFileManager.getInstance().findFileByUrl(url) } return field } private set companion object { @Synchronized @Throws(IOException::class) fun serialize(out: DataOutput, entry: IgnoreEntryOccurrence) { out.run { writeUTF(entry.url) writeInt(entry.items.size) entry.items.forEach { writeUTF(it.first) writeBoolean(it.second) } } } @Synchronized @Throws(IOException::class) fun deserialize(input: DataInput): IgnoreEntryOccurrence { val url = input.readUTF() val items = mutableListOf<Pair<String, Boolean>>() if (url.isNotEmpty()) { val size = input.readInt() repeat((0 until size).count()) { items.add(Pair.create(input.readUTF(), input.readBoolean())) } } return IgnoreEntryOccurrence(url, items) } } override fun hashCode() = HashCodeBuilder().append(url).apply { items.forEach { append(it.first).append(it.second) } }.toHashCode() override fun equals(other: Any?) = when { other !is IgnoreEntryOccurrence -> false url != other.url || items.size != other.items.size -> false else -> items.indices.find { items[it].toString() != other.items[it].toString() } == null } }
src/main/kotlin/mobi/hsz/idea/gitignore/indexing/IgnoreEntryOccurrence.kt
140231014
package com.github.kerubistan.kerub.security const val admin = "admin" const val user = "user" /** * The list of application roles. * See permissions assigned to roles in roles.ini */ enum class Roles(val roleName: String) { /** * The administrators are able to manage the infrastructure, manage hosts, storage, networks. */ Admin(admin), /** * Users can use the virtual machines created for them, but they can not create new resources. */ User(user) }
src/main/kotlin/com/github/kerubistan/kerub/security/Roles.kt
359450069
package com.jtransc.gen.common import com.jtransc.io.ProcessUtils import java.io.File abstract class BaseCompiler(val cmdName: String) { val cmd by lazy { ProcessUtils.which(cmdName) } val available by lazy { cmd != null } abstract fun genCommand(programFile: File, config: Config): List<String> data class Config( val debug: Boolean = false, val libs: List<String> = listOf(), val includeFolders: List<String> = listOf(), val libsFolders: List<String> = listOf(), val defines: List<String> = listOf() ) }
jtransc-core/src/com/jtransc/gen/common/BaseCompiler.kt
4233669919
/* * Charlatano: Free and open-source (FOSS) cheat for CS:GO/CS:CO * Copyright (C) 2017 - Thomas G. P. Nappo, Jonathan Beaudoin * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.charlatano.game.offsets import com.charlatano.game.CSGO.csgoEXE import com.charlatano.game.CSGO.clientDLL import com.charlatano.game.offsets.ClientOffsets.decalname import com.charlatano.utils.extensions.uint fun findDecal(): Long { val mask = ByteArray(4) for (i in 0..3) mask[i] = (((decalname shr 8 * i)) and 0xFF).toByte() val memory = Offset.memoryByModule[clientDLL]!! var skipped = 0 var currentAddress = 0L while (currentAddress < clientDLL.size - mask.size) { if (memory.mask(currentAddress, mask, false)) { if (skipped < 5) { // skips currentAddress += 0xA // skipSize skipped++ continue } return currentAddress + clientDLL.address } currentAddress++ } return -1L } fun findFirstClass() = csgoEXE.uint(findDecal() + 0x3B)
src/main/kotlin/com/charlatano/game/offsets/FirstClassFinder.kt
2909493575
package hook.Instrumentation.premain import javassist.ClassPool import javassist.CtClass import java.io.ByteArrayInputStream import java.lang.instrument.ClassFileTransformer import java.lang.instrument.IllegalClassFormatException import java.security.ProtectionDomain class ByteChangeTransformerKt : ClassFileTransformer { @Throws(IllegalClassFormatException::class) override fun transform(loader: ClassLoader, className: String, classBeingRedefined: Class<*>?, protectionDomain: ProtectionDomain, classfileBuffer: ByteArray): ByteArray { // if (!"hook.Instrumentation.premain.TestAgent".equals(className)) { // // 只修改指定的Class // return classfileBuffer; // } println(" passing! className:$className") var transformed: ByteArray? = null var cl: CtClass? = null try { // CtClass、ClassPool、CtMethod、ExprEditor都是javassist提供的字节码操作的类 val pool = ClassPool.getDefault() cl = pool.makeClass(ByteArrayInputStream(classfileBuffer)) val methods = cl.declaredMethods for (i in methods.indices) { val method = methods[i] if (method.methodInfo.codeAttribute != null) { method.insertBefore("System.out.println(\" inserting \t ${className}.${method.name}\");") } // methods[i].insertAfter("System.out.println(\" after\");"); // methods[i].instrument(new ExprEditor() { // @Override // public void edit(MethodCall m) throws CannotCompileException { // // 把方法体直接替换掉,其中 $proceed($$);是javassist的语法,用来表示原方法体的调用 // m.replace("{ long stime = System.currentTimeMillis();" // + " $_ = $proceed($$);" // + "System.out.println(\"" + m.getClassName() + "." + m.getMethodName() // + " cost:\" + (System.currentTimeMillis() - stime) + \" ms\"); }"); // } // }); } // javassist会把输入的Java代码再编译成字节码byte[] transformed = cl.toBytecode() } catch (e: Exception) { e.printStackTrace() } finally { cl?.detach() } return transformed!! } }
HttpTest3/src/main/java/hook/Instrumentation/premain/ByteChangeTransformerKt.kt
2490714354
package com.like.common.view.dragview.animation import android.app.Activity import com.like.common.view.dragview.entity.DragInfo import com.like.common.view.dragview.view.BaseDragView class AnimationConfig(info: DragInfo, val view: BaseDragView) { companion object { const val DURATION = 300L } val MAX_CANVAS_TRANSLATION_Y = view.height.toFloat() / 4 var curCanvasBgAlpha = 255 var curCanvasTranslationX = 0f var curCanvasTranslationY = 0f var curCanvasScale = 1f var originScaleX = info.originWidth / view.width.toFloat() var originScaleY = info.originHeight / view.height.toFloat() var originTranslationX = info.originCenterX - view.width / 2 var originTranslationY = info.originCenterY - view.height / 2 var minCanvasScale = info.originWidth / view.width fun setData(info: DragInfo) { curCanvasBgAlpha = 255 curCanvasTranslationX = 0f curCanvasTranslationY = 0f curCanvasScale = 1f originScaleX = info.originWidth / view.width.toFloat() originScaleY = info.originHeight / view.height.toFloat() originTranslationX = info.originCenterX - view.width / 2 originTranslationY = info.originCenterY - view.height / 2 minCanvasScale = info.originWidth / view.width } fun finishActivity() { val activity = view.context if (activity is Activity) { activity.finish() activity.overridePendingTransition(0, 0) } } fun updateCanvasTranslationX(translationX: Float) { curCanvasTranslationX = translationX } fun updateCanvasTranslationY(translationY: Float) { curCanvasTranslationY = translationY } fun updateCanvasScale() { val translateYPercent = Math.abs(curCanvasTranslationY) / view.height val scale = 1 - translateYPercent curCanvasScale = when { scale < minCanvasScale -> minCanvasScale scale > 1f -> 1f else -> scale } } fun updateCanvasBgAlpha() { val translateYPercent = Math.abs(curCanvasTranslationY) / view.height val alpha = (255 * (1 - translateYPercent)).toInt() curCanvasBgAlpha = when { alpha > 255 -> 255 alpha < 0 -> 0 else -> alpha } } }
common/src/main/java/com/like/common/view/dragview/animation/AnimationConfig.kt
2377480687
package com.orgzly.android.widgets import android.content.Context import android.content.Intent import android.util.Log import android.view.View import android.widget.RemoteViews import android.widget.RemoteViewsService import com.orgzly.BuildConfig import com.orgzly.R import com.orgzly.android.App import com.orgzly.android.AppIntent import com.orgzly.android.data.DataRepository import com.orgzly.android.db.entity.NoteView import com.orgzly.android.prefs.AppPreferences import com.orgzly.android.query.Query import com.orgzly.android.query.user.InternalQueryParser import com.orgzly.android.ui.TimeType import com.orgzly.android.ui.notes.query.agenda.AgendaItem import com.orgzly.android.ui.notes.query.agenda.AgendaItems import com.orgzly.android.ui.util.TitleGenerator import com.orgzly.android.util.LogUtils import com.orgzly.android.util.UserTimeFormatter import com.orgzly.org.datetime.OrgRange import org.joda.time.DateTime import javax.inject.Inject class ListWidgetService : RemoteViewsService() { @Inject lateinit var dataRepository: DataRepository override fun onCreate() { App.appComponent.inject(this) super.onCreate() } override fun onGetViewFactory(intent: Intent): RemoteViewsFactory { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) val queryString = intent.getStringExtra(AppIntent.EXTRA_QUERY_STRING).orEmpty() return ListWidgetViewsFactory(applicationContext, queryString) } private sealed class WidgetEntry(open val id: Long) { data class Overdue(override val id: Long) : WidgetEntry(id) data class Day(override val id: Long, val day: DateTime) : WidgetEntry(id) data class Note( override val id: Long, val noteView: NoteView, val agendaTimeType: TimeType? = null ) : WidgetEntry(id) } inner class ListWidgetViewsFactory( val context: Context, private val queryString: String ) : RemoteViewsFactory { private val query: Query by lazy { val parser = InternalQueryParser() parser.parse(queryString) } private val userTimeFormatter by lazy { UserTimeFormatter(context) } private var dataList: List<WidgetEntry> = emptyList() override fun onCreate() { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) } override fun getLoadingView(): RemoteViews? { return null } override fun getItemId(position: Int): Long { return dataList[position].id } override fun onDataSetChanged() { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) val notes = dataRepository.selectNotesFromQuery(query) if (query.isAgenda()) { val idMap = mutableMapOf<Long, Long>() val agendaItems = AgendaItems.getList(notes, query, idMap) dataList = agendaItems.map { when (it) { is AgendaItem.Overdue -> WidgetEntry.Overdue(it.id) is AgendaItem.Day -> WidgetEntry.Day(it.id, it.day) is AgendaItem.Note -> WidgetEntry.Note(it.id, it.note, it.timeType) } } } else { dataList = notes.map { WidgetEntry.Note(it.note.id, it) } } } override fun hasStableIds(): Boolean { return true } override fun getViewAt(position: Int): RemoteViews? { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, position) if (position >= dataList.size) { Log.e(TAG, "List too small (${dataList.size}) for requested position $position") return null } return when (val entry = dataList[position]) { is WidgetEntry.Overdue -> RemoteViews(context.packageName, R.layout.item_list_widget_divider).apply { setupRemoteViews(this) WidgetStyle.updateDivider(this, context) } is WidgetEntry.Day -> RemoteViews(context.packageName, R.layout.item_list_widget_divider).apply { setupRemoteViews(this, entry) WidgetStyle.updateDivider(this, context) } is WidgetEntry.Note -> RemoteViews(context.packageName, R.layout.item_list_widget).apply { setupRemoteViews(this, entry) WidgetStyle.updateNote(this, context) } } } override fun getCount(): Int { return dataList.size } override fun getViewTypeCount(): Int { return 2 } override fun onDestroy() { if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG) } private fun setupRemoteViews(views: RemoteViews) { views.setTextViewText( R.id.widget_list_item_divider_value, context.getString(R.string.overdue)) } private fun setupRemoteViews(views: RemoteViews, entry: WidgetEntry.Day) { views.setTextViewText( R.id.widget_list_item_divider_value, userTimeFormatter.formatDate(entry.day)) } private fun setupRemoteViews(row: RemoteViews, entry: WidgetEntry.Note) { val noteView = entry.noteView val displayPlanningTimes = AppPreferences.displayPlanning(context) val displayBookName = AppPreferences.widgetDisplayBookName(context) val doneStates = AppPreferences.doneKeywordsSet(context) // Title (colors depend on current theme) val titleGenerator = TitleGenerator(context, false, WidgetStyle.getTitleAttributes(context)) row.setTextViewText(R.id.item_list_widget_title, titleGenerator.generateTitle(noteView)) // Notebook name if (displayBookName) { row.setTextViewText(R.id.item_list_widget_book_text, noteView.bookName) row.setViewVisibility(R.id.item_list_widget_book, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_book, View.GONE) } // Closed time if (displayPlanningTimes && noteView.closedRangeString != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(noteView.closedRangeString)) row.setTextViewText(R.id.item_list_widget_closed_text, time) row.setViewVisibility(R.id.item_list_widget_closed, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_closed, View.GONE) } var scheduled = noteView.scheduledRangeString var deadline = noteView.deadlineRangeString var event = noteView.eventString // In Agenda only display time responsible for item's presence when (entry.agendaTimeType) { TimeType.SCHEDULED -> { deadline = null event = null } TimeType.DEADLINE -> { scheduled = null event = null } TimeType.EVENT -> { scheduled = null deadline = null } else -> { } } // Scheduled time if (displayPlanningTimes && scheduled != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(scheduled)) row.setTextViewText(R.id.item_list_widget_scheduled_text, time) row.setViewVisibility(R.id.item_list_widget_scheduled, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_scheduled, View.GONE) } // Deadline time if (displayPlanningTimes && deadline != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(deadline)) row.setTextViewText(R.id.item_list_widget_deadline_text, time) row.setViewVisibility(R.id.item_list_widget_deadline, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_deadline, View.GONE) } // Event time if (displayPlanningTimes && event != null) { val time = userTimeFormatter.formatAll(OrgRange.parse(event)) row.setTextViewText(R.id.item_list_widget_event_text, time) row.setViewVisibility(R.id.item_list_widget_event, View.VISIBLE) } else { row.setViewVisibility(R.id.item_list_widget_event, View.GONE) } // Check mark if (!AppPreferences.widgetDisplayCheckmarks(context) || doneStates.contains(noteView.note.state)) { row.setViewVisibility(R.id.item_list_widget_done, View.GONE) } else { row.setViewVisibility(R.id.item_list_widget_done, View.VISIBLE) } // Intent for opening note val openIntent = Intent() openIntent.putExtra(AppIntent.EXTRA_CLICK_TYPE, ListWidgetProvider.OPEN_CLICK_TYPE) openIntent.putExtra(AppIntent.EXTRA_NOTE_ID, noteView.note.id) openIntent.putExtra(AppIntent.EXTRA_BOOK_ID, noteView.note.position.bookId) row.setOnClickFillInIntent(R.id.item_list_widget_layout, openIntent) // Intent for marking note done val doneIntent = Intent() doneIntent.putExtra(AppIntent.EXTRA_CLICK_TYPE, ListWidgetProvider.DONE_CLICK_TYPE) doneIntent.putExtra(AppIntent.EXTRA_NOTE_ID, noteView.note.id) row.setOnClickFillInIntent(R.id.item_list_widget_done, doneIntent) } } companion object { private val TAG = ListWidgetService::class.java.name } }
app/src/main/java/com/orgzly/android/widgets/ListWidgetService.kt
3135939236
package com.soywiz.kpspemu.hle.manager import com.soywiz.kds.* import com.soywiz.klock.* import com.soywiz.klogger.* import com.soywiz.kmem.* import com.soywiz.korio.async.* import com.soywiz.korio.error.* import com.soywiz.korio.lang.* import com.soywiz.kpspemu.* import com.soywiz.kpspemu.cpu.* import com.soywiz.kpspemu.cpu.dynarec.* import com.soywiz.kpspemu.cpu.interpreter.* import com.soywiz.kpspemu.mem.* import com.soywiz.kpspemu.util.* import kotlin.collections.set import kotlin.math.* import com.soywiz.kmem.umod import com.soywiz.krypto.encoding.* import kotlinx.coroutines.channels.* import com.soywiz.korio.error.invalidOp as invalidOp1 //const val INSTRUCTIONS_PER_STEP = 500_000 //const val INSTRUCTIONS_PER_STEP = 1_000_000 //const val INSTRUCTIONS_PER_STEP = 2_000_000 //const val INSTRUCTIONS_PER_STEP = 4_000_000 const val INSTRUCTIONS_PER_STEP = 5_000_000 //const val INSTRUCTIONS_PER_STEP = 10_000_000 //const val INSTRUCTIONS_PER_STEP = 100_000_000 class ThreadsWithPriority(val priority: Int) : Comparable<ThreadsWithPriority> { val threads = arrayListOf<PspThread>() var currentIndex = 0 val runningThreads get() = threads.count { it.running } fun next(): PspThread? = when { threads.isNotEmpty() -> threads[currentIndex++ % threads.size] else -> null } fun nextRunning(): PspThread? { for (n in 0 until threads.size) { val n = next() if (n != null && n.running) return n } return null } override fun compareTo(other: ThreadsWithPriority): Int { return this.priority.compareTo(other.priority) } override fun toString(): String = "ThreadsWithPriority(priority=$priority)" } class ThreadManager(emulator: Emulator) : Manager<PspThread>("Thread", emulator) { val logger = Logger("ThreadManager").apply { //level = LogLevel.TRACE } val prioritiesByValue = LinkedHashMap<Int, ThreadsWithPriority>() val priorities = PriorityQueue<ThreadsWithPriority>() val currentPriorities = PriorityQueue<ThreadsWithPriority>() val threads get() = resourcesById.values val waitingThreads: Int get() = resourcesById.count { it.value.waiting } val activeThreads: Int get() = resourcesById.count { it.value.running } val totalThreads: Int get() = resourcesById.size val aliveThreadCount: Int get() = resourcesById.values.count { it.running || it.waiting } val onThreadChanged = Signal<PspThread>() val onThreadChangedChannel = Channel<PspThread>().broadcast() val waitThreadChanged = onThreadChangedChannel.openSubscription() var currentThread: PspThread? = null override fun reset() { super.reset() currentThread = null } fun setThreadPriority(thread: PspThread, priority: Int) { if (thread.priority == priority) return val oldThreadsWithPriority = thread.threadsWithPriority if (oldThreadsWithPriority != null) { oldThreadsWithPriority.threads.remove(thread) if (oldThreadsWithPriority.threads.isEmpty()) { prioritiesByValue.remove(oldThreadsWithPriority.priority) priorities.remove(oldThreadsWithPriority) } } val newThreadsWithPriority = prioritiesByValue.getOrPut(priority) { ThreadsWithPriority(priority).also { priorities.add(it) } } thread.threadsWithPriority = newThreadsWithPriority newThreadsWithPriority.threads.add(thread) } fun create( name: String, entryPoint: Int, initPriority: Int, stackSize: Int, attributes: Int, optionPtr: Ptr ): PspThread { //priorities.sortBy { it.priority } var attr = attributes val ssize = max(stackSize, 0x200).nextAlignedTo(0x100) //val ssize = max(stackSize, 0x20000).nextAlignedTo(0x10000) val stack = memoryManager.stackPartition.allocateHigh(ssize, "${name}_stack") println(stack.toString2()) val thread = PspThread(this, allocId(), name, entryPoint, stack, initPriority, attributes, optionPtr) logger.info { "stack:%08X-%08X (%d)".format(stack.low.toInt(), stack.high.toInt(), stack.size.toInt()) } //memoryManager.userPartition.dump() attr = attr or PspThreadAttributes.User attr = attr or PspThreadAttributes.LowFF if (!(attr hasFlag PspThreadAttributes.NoFillStack)) { logger.trace { "FILLING: $stack" } mem.fill(-1, stack.low.toInt(), stack.size.toInt()) } else { logger.trace { "NOT FILLING: $stack" } } threadManager.onThreadChanged(thread) threadManager.onThreadChangedChannel.trySend(thread) return thread } @Deprecated("USE suspendReturnInt or suspendReturnVoid") fun suspend(): Nothing { throw CpuBreakExceptionCached(CpuBreakException.THREAD_WAIT) } fun suspendReturnInt(value: Int): Nothing { currentThread?.state?.V0 = value throw CpuBreakExceptionCached(CpuBreakException.THREAD_WAIT) } fun suspendReturnVoid(): Nothing { throw CpuBreakExceptionCached(CpuBreakException.THREAD_WAIT) } fun getActiveThreadPriorities(): List<Int> = threads.filter { it.running }.map { it.priority }.distinct().sorted() fun getActiveThreadsWithPriority(priority: Int): List<PspThread> = threads.filter { it.running && it.priority == priority } val lowestThreadPriority get() = threads.minByOrNull { it.priority }?.priority ?: 0 fun getFirstThread(): PspThread? { for (thread in threads) { if (thread.priority == lowestThreadPriority) return thread } return null } fun getNextPriority(priority: Int): Int? { return getActiveThreadPriorities().firstOrNull { it > priority } } fun computeNextThread(prevThread: PspThread?): PspThread? { if (prevThread == null) return getFirstThread() val threadsWithPriority = getActiveThreadsWithPriority(prevThread.priority) val threadsWithPriorityCount = threadsWithPriority.size if (threadsWithPriorityCount > 0) { val index = threadsWithPriority.indexOf(prevThread) umod threadsWithPriorityCount return threadsWithPriority.getOrNull((index + 1) umod threadsWithPriorityCount) } else { val nextPriority = getNextPriority(prevThread.priority) return nextPriority?.let { getActiveThreadsWithPriority(it).firstOrNull() } } } suspend fun waitThreadChange() { //println("[1]") /* kotlinx.coroutines.withTimeout(16L) { waitThreadChanged.receive() } */ delay(1.milliseconds) //onThreadChanged.waitOne() //println("[2]") //coroutineContext.sleep(0) } enum class StepResult { NO_THREAD, BREAKPOINT, TIMEOUT } fun step(): StepResult { val start = DateTime.now() if (emulator.globalTrace) { println("-----") for (thread in threads) { println("- ${thread.name} : ${thread.priority} : running=${thread.running}") } println("-----") } currentPriorities.clear() currentPriorities.addAll(priorities) //Console.error("ThreadManager.STEP") while (currentPriorities.isNotEmpty()) { val threads = currentPriorities.removeHead() //println("threads: $threads") while (true) { val now = DateTime.now() val current = threads.nextRunning() ?: break //println(" Running Thread.STEP: $current") if (emulator.globalTrace) println("Current thread: ${current.name}") try { current.step(now.unixMillisDouble) } catch (e: BreakpointException) { //Console.error("StepResult.BREAKPOINT: $e") return StepResult.BREAKPOINT } if (emulator.globalTrace) println("Next thread: ${current.name}") val elapsed = now - start if (elapsed >= 16.milliseconds) { //coroutineContext.delay(1.milliseconds) Console.error("StepResult.TIMEOUT: $elapsed") return StepResult.TIMEOUT } } } //dump() return StepResult.NO_THREAD } val availablePriorities: List<Int> get() = resourcesById.values.filter { it.running }.map { it.priority }.distinct().sorted() val availableThreadCount get() = resourcesById.values.count { it.running } val availableThreads get() = resourcesById.values.filter { it.running }.sortedBy { it.priority } val traces = hashMapOf<String, Boolean>() fun trace(name: String, trace: Boolean = true) { if (trace) { traces[name] = true } else { traces.remove(name) } tryGetByName(name)?.updateTrace() } fun stopAllThreads() { for (t in resourcesById.values.toList()) { t.exitAndKill() } throw CpuBreakExceptionCached(CpuBreakException.THREAD_EXIT_KILL) } fun executeInterrupt(address: Int, argument: Int) { val gcpustate = emulator.globalCpuState val oldInsideInterrupt = gcpustate.insideInterrupt gcpustate.insideInterrupt = true try { val thread = threads.first() val cpu = thread.state.clone() cpu._thread = thread val interpreter = CpuInterpreter(cpu, emulator.breakpoints, emulator.nameProvider) cpu.setPC(address) cpu.RA = CpuBreakException.INTERRUPT_RETURN_RA cpu.r4 = argument val start = timeManager.getTimeInMicroseconds() while (true) { val now = timeManager.getTimeInMicroseconds() interpreter.steps(10000) if (now - start >= 16.0) { println("Interrupt is taking too long...") break // Rest a bit } } } catch (e: CpuBreakException) { if (e.id != CpuBreakException.INTERRUPT_RETURN) { throw e } } finally { gcpustate.insideInterrupt = oldInsideInterrupt } } fun delayThread(micros: Int) { // @TODO: } fun dump() { println("ThreadManager.dump:") for (thread in threads) { println(" - $thread") } } val summary: String get() = "[" + threads.map { "'${it.name}'#${it.id} P${it.priority} : ${it.phase}" }.joinToString(", ") + "]" } sealed class WaitObject { //data class TIME(val instant: Double) : WaitObject() { // override fun toString(): String = "TIME(${instant.toLong()})" //} //data class PROMISE(val promise: Promise<Unit>, val reason: String) : WaitObject() data class COROUTINE(val reason: String) : WaitObject() //object SLEEP : WaitObject() object VBLANK : WaitObject() } class PspThread internal constructor( val threadManager: ThreadManager, id: Int, name: String, val entryPoint: Int, val stack: MemoryPartition, val initPriority: Int, var attributes: Int, val optionPtr: Ptr ) : Resource(threadManager, id, name), WithEmulator { var threadsWithPriority: ThreadsWithPriority? = null var preemptionCount: Int = 0 val totalExecutedInstructions: Long get() = state.totalExecuted val onEnd = Signal<Unit>() val onWakeUp = Signal<Unit>() val logger = Logger("PspThread") enum class Phase { STOPPED, RUNNING, WAITING, DELETED } override fun toString(): String { return "PspThread(id=$id, name='$name', phase=$phase, status=$status, priority=$priority, waitObject=$waitObject, waitInfo=$waitInfo)" } val status: Int get() { var out: Int = 0 if (running) out = out or ThreadStatus.RUNNING if (waiting) out = out or ThreadStatus.WAIT if (phase == Phase.DELETED) out = out or ThreadStatus.DEAD return out } var acceptingCallbacks: Boolean = false var waitObject: WaitObject? = null var waitInfo: Any? = null var exitStatus: Int = 0 var phase: Phase = Phase.STOPPED set(value) = run { field = value } val priority: Int get() = threadsWithPriority?.priority ?: Int.MAX_VALUE val running: Boolean get() = phase == Phase.RUNNING val waiting: Boolean get() = waitObject != null override val emulator get() = manager.emulator val state = CpuState("state.thread.$name", emulator.globalCpuState, emulator.syscalls).apply { _thread = this@PspThread setPC(entryPoint) SP = stack.high.toInt() RA = CpuBreakException.THREAD_EXIT_KIL_RA println("CREATED THREAD('$name'): PC=${PC.hex}, SP=${SP.hex}") } val interpreter = CpuInterpreter(state, emulator.breakpoints, emulator.nameProvider) val dynarek = DynarekRunner(state, emulator.breakpoints, emulator.nameProvider) //val interpreter = FastCpuInterpreter(state) init { updateTrace() setThreadProps(Phase.STOPPED) threadManager.setThreadPriority(this, initPriority) } fun setThreadProps(phase: Phase, waitObject: WaitObject? = this.waitObject, waitInfo: Any? = this.waitInfo, acceptingCallbacks: Boolean = this.acceptingCallbacks) { this.phase = phase this.waitObject = waitObject this.waitInfo = waitInfo this.acceptingCallbacks = acceptingCallbacks if (phase == Phase.STOPPED) { onEnd(Unit) } if (phase == Phase.DELETED) { manager.freeById(id) logger.warn { "Deleting Thread: $name" } } threadManager.onThreadChanged(this) threadManager.onThreadChangedChannel.trySend(this) } fun updateTrace() { interpreter.trace = threadManager.traces[name] == true } fun putDataInStack(bytes: ByteArray, alignment: Int = 0x10): PtrArray { val blockSize = bytes.size.nextAlignedTo(alignment) state.SP -= blockSize mem.write(state.SP, bytes) return PtrArray(mem.ptr(state.SP), bytes.size) } fun putWordInStack(word: Int, alignment: Int = 0x10): PtrArray { val blockSize = 4.nextAlignedTo(alignment) state.SP -= blockSize mem.sw(state.SP, word) return mem.ptr(state.SP).array(4) } fun putWordsInStack(vararg words: Int, alignment: Int = 0x10): PtrArray { val blockSize = (words.size * 4).nextAlignedTo(alignment) state.SP -= blockSize for (n in 0 until words.size) mem.sw(state.SP + n * 4, words[n]) return mem.ptr(state.SP).array(words.size * 4) } fun start() { resume() } fun resume() { setThreadProps(phase = Phase.RUNNING, waitObject = null, waitInfo = null, acceptingCallbacks = false) } fun stop(reason: String = "generic") { if (phase != Phase.STOPPED) { logger.warn { "Stopping Thread: $name : reason=$reason" } setThreadProps(phase = Phase.STOPPED) } //threadManager.onThreadChanged(this) } fun delete() { stop() setThreadProps(phase = Phase.DELETED) } fun exitAndKill() { stop() delete() } fun step(now: Double, trace: Boolean = tracing): Int { //if (name == "update_thread") { // println("Ignoring: Thread.${this.name}") // stop("ignoring") // return //} //println("Step: Thread.${this.name}") preemptionCount++ try { if (emulator.interpreted) { interpreter.steps(INSTRUCTIONS_PER_STEP, trace) } else { dynarek.steps(INSTRUCTIONS_PER_STEP, trace) } return 0 } catch (e: CpuBreakException) { when (e.id) { CpuBreakException.THREAD_EXIT_KILL -> { logger.info { "BREAK: THREAD_EXIT_KILL ('${this.name}', ${this.id})" } println("BREAK: THREAD_EXIT_KILL ('${this.name}', ${this.id})") exitAndKill() } CpuBreakException.THREAD_WAIT -> { // Do nothing } CpuBreakException.INTERRUPT_RETURN -> { // Do nothing } else -> { println("CPU: ${state.summary}") println("ERROR at PspThread.step") e.printStackTrace() throw e } } return e.id } } fun markWaiting(wait: WaitObject, cb: Boolean) { setThreadProps(phase = Phase.WAITING, waitObject = wait, acceptingCallbacks = cb) } fun suspend(wait: WaitObject, cb: Boolean) { markWaiting(wait, cb) //if (wait is WaitObject.PROMISE) wait.promise.then { resume() } threadManager.suspend() } var pendingAccumulatedMicrosecondsToWait: Int = 0 suspend fun sleepMicro(microseconds: Int) { val totalMicroseconds = pendingAccumulatedMicrosecondsToWait + microseconds pendingAccumulatedMicrosecondsToWait = totalMicroseconds % 1000 val totalMilliseconds = totalMicroseconds / 1000 // @TODO: This makes sceRtc test to be flaky //if (totalMilliseconds < 1) { // pendingAccumulatedMicrosecondsToWait += totalMilliseconds * 1000 //} else { coroutineContext.delay(totalMilliseconds.milliseconds) //} } suspend fun sleepSeconds(seconds: Double) = sleepMicro((seconds * 1_000_000).toInt()) suspend fun sleepSecondsIfRequired(seconds: Double) { if (seconds > 0.0) sleepMicro((seconds * 1_000_000).toInt()) } fun cpuBreakException(e: CpuBreakException) { } var tracing: Boolean = false } var CpuState._thread: PspThread? by Extra.Property { null } val CpuState.thread: PspThread get() = _thread ?: invalidOp1("CpuState doesn't have a thread attached") data class PspEventFlag(override val id: Int) : ResourceItem { var name: String = "" var attributes: Int = 0 var currentPattern: Int = 0 var optionsPtr: Ptr? = null fun poll(bitsToMatch: Int, waitType: Int, outBits: Ptr): Boolean { if (outBits.isNotNull) outBits.sw(0, this.currentPattern) val res = when { (waitType and EventFlagWaitTypeSet.Or) != 0 -> ((this.currentPattern and bitsToMatch) != 0) // one or more bits of the mask else -> (this.currentPattern and bitsToMatch) == bitsToMatch // all the bits of the mask } if (res) { this._doClear(bitsToMatch, waitType) return true } else { return false } } private fun _doClear(bitsToMatch: Int, waitType: Int) { if ((waitType and (EventFlagWaitTypeSet.ClearAll)) != 0) this.clearBits(-1.inv(), false) if ((waitType and (EventFlagWaitTypeSet.Clear)) != 0) this.clearBits(bitsToMatch.inv(), false) } fun clearBits(bitsToClear: Int, doUpdateWaitingThreads: Boolean = true) { this.currentPattern = this.currentPattern and bitsToClear if (doUpdateWaitingThreads) this.updateWaitingThreads() } private fun updateWaitingThreads() { //this.waitingThreads.forEach(waitingThread => { // if (this.poll(waitingThread.bitsToMatch, waitingThread.waitType, waitingThread.outBits)) { // waitingThread.wakeUp(); // } //}); } fun setBits(bits: Int, doUpdateWaitingThreads: Boolean = true) { this.currentPattern = this.currentPattern or bits if (doUpdateWaitingThreads) this.updateWaitingThreads() } } object EventFlagWaitTypeSet { const val And = 0x00 const val Or = 0x01 const val ClearAll = 0x10 const val Clear = 0x20 const val MaskValidBits = Or or Clear or ClearAll } object ThreadStatus { const val RUNNING = 1 const val READY = 2 const val WAIT = 4 const val SUSPEND = 8 const val DORMANT = 16 const val DEAD = 32 const val WAITSUSPEND = WAIT or SUSPEND } class SceKernelThreadInfo( var size: Int = 0, var name: String = "", var attributes: Int = 0, var status: Int = 0, // ThreadStatus var entryPoint: Int = 0, var stackPointer: Int = 0, var stackSize: Int = 0, var GP: Int = 0, var priorityInit: Int = 0, var priority: Int = 0, var waitType: Int = 0, var waitId: Int = 0, var wakeupCount: Int = 0, var exitStatus: Int = 0, var runClocksLow: Int = 0, var runClocksHigh: Int = 0, var interruptPreemptionCount: Int = 0, var threadPreemptionCount: Int = 0, var releaseCount: Int = 0 ) { companion object : Struct<SceKernelThreadInfo>( { SceKernelThreadInfo() }, SceKernelThreadInfo::size AS INT32, SceKernelThreadInfo::name AS STRINGZ(32), SceKernelThreadInfo::attributes AS INT32, SceKernelThreadInfo::status AS INT32, SceKernelThreadInfo::entryPoint AS INT32, SceKernelThreadInfo::stackPointer AS INT32, SceKernelThreadInfo::stackSize AS INT32, SceKernelThreadInfo::GP AS INT32, SceKernelThreadInfo::priorityInit AS INT32, SceKernelThreadInfo::priority AS INT32, SceKernelThreadInfo::waitType AS INT32, SceKernelThreadInfo::waitId AS INT32, SceKernelThreadInfo::wakeupCount AS INT32, SceKernelThreadInfo::exitStatus AS INT32, SceKernelThreadInfo::runClocksLow AS INT32, SceKernelThreadInfo::runClocksHigh AS INT32, SceKernelThreadInfo::interruptPreemptionCount AS INT32, SceKernelThreadInfo::threadPreemptionCount AS INT32, SceKernelThreadInfo::releaseCount AS INT32 ) } object PspThreadAttributes { const val None = 0 const val LowFF = 0x000000FF.toInt() const val Vfpu = 0x00004000.toInt() // Enable VFPU access for the thread. const val V0x2000 = 0x2000.toInt() const val V0x4000 = 0x4000.toInt() const val V0x400000 = 0x400000.toInt() const val V0x800000 = 0x800000.toInt() const val V0xf00000 = 0xf00000.toInt() const val V0x8000000 = 0x8000000.toInt() const val V0xf000000 = 0xf000000.toInt() const val User = 0x80000000.toInt() // Start the thread in user mode (done automatically if the thread creating it is in user mode). const val UsbWlan = 0xa0000000.toInt() // Thread is part of the USB/WLAN API. const val Vsh = 0xc0000000.toInt() // Thread is part of the VSH API. //val ScratchRamEnable = 0x00008000, // Allow using scratchpad memory for a thread, NOT USABLE ON V1.0 const val NoFillStack = 0x00100000.toInt() // Disables filling the stack with 0xFF on creation const val ClearStack = 0x00200000.toInt() // Clear the stack when the thread is deleted const val ValidMask = (LowFF or Vfpu or User or UsbWlan or Vsh or /*ScratchRamEnable |*/ NoFillStack or ClearStack or V0x2000 or V0x4000 or V0x400000 or V0x800000 or V0xf00000 or V0x8000000 or V0xf000000).toInt() }
src/commonMain/kotlin/com/soywiz/kpspemu/hle/manager/ThreadManager.kt
360511915
package com.foo.graphql.unionInternal.type data class Pot( override var id: Int? = null, val color: String? = null, val size: Int? = null ) : Bouquet
e2e-tests/spring-graphql/src/main/kotlin/com/foo/graphql/unionInternal/type/Pot.kt
1626798463
package com.squareup.sqldelight.core.compiler import com.squareup.kotlinpoet.ClassName import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.TypeSpec import com.squareup.kotlinpoet.asTypeName import com.squareup.kotlinpoet.joinToCode import com.squareup.sqldelight.core.SqlDelightFileIndex import com.squareup.sqldelight.core.lang.DATABASE_SCHEMA_TYPE import kotlin.reflect.KClass internal class DatabaseExposerGenerator( val implementation: TypeSpec, val fileIndex: SqlDelightFileIndex ) { private val interfaceType = ClassName(fileIndex.packageName, fileIndex.className) fun exposedSchema(): PropertySpec { return PropertySpec.builder("schema", DATABASE_SCHEMA_TYPE) .addModifiers(KModifier.INTERNAL) .receiver(KClass::class.asTypeName().parameterizedBy(interfaceType)) .getter( FunSpec.getterBuilder() .addStatement("return %N.Schema", implementation) .build() ) .build() } fun exposedConstructor(): FunSpec { return implementation.primaryConstructor!!.let { constructor -> FunSpec.builder("newInstance") .addModifiers(KModifier.INTERNAL) .returns(ClassName(fileIndex.packageName, fileIndex.className)) .receiver(KClass::class.asTypeName().parameterizedBy(interfaceType)) .addParameters(constructor.parameters) .addStatement("return %N(%L)", implementation, constructor.parameters.map { CodeBlock.of("%N", it) }.joinToCode(", ")) .build() } } }
sqldelight-compiler/src/main/kotlin/com/squareup/sqldelight/core/compiler/DatabaseExposerGenerator.kt
839600425
package com.braisgabin.mockable annotation class Mockable
hanabi/src/main/kotlin/com/braisgabin/mockable/Mockable.kt
3702516673
package org.evomaster.core.logging import ch.qos.logback.classic.LoggerContext import ch.qos.logback.classic.joran.JoranConfigurator import ch.qos.logback.core.joran.spi.JoranException import org.evomaster.core.AnsiColor import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.InputStream /** See "logback.xml" under the resources folder */ class LoggingUtil { companion object{ /** * Logger used to provide expected info to the user */ fun getInfoLogger(): Logger = LoggerFactory.getLogger("info_logger") ?: throw IllegalStateException("Failed to init logger") /** * A WARN log that can be printed only once. * If called twice (or more), such calls are ignored */ fun uniqueWarn(log: Logger, msg: String){ log.warn(UniqueTurboFilter.UNIQUE_MARKER, msg) } /** * A WARN log that can be printed only once. * If called twice (or more), such calls are ignored */ fun uniqueWarn(log: Logger, msg: String, arg: Any){ log.warn(UniqueTurboFilter.UNIQUE_MARKER, msg, arg) } fun uniqueUserWarn(msg: String) { uniqueWarn(getInfoLogger(), AnsiColor.inRed("WARNING: $msg")) } /** * Only needed for testing/debugging */ fun changeLogbackFile(resourceFilePath: String): Boolean { require(resourceFilePath.endsWith(".xml")) { "Logback file name does not terminate with '.xml'" } val context: LoggerContext = LoggerFactory.getILoggerFactory() as LoggerContext try { val configurator = JoranConfigurator() configurator.context = context var f: InputStream? = null f = if (LoggingUtil::class.java.classLoader != null) { LoggingUtil::class.java.classLoader.getResourceAsStream(resourceFilePath) } else { // If the classloader is null, then that could mean the class was loaded // with the bootstrap classloader, so let's try that as well ClassLoader.getSystemClassLoader().getResourceAsStream(resourceFilePath) } if (f == null) { val msg = "$resourceFilePath not found on classpath" System.err.println(msg) return false } else { context.reset() configurator.doConfigure(f) } } catch (je: JoranException) { return false } return true } } }
core/src/main/kotlin/org/evomaster/core/logging/LoggingUtil.kt
3867346232
package com.soywiz.vitaorganizer.tasks import com.soywiz.vitaorganizer.* class OneStepToVitaTask(vitaOrganizer: VitaOrganizer, val vpkFile: VpkFile) : VitaTask(vitaOrganizer) { val sendPromotingVpkTask = SendPromotingVpkToVitaTask(vitaOrganizer, vpkFile) val sendDataTask = SendDataToVitaTask(vitaOrganizer, vpkFile) override fun checkBeforeQueue() { sendPromotingVpkTask.checkBeforeQueue() sendDataTask.checkBeforeQueue() } override fun perform() { sendPromotingVpkTask.performBase() status(Texts.format("PROMOTING_VPK")) if(!PsvitaDevice.promoteVpk(sendPromotingVpkTask.vpkPath)) { status("Promoting failed! Task aborted!") return } PsvitaDevice.removeFile("/" + sendPromotingVpkTask.vpkPath) sendDataTask.performBase() info(Texts.format("GAME_SENT_SUCCESSFULLY", "id" to vpkFile.id)) } }
src/com/soywiz/vitaorganizer/tasks/OneStepToVitaTask.kt
1940394287
package com.openconference.sessions import com.openconference.model.SessionsLoader import com.openconference.model.errormessage.ErrorMessageDeterminer import com.openconference.sessions.presentationmodel.SessionPresentationModelTransformer import com.openconference.util.RxPresenter import com.openconference.util.SchedulerTransformer import javax.inject.Inject /** * Presenter responsible to show display sessions in [SessionsView] * * @author Hannes Dorfmann */ class SessionsPresenter @Inject constructor(scheduler: SchedulerTransformer, private val sessionsLoader: SessionsLoader, private val presentationModelTransformer: SessionPresentationModelTransformer, errorMessageDeterminer: ErrorMessageDeterminer) : RxPresenter<SessionsView>( scheduler, errorMessageDeterminer) { fun loadSessions() { view?.showLoading() subscribe(sessionsLoader.allSessions().map { presentationModelTransformer.transform(it) }, { view?.showContent(it) }, { view?.showError(errorMessageDeterminer.getErrorMessageRes(it)) } ) } }
app/src/main/java/com/openconference/sessions/SessionsPresenter.kt
2399813054
package io.thecontext.podcaster.input import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException import io.reactivex.Scheduler import io.reactivex.Single import io.thecontext.podcaster.value.Episode import io.thecontext.podcaster.value.Person import io.thecontext.podcaster.value.Podcast import java.io.File interface InputReader { sealed class Result { data class Success(val podcast: Podcast, val episodes: List<Episode>, val people: List<Person>) : Result() data class Failure(val message: String) : Result() } fun read(peopleFile: File, podcastFile: File, episodeFiles: Map<File, File>): Single<Result> class Impl( private val yamlReader: YamlReader, private val textReader: TextReader, private val ioScheduler: Scheduler ) : InputReader { override fun read(peopleFile: File, podcastFile: File, episodeFiles: Map<File, File>) = Single .fromCallable { val podcast = try { yamlReader.readPodcast(podcastFile) } catch (e: MissingKotlinParameterException) { return@fromCallable Result.Failure("Podcast YAML is missing value for [${e.parameter.name}].") } val episodes = episodeFiles.map { (episodeFile, episodeNotesFile) -> val episodeSlug = episodeFile.parentFile.name val episodeNotes = textReader.read(episodeNotesFile) val episode = try { yamlReader.readEpisode(episodeFile) } catch (e: MissingKotlinParameterException) { return@fromCallable Result.Failure("Episode YAML [$episodeSlug] is missing value for [${e.parameter.name}].") } episode.copy(slug = episodeSlug, notesMarkdown = episodeNotes) } val people = try { yamlReader.readPeople(peopleFile).distinctBy { it.id } } catch (e: MissingKotlinParameterException) { return@fromCallable Result.Failure("People YAML is missing value for [${e.parameter.name}].") } Result.Success(podcast, episodes, people) } .subscribeOn(ioScheduler) } }
src/main/kotlin/io/thecontext/podcaster/input/InputReader.kt
3759603777
package com.jjl.jjlaccounttestandroid.view.home import android.content.Intent import android.support.v7.widget.LinearLayoutManager import com.jjl.accounttest.domain.view.home.HomeContract import com.jjl.accounttest.domain.view.home.HomePresenter import com.jjl.accounttest.domain.viewmodel.HomeListViewModel import com.jjl.accounttest.domain.viewmodel.HomeType import com.jjl.jjlaccounttest.nativelibs.AndroidTextProvider import com.jjl.jjlaccounttestandroid.R import com.jjl.jjlaccounttestandroid.view.BaseActivity import com.jjl.jjlaccounttestandroid.view.accountList.AccountListUnfilteredActivity import com.jjl.jjlaccounttestandroid.view.accountList.AccountListVisibleActivity import com.pedrogomez.renderers.ListAdapteeCollection import com.pedrogomez.renderers.RVRendererAdapter import com.pedrogomez.renderers.RendererBuilder import kotlinx.android.synthetic.main.activity_home.* class HomeActivity : BaseActivity<HomeContract.HomeView, HomePresenter>(), HomeContract.HomeView { override fun getLayoutRes(): Int { return R.layout.activity_home } override fun providePresenter(): HomePresenter { return HomePresenter(this, AndroidTextProvider(this)) } override fun configureViews() { val linManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) recyclerview.layoutManager = linManager } override fun drawElements(list: List<HomeListViewModel>) { val renderer = HomeViewModelRenderer(listener = { homeListViewModel -> showFilter(homeListViewModel.homeType) }) val rendererBuilder = RendererBuilder(renderer) recyclerview.adapter = RVRendererAdapter(rendererBuilder, ListAdapteeCollection(list)) } private fun showFilter(homeType: HomeType) { when (homeType) { HomeType.DEFAULT -> openIntent(Intent(this, AccountListUnfilteredActivity::class.java)) HomeType.ONLY_VISIBLE -> openIntent(Intent(this, AccountListVisibleActivity::class.java)) } } private fun openIntent(intent: Intent) { startActivity(intent) } }
mobile/src/main/java/com/jjl/jjlaccounttestandroid/view/home/HomeActivity.kt
1268462930
/* * Copyright 2020 Esri * * 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.esri.arcgisruntime.sample.viewshedlocation import android.graphics.Color import android.os.Bundle import android.util.Log import android.view.MotionEvent import android.widget.CheckBox import android.widget.SeekBar import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.geoanalysis.LocationViewshed import com.esri.arcgisruntime.geoanalysis.Viewshed import com.esri.arcgisruntime.geometry.Point import com.esri.arcgisruntime.layers.ArcGISSceneLayer import com.esri.arcgisruntime.mapping.* import com.esri.arcgisruntime.mapping.view.* import com.esri.arcgisruntime.sample.viewshedlocation.databinding.ActivityMainBinding import java.util.concurrent.ExecutionException import kotlin.math.roundToInt class MainActivity : AppCompatActivity() { // initialize location viewshed parameters private val initHeading = 0 private val initPitch = 60 private val initHorizontalAngle = 75 private val initVerticalAngle = 90 private val initMinDistance = 0 private val initMaxDistance = 1500 private var minDistance: Int = 0 private var maxDistance: Int = 0 private lateinit var viewShed: LocationViewshed private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val sceneView: SceneView by lazy { activityMainBinding.sceneView } private val headingSeekBar: SeekBar by lazy { activityMainBinding.include.headingSeekBar } private val currHeading: TextView by lazy { activityMainBinding.include.currHeading } private val currPitch: TextView by lazy { activityMainBinding.include.currPitch } private val pitchSeekBar: SeekBar by lazy { activityMainBinding.include.pitchSeekBar } private val currHorizontalAngle: TextView by lazy { activityMainBinding.include.currHorizontalAngle } private val horizontalAngleSeekBar: SeekBar by lazy { activityMainBinding.include.horizontalAngleSeekBar } private val currVerticalAngle: TextView by lazy { activityMainBinding.include.currVerticalAngle } private val verticalAngleSeekBar: SeekBar by lazy { activityMainBinding.include.verticalAngleSeekBar } private val currMinimumDistance: TextView by lazy { activityMainBinding.include.currMinimumDistance } private val minDistanceSeekBar: SeekBar by lazy { activityMainBinding.include.minDistanceSeekBar } private val currMaximumDistance: TextView by lazy { activityMainBinding.include.currMaximumDistance } private val maxDistanceSeekBar: SeekBar by lazy { activityMainBinding.include.maxDistanceSeekBar } private val frustumVisibilityCheckBox: CheckBox by lazy { activityMainBinding.include.frustumVisibilityCheckBox } private val viewshedVisibilityCheckBox: CheckBox by lazy { activityMainBinding.include.viewshedVisibilityCheckBox } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create a surface for elevation data val surface = Surface().apply { elevationSources.add(ArcGISTiledElevationSource(getString(R.string.elevation_service))) } // create a layer of buildings val buildingsSceneLayer = ArcGISSceneLayer(getString(R.string.buildings_layer)) // create a scene and add imagery basemap, elevation surface, and buildings layer to it val buildingsScene = ArcGISScene(BasemapStyle.ARCGIS_IMAGERY).apply { baseSurface = surface operationalLayers.add(buildingsSceneLayer) } val initLocation = Point(-4.50, 48.4, 1000.0) // create viewshed from the initial location viewShed = LocationViewshed( initLocation, initHeading.toDouble(), initPitch.toDouble(), initHorizontalAngle.toDouble(), initVerticalAngle.toDouble(), initMinDistance.toDouble(), initMaxDistance.toDouble() ).apply { setFrustumOutlineVisible(true) } Viewshed.setFrustumOutlineColor(Color.BLUE) sceneView.apply { // add the buildings scene to the sceneView scene = buildingsScene // add a camera and set it to orbit the starting location point of the frustum cameraController = OrbitLocationCameraController(initLocation, 5000.0) setViewpointCamera(Camera(initLocation, 20000000.0, 0.0, 55.0, 0.0)) } // create an analysis overlay to add the viewshed to the scene view val analysisOverlay = AnalysisOverlay().apply { analyses.add(viewShed) } sceneView.analysisOverlays.add(analysisOverlay) // initialize the UI controls handleUiElements() } /** * Handles double touch drag for movement of viewshed location point and listeners for * changes in seek bar progress. */ private fun handleUiElements() { sceneView.setOnTouchListener(object : DefaultSceneViewOnTouchListener(sceneView) { // double tap and hold second tap to drag viewshed to a new location override fun onDoubleTouchDrag(motionEvent: MotionEvent): Boolean { // convert from screen point to location point val screenPoint = android.graphics.Point( motionEvent.x.roundToInt(), motionEvent.y.roundToInt() ) val locationPointFuture = sceneView.screenToLocationAsync(screenPoint) locationPointFuture.addDoneListener { try { val locationPoint = locationPointFuture.get() // add 50 meters to location point and set to viewshed viewShed.location = Point(locationPoint.x, locationPoint.y, locationPoint.z + 50) } catch (e: InterruptedException) { logError("Error converting screen point to location point: " + e.message) } catch (e: ExecutionException) { logError("Error converting screen point to location point: " + e.message) } } // ignore default double touch drag gesture return true } }) // toggle visibility of the viewshed viewshedVisibilityCheckBox.setOnCheckedChangeListener { buttonView, isChecked -> viewShed.isVisible = isChecked } // toggle visibility of the frustum outline frustumVisibilityCheckBox.setOnCheckedChangeListener { buttonView, isChecked -> viewShed.setFrustumOutlineVisible(isChecked) } // heading range 0 - 360 headingSeekBar.max = 360 setHeading(initHeading) headingSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { setHeading(seekBar.progress) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // set arbitrary max to 180 to avoid nonsensical pitch values pitchSeekBar.max = 180 setPitch(initPitch) pitchSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { setPitch(seekBar.progress) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // horizontal angle range 1 - 120 horizontalAngleSeekBar.max = 120 setHorizontalAngle(initHorizontalAngle) horizontalAngleSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { val horizontalAngle = horizontalAngleSeekBar.progress if (horizontalAngle > 0) { // horizontal angle must be > 0 setHorizontalAngle(horizontalAngle) } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // vertical angle range 1 - 120 verticalAngleSeekBar.max = 120 setVerticalAngle(initVerticalAngle) verticalAngleSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { val verticalAngle = verticalAngleSeekBar.progress if (verticalAngle > 0) { // vertical angle must be > 0 setVerticalAngle(verticalAngle) } } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // initialize the minimum distance minDistance = initMinDistance // set to 1000 below the arbitrary max minDistanceSeekBar.max = 8999 setMinDistance(initMinDistance) minDistanceSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { minDistance = seekBar.progress if (maxDistance - minDistance < 1000) { maxDistance = minDistance + 1000 setMaxDistance(maxDistance) } setMinDistance(minDistance) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) // initialize the maximum distance maxDistance = initMaxDistance // set arbitrary max to 9999 to allow a maximum of 4 digits maxDistanceSeekBar.max = 9999 setMaxDistance(initMaxDistance) maxDistanceSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) { maxDistance = seekBar.progress if (maxDistance - minDistance < 1000) { minDistance = if (maxDistance > 1000) { maxDistance - 1000 } else { 0 } setMinDistance(minDistance) } setMaxDistance(maxDistance) } override fun onStartTrackingTouch(seekBar: SeekBar) {} override fun onStopTrackingTouch(seekBar: SeekBar) {} }) } /** * Set viewshed heading, seek bar progress, and current heading text view. * * @param heading in degrees */ private fun setHeading(heading: Int) { headingSeekBar.progress = heading currHeading.text = heading.toString() viewShed.heading = heading.toDouble() } /** * Set viewshed pitch, seek bar progress, and current pitch text view. * * @param pitch in degrees */ private fun setPitch(pitch: Int) { pitchSeekBar.progress = pitch currPitch.text = pitch.toString() viewShed.pitch = pitch.toDouble() } /** * Set viewshed horizontal angle, seek bar progress, and current horizontal angle text view. * * @param horizontalAngle in degrees, > 0 and <= 120 */ private fun setHorizontalAngle(horizontalAngle: Int) { if (horizontalAngle in 1..120) { horizontalAngleSeekBar.progress = horizontalAngle currHorizontalAngle.text = horizontalAngle.toString() viewShed.horizontalAngle = horizontalAngle.toDouble() } else { logError("Horizontal angle must be greater than 0 and less than or equal to 120.") } } /** * Set viewshed vertical angle, seek bar progress, and current vertical angle text view. * * @param verticalAngle in degrees, > 0 and <= 120 */ private fun setVerticalAngle(verticalAngle: Int) { if (verticalAngle in 1..120) { verticalAngleSeekBar.progress = verticalAngle currVerticalAngle.text = verticalAngle.toString() viewShed.verticalAngle = verticalAngle.toDouble() } else { logError("Vertical angle must be greater than 0 and less than or equal to 120.") } } /** * Set viewshed minimum distance, seek bar progress, and current minimum distance text view. * * @param minDistance in meters */ private fun setMinDistance(minDistance: Int) { minDistanceSeekBar.progress = minDistance currMinimumDistance.text = minDistance.toString() viewShed.minDistance = minDistance.toDouble() } /** * Set viewshed maximum distance, seek bar progress, and current maximum distance text view. * * @param maxDistance in meters */ private fun setMaxDistance(maxDistance: Int) { maxDistanceSeekBar.progress = maxDistance currMaximumDistance.text = maxDistance.toString() viewShed.maxDistance = maxDistance.toDouble() } override fun onPause() { sceneView.pause() super.onPause() } override fun onResume() { super.onResume() sceneView.resume() } override fun onDestroy() { sceneView.dispose() super.onDestroy() } /** * Log an error to logcat and to the screen via Toast. * @param message the text to log. */ private fun logError(message: String?) { message?.let { Log.e(TAG, message) Toast.makeText(this, message, Toast.LENGTH_LONG).show() } } companion object { private val TAG: String = MainActivity::class.java.simpleName } }
kotlin/viewshed-location/src/main/java/com/esri/arcgisruntime/sample/viewshedlocation/MainActivity.kt
3318520302
/* * This file is part of JuniperBot. * * JuniperBot 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. * JuniperBot 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 JuniperBot. If not, see <http://www.gnu.org/licenses/>. */ package ru.juniperbot.api import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration import org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration import org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration import org.springframework.boot.autoconfigure.security.servlet.SecurityRequestMatcherProviderAutoConfiguration import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Import import org.springframework.context.annotation.ImportResource import org.springframework.web.method.support.HandlerMethodArgumentResolver import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import ru.juniperbot.api.common.ApiRequestLoggingFilter import ru.juniperbot.api.common.AtomFeedArgumentResolver import ru.juniperbot.common.configuration.CommonConfiguration import ru.juniperbot.common.support.ModuleMessageSource import ru.juniperbot.common.support.ModuleMessageSourceImpl @Import(CommonConfiguration::class) @ImportResource("classpath:security-context.xml") @SpringBootApplication(exclude = [ SecurityAutoConfiguration::class, SecurityFilterAutoConfiguration::class, SecurityRequestMatcherProviderAutoConfiguration::class, OAuth2ClientAutoConfiguration::class, OAuth2ResourceServerAutoConfiguration::class ]) class JuniperApiApplication : WebMvcConfigurer { @Bean fun webMessages(): ModuleMessageSource = ModuleMessageSourceImpl("web-jbmessages") override fun addArgumentResolvers(argumentResolvers: MutableList<HandlerMethodArgumentResolver>?) { argumentResolvers!!.add(AtomFeedArgumentResolver()) } @Bean fun requestLoggingFilter(): ApiRequestLoggingFilter = ApiRequestLoggingFilter().apply { this.setBeforeMessagePrefix("Before Request ") this.setAfterMessagePrefix("After Request ") this.setBeforeMessageSuffix("") this.setAfterMessageSuffix("") this.setMaxPayloadLength(10000) this.setIncludeClientInfo(true) this.setIncludeQueryString(true) this.setIncludePayload(true) } } object Launcher { @JvmStatic fun main(args: Array<String>) { SpringApplication(JuniperApiApplication::class.java).run(*args) } }
jb-api/src/main/java/ru/juniperbot/api/Launcher.kt
2909361360
/* * 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.pcc.chronicle.api.flags import kotlinx.coroutines.flow.StateFlow /** * Entrypoint of configuration [Flags] for Chronicle: an abstraction layer between Chronicle and the * underlying application's configuration system. * * Each application integrating Chronicle will need to supply a [FlagsReader] to the dagger graph. * Most applications will populate the [Flags] for their [FlagsReader] using DeviceConfig. For * simplicity, it's required that [Flags] instances be identical for an entire application - even * if the application has multiple processes. */ interface FlagsReader { /** The current value of the [Flags] for Chronicle. */ val config: StateFlow<Flags> }
java/com/google/android/libraries/pcc/chronicle/api/flags/FlagsReader.kt
2409025372
package com.jayrave.falkon.sqlBuilders.test.create import com.jayrave.falkon.sqlBuilders.CreateTableSqlBuilder import com.jayrave.falkon.sqlBuilders.test.DbForTest import com.jayrave.falkon.sqlBuilders.test.buildArgListForSql import com.jayrave.falkon.sqlBuilders.test.execute import com.jayrave.falkon.sqlBuilders.test.findAllRecordsInTable import org.assertj.core.api.Assertions.assertThat class TestAutoIncrement( private val createTableSqlBuilder: CreateTableSqlBuilder, private val db: DbForTest) { fun `auto incrementing column increments value by at least 1 if not explicitly inserted`() { // Create table with auto incrementing primary key val counterColumn = ColumnInfoForTest("counter", db.intDataType) val idColumn = ColumnInfoForTest("id", db.intDataType, isId = true, autoIncrement = true) val tableInfo = TableInfoForTest( "test", listOf(idColumn, counterColumn), emptyList(), emptyList() ) val dataSource = db.dataSource dataSource.execute(createTableSqlBuilder.build(tableInfo)) // Insert records with increasing counter val counter = 1..5 counter.forEach { dataSource.execute( "INSERT INTO ${tableInfo.name} (${counterColumn.name}) " + "VALUES (${buildArgListForSql(it)})" ) } // Get all records from db val allRecords = dataSource.findAllRecordsInTable( tableInfo.name, listOf(idColumn.name, counterColumn.name) ) // Make sure all records got inserted assertThat(allRecords).hasSize(counter.count()) // Assert auto increment works allRecords.take(allRecords.size - 1).forEachIndexed { index, currentRecord -> // Extract fields of current record val currentRecordId = currentRecord[idColumn.name]!!.toInt() val currentRecordCounter = currentRecord[counterColumn.name]!!.toInt() // Extract fields of next record val nextRecord = allRecords[index + 1] val nextRecordId = nextRecord[idColumn.name]!!.toInt() val nextRecordCounter = nextRecord[counterColumn.name]!!.toInt() assertThat(Math.signum(currentRecordId.compareTo(nextRecordId).toFloat())).isEqualTo( Math.signum(currentRecordCounter.compareTo(nextRecordCounter).toFloat()) ) } } }
falkon-sql-builder-test-common/src/main/kotlin/com/jayrave/falkon/sqlBuilders/test/create/TestAutoIncrement.kt
18066891
package com.wabadaba.dziennik import org.amshove.kluent.shouldBeInstanceOf import kotlin.reflect.KClass abstract class BaseTest { protected fun readFile(filename: String) = this.javaClass.getResource(filename)?.readText() ?: throw IllegalStateException("File $filename not found") fun <T : Any> Any.shouldBeInstanceOf(clazz: KClass<T>, assertions: (T.() -> Unit)) { this shouldBeInstanceOf clazz @Suppress("UNCHECKED_CAST") assertions(this as T) } }
app/src/test/kotlin/com/wabadaba/dziennik/BaseTest.kt
984891800
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package dev.flutter.rfw.examples.local import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
packages/rfw/example/local/android/app/src/main/kotlin/dev/flutter/rfw/examples/local/MainActivity.kt
1250667237
/* * Copyright 2021 Ren Binden * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.monsters.bukkit.monsterstat import com.rpkit.core.expression.RPKExpressionService import com.rpkit.core.service.Services import com.rpkit.monsters.bukkit.RPKMonstersBukkit import com.rpkit.monsters.bukkit.monsterlevel.RPKMonsterLevelService import org.bukkit.ChatColor import org.bukkit.attribute.Attribute import org.bukkit.entity.EntityType import org.bukkit.entity.LivingEntity class RPKMonsterStatServiceImpl(override val plugin: RPKMonstersBukkit) : RPKMonsterStatService { override fun getMonsterHealth(monster: LivingEntity): Double { return monster.health } override fun setMonsterHealth(monster: LivingEntity, health: Double) { monster.health = health setMonsterNameplate(monster, health = health) } override fun getMonsterMaxHealth(monster: LivingEntity): Double { val monsterNameplate = monster.customName val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return monster.health val maxHealth = if (monsterNameplate != null) { val maxHealthString = Regex("${ChatColor.RED}❤ ${ChatColor.WHITE}(\\d+\\.\\d+)/(\\d+\\.\\d+)") .find(monsterNameplate) ?.groupValues ?.get(2) if (maxHealthString != null) { try { maxHealthString.toDouble() } catch (ignored: NumberFormatException) { calculateMonsterMaxHealth(monster.type, monsterLevelService.getMonsterLevel(monster)) } } else { calculateMonsterMaxHealth(monster.type, monsterLevelService.getMonsterLevel(monster)) } } else { calculateMonsterMaxHealth(monster.type, monsterLevelService.getMonsterLevel(monster)) } monster.getAttribute(Attribute.GENERIC_MAX_HEALTH)?.baseValue = maxHealth return monster.getAttribute(Attribute.GENERIC_MAX_HEALTH)?.value ?: monster.health } override fun getMonsterMinDamageMultiplier(monster: LivingEntity): Double { return getMonsterMinDamage(monster) / (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMinDamageMultiplier(monster: LivingEntity, minDamageMultiplier: Double) { setMonsterNameplate(monster, minDamageMultiplier = minDamageMultiplier) } override fun getMonsterMinDamage(monster: LivingEntity): Double { val monsterNameplate = monster.customName if (monsterNameplate != null) { val minDamage = Regex("${ChatColor.RED}⚔ ${ChatColor.WHITE}(\\d+\\.\\d+)-(\\d+\\.\\d+)") .find(monsterNameplate) ?.groupValues ?.get(1) if (minDamage != null) { try { return minDamage.toDouble() } catch (ignored: NumberFormatException) { } } } val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return 1.0 return calculateMonsterMinDamageMultiplier(monster.type, monsterLevelService.getMonsterLevel(monster)) * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMinDamage(monster: LivingEntity, minDamage: Double) { setMonsterNameplate(monster, minDamage = minDamage) } override fun getMonsterMaxDamageMultiplier(monster: LivingEntity): Double { return getMonsterMaxDamage(monster) / (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMaxDamageMultiplier(monster: LivingEntity, maxDamageMultiplier: Double) { setMonsterNameplate(monster, maxDamageMultiplier = maxDamageMultiplier) } override fun getMonsterMaxDamage(monster: LivingEntity): Double { val monsterNameplate = monster.customName if (monsterNameplate != null) { val maxDamage = Regex("${ChatColor.RED}⚔ ${ChatColor.WHITE}(\\d+\\.\\d+)-(\\d+\\.\\d+)") .find(monsterNameplate) ?.groupValues ?.get(2) if (maxDamage != null) { try { return maxDamage.toDouble() } catch (ignored: NumberFormatException) { } } } val monsterLevelService = Services[RPKMonsterLevelService::class.java] ?: return 1.0 return calculateMonsterMaxDamageMultiplier(monster.type, monsterLevelService.getMonsterLevel(monster)) * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0) } override fun setMonsterMaxDamage(monster: LivingEntity, maxDamage: Double) { setMonsterNameplate(monster, maxDamage = maxDamage) } fun calculateMonsterMaxHealth(entityType: EntityType, level: Int): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 1.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.$entityType.max-health") ?: plugin.config.getString("monsters.default.max-health") ?: return 1.0) return expression.parseDouble(mapOf( "level" to level.toDouble() )) ?: 1.0 } fun calculateMonsterMinDamageMultiplier(entityType: EntityType, level: Int): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 1.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.$entityType.min-damage-multiplier") ?: plugin.config.getString("monsters.default.min-damage-multiplier") ?: return 1.0) return expression.parseDouble(mapOf( "level" to level.toDouble() )) ?: 1.0 } fun calculateMonsterMaxDamageMultiplier(entityType: EntityType, level: Int): Double { val expressionService = Services[RPKExpressionService::class.java] ?: return 1.0 val expression = expressionService.createExpression(plugin.config.getString("monsters.$entityType.max-damage-multiplier") ?: plugin.config.getString("monsters.default.max-damage-multiplier") ?: return 1.0) return expression.parseDouble(mapOf( "level" to level.toDouble() )) ?: 1.0 } fun setMonsterNameplate( monster: LivingEntity, level: Int = Services[RPKMonsterLevelService::class.java]?.getMonsterLevel(monster) ?: 1, health: Double = getMonsterHealth(monster), maxHealth: Double = getMonsterMaxHealth(monster), minDamageMultiplier: Double = getMonsterMinDamageMultiplier(monster), maxDamageMultiplier: Double = getMonsterMaxDamageMultiplier(monster), minDamage: Double = (minDamageMultiplier * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0)), maxDamage: Double = (maxDamageMultiplier * (monster.getAttribute(Attribute.GENERIC_ATTACK_DAMAGE)?.value ?: 1.0)) ) { val monsterName = monster.type.toString().lowercase().replace('_', ' ') val formattedHealth = String.format("%.2f", health) val formattedMaxHealth = String.format("%.2f", maxHealth) val formattedMinDamage = String.format("%.2f", minDamage) val formattedMaxDamage = String.format("%.2f", maxDamage) val nameplate = "${ChatColor.WHITE}Lv${ChatColor.YELLOW}$level " + "$monsterName " + "${ChatColor.RED}❤ ${ChatColor.WHITE}$formattedHealth/$formattedMaxHealth " + "${ChatColor.RED}⚔ ${ChatColor.WHITE}$formattedMinDamage-$formattedMaxDamage" monster.customName = nameplate monster.isCustomNameVisible = true } }
bukkit/rpk-monsters-bukkit/src/main/kotlin/com/rpkit/monsters/bukkit/monsterstat/RPKMonsterStatServiceImpl.kt
3588922795
/* * Copyright 2020 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.characters.bukkit.command.character.set import com.rpkit.characters.bukkit.RPKCharactersBukkit import org.bukkit.command.Command import org.bukkit.command.CommandExecutor import org.bukkit.command.CommandSender /** * Character set command. * Parent command for commands used to set character attributes. */ class CharacterSetCommand(private val plugin: RPKCharactersBukkit) : CommandExecutor { private val characterSetProfileCommand = CharacterSetProfileCommand(plugin) private val characterSetNameCommand = CharacterSetNameCommand(plugin) private val characterSetGenderCommand = CharacterSetGenderCommand(plugin) private val characterSetAgeCommand = CharacterSetAgeCommand(plugin) private val characterSetRaceCommand = CharacterSetRaceCommand(plugin) private val characterSetDescriptionCommand = CharacterSetDescriptionCommand(plugin) private val characterSetDeadCommand = CharacterSetDeadCommand(plugin) override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<String>): Boolean { if (args.isNotEmpty()) { val newArgs = args.drop(1).toTypedArray() if (args[0].equals("profile", ignoreCase = true)) { return characterSetProfileCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("name", ignoreCase = true)) { return characterSetNameCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("gender", ignoreCase = true)) { return characterSetGenderCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("age", ignoreCase = true)) { return characterSetAgeCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("race", ignoreCase = true)) { return characterSetRaceCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("description", ignoreCase = true) || args[0].equals("desc", ignoreCase = true)) { return characterSetDescriptionCommand.onCommand(sender, command, label, newArgs) } else if (args[0].equals("dead", ignoreCase = true)) { return characterSetDeadCommand.onCommand(sender, command, label, newArgs) } else { sender.sendMessage(plugin.messages["character-set-usage"]) } } else { sender.sendMessage(plugin.messages["character-set-usage"]) } return true } }
bukkit/rpk-characters-bukkit/src/main/kotlin/com/rpkit/characters/bukkit/command/character/set/CharacterSetCommand.kt
3333139812
package io.hammerhead.mocha.dsl import io.hammerhead.mocha.api.TestAction import io.hammerhead.mocha.api.setup.Setup import io.hammerhead.mocha.api.uiactions.espresso.EspressoActionsDelegator import io.hammerhead.mocha.api.uiactions.uiautomator.UiActionsDelegator fun testAction(description: String, init: TestAction.() -> Unit) { val testAction = TestAction(description) testAction.init() } fun TestAction.setup(init: Setup.() -> Unit) { Setup().init() } fun TestAction.action(init: EspressoActionsDelegator.() -> Unit) { EspressoActionsDelegator().init() } fun TestAction.automatorAction(init: UiActionsDelegator.() -> Unit) { UiActionsDelegator().init() }
mocha-api/src/main/kotlin/io/hammerhead/mocha/dsl/TestActionsDsl.kt
1673263855
package me.minikin.kebab import android.os.Bundle import io.flutter.app.FlutterActivity import io.flutter.plugins.GeneratedPluginRegistrant class MainActivity(): FlutterActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) GeneratedPluginRegistrant.registerWith(this) } }
android/app/src/main/kotlin/me/minikin/kebab/MainActivity.kt
355905920
package org.rust.lang.core.psi import com.intellij.psi.PsiDirectory import java.util.* interface RustMod : RustQualifiedNameOwner, RustItemsOwner { /** * Returns a parent module (`super::` in paths). * * The parent module may be in the same or other file. * * Reference: * https://doc.rust-lang.org/reference.html#paths */ val `super`: RustMod? val modName: String? val ownsDirectory: Boolean val ownedDirectory: PsiDirectory? val isCrateRoot: Boolean companion object { val MOD_RS = "mod.rs" } } val RustMod.superMods: List<RustMod> get() { // For malformed programs, chain of `super`s may be infinite // because of cycles, and we need to detect this situation. val visited = HashSet<RustMod>() return generateSequence(this) { it.`super` } .takeWhile { visited.add(it) } .toList() }
src/main/kotlin/org/rust/lang/core/psi/RustMod.kt
2456865487
package com.droibit.quickly.main import com.droibit.quickly.data.repository.appinfo.AppInfo import com.droibit.quickly.data.repository.appinfo.AppInfoRepository import com.droibit.quickly.data.repository.settings.ShowSettingsRepository import com.jakewharton.rxrelay.BehaviorRelay import com.jakewharton.rxrelay.PublishRelay import rx.Observable import rx.schedulers.Schedulers import timber.log.Timber class LoadAppInfoTask( private val appInfoRepository: AppInfoRepository, private val showSettingsRepository: ShowSettingsRepository, private val runningRelay: BehaviorRelay<Boolean>) : MainContract.LoadAppInfoTask { private var cachedApps: List<AppInfo>? = null @Suppress("HasPlatformType") override fun isRunning() = runningRelay.distinctUntilChanged() override fun requestLoad(forceReload: Boolean): Observable<List<AppInfo>> { Timber.d("requestLoad(forceReload=$forceReload)") // TODO: if forceReload, need delay 1sec val shouldRunningCall = forceReload || !appInfoRepository.hasCache return appInfoRepository.loadAll(forceReload) .map { apps -> apps.filter { filterIfOnlyInstalled(it) } } .filter { it != cachedApps } .doOnNext { cachedApps = it } .subscribeOn(Schedulers.io()) .doOnSubscribe { if (shouldRunningCall) runningRelay.call(true) } // TODO: need review .doOnUnsubscribe { if (shouldRunningCall) runningRelay.call(false) } // TODO: need review } private fun filterIfOnlyInstalled(appInfo: AppInfo): Boolean { if (showSettingsRepository.isShowSystem) { return true } return !appInfo.preInstalled } }
app/src/main/kotlin/com/droibit/quickly/main/LoadAppInfoTask.kt
4281276690
package tutorial.`object` import java.util.* open class Base(val name: String) { init { println("Initializing Base") } open val size: Int = name.length.also { println("Initializing size in Base: $it") } } class Derived( name: String, val lastName: String ) : Base(name.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } .also { println("Argument for Base: $it") }) { init { println("Initializing Derived") } override val size: Int = (super.size + lastName.length).also { println("Initializing size in Derived: $it") } } fun main() { println("Constructing Derived(\"hello\", \"world\")") val d = Derived("hello", "world") }
src/kotlin/src/tutorial/object/Inheritance.kt
2540411006
package io.innofang.abstract_factory.example.kotlin /** * Created by Inno Fang on 2017/9/2. */ abstract class CakeFactory { abstract fun cream(): CakeCream abstract fun style(): CakeStyle }
src/io/innofang/abstract_factory/example/kotlin/CakeFactory.kt
4083403649
package de.maibornwolff.codecharta.importer.metricgardenerimporter import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper import com.lordcodes.turtle.ShellLocation import com.lordcodes.turtle.shellRun import de.maibornwolff.codecharta.importer.metricgardenerimporter.json.MetricGardenerProjectBuilder import de.maibornwolff.codecharta.importer.metricgardenerimporter.model.MetricGardenerNodes import de.maibornwolff.codecharta.serialization.ProjectSerializer import de.maibornwolff.codecharta.tools.interactiveparser.InteractiveParser import de.maibornwolff.codecharta.tools.interactiveparser.ParserDialogInterface import mu.KotlinLogging import picocli.CommandLine import java.io.File import java.io.IOException import java.io.PrintStream import java.nio.charset.Charset import java.nio.file.Paths import java.util.concurrent.Callable @CommandLine.Command( name = "metricgardenerimport", description = ["generates a cc.json file from a project parsed with metric-gardener"], footer = ["Copyright(c) 2022, MaibornWolff GmbH"] ) class MetricGardenerImporter( private val output: PrintStream = System.out ) : Callable<Void>, InteractiveParser { private val logger = KotlinLogging.logger {} private val mapper = jacksonObjectMapper() @CommandLine.Option( names = ["-h", "--help"], usageHelp = true, description = ["Specify: path/to/input/folder/or/file -o path/to/outputfile.json"] ) private var help = false @CommandLine.Parameters( arity = "1", paramLabel = "FOLDER or FILE", description = ["path for project folder or code file"] ) private var inputFile = File("") @CommandLine.Option(names = ["-j", "--is-json-file"], description = ["Input file is a MetricGardener JSON file"]) private var isJsonFile: Boolean = false @CommandLine.Option(names = ["-o", "--output-file"], description = ["output File"]) private var outputFile: String? = null @CommandLine.Option(names = ["-nc", "--not-compressed"], description = ["save uncompressed output File"]) private var compress = true @Throws(IOException::class) override fun call(): Void? { if (!inputFile.exists()) { printErrorLog() return null } if (!isJsonFile) { val tempMgOutput = File.createTempFile("MGOutput", ".json") tempMgOutput.deleteOnExit() val npm = if (isWindows()) "npm.cmd" else "npm" shellRun( command = npm, arguments = listOf( "exec", "-y", "metric-gardener", "--", "parse", inputFile.absolutePath, "--output-path", tempMgOutput.absolutePath ), workingDirectory = ShellLocation.CURRENT_WORKING ) inputFile = tempMgOutput } val metricGardenerNodes: MetricGardenerNodes = mapper.readValue(inputFile.reader(Charset.defaultCharset()), MetricGardenerNodes::class.java) val metricGardenerProjectBuilder = MetricGardenerProjectBuilder(metricGardenerNodes) val project = metricGardenerProjectBuilder.build() ProjectSerializer.serializeToFileOrStream(project, outputFile, output, compress) return null } private fun printErrorLog() { val path = Paths.get("").toAbsolutePath().toString() logger.error { "Current working directory = $path" } logger.error { "Could not find $inputFile" } } companion object { @JvmStatic fun main(args: Array<String>) { CommandLine(MetricGardenerImporter()).execute(*args) } } private fun isWindows(): Boolean { return System.getProperty("os.name").contains("win", ignoreCase = true) } override fun getDialog(): ParserDialogInterface = ParserDialog }
analysis/import/MetricGardenerImporter/src/main/kotlin/de/maibornwolff/codecharta/importer/metricgardenerimporter/MetricGardenerImporter.kt
1672956869
package cc.vileda.kalfor data class KalforProxyRequest( val key: String = "", val path: String = "" )
library/src/main/kotlin/cc/vileda/kalfor/KalforProxyRequest.kt
2187986884
package com.rectanglel.patstatic.model import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonWriter import java.io.* import java.lang.reflect.Type import java.util.concurrent.locks.ReentrantReadWriteLock /** * Abstract class that has logic that helps with deciding to download from disk or from internet * * * Created by epicstar on 3/12/17. * @author Jeremy Jao */ abstract class AbstractDataManager<out T>(dataDirectory: File, private val staticData: StaticData, private val serializedType: Type, private val cacheFolderName: String) { private val rwl: ReentrantReadWriteLock = ReentrantReadWriteLock() protected val dataDirectory: File = File(dataDirectory, cacheFolderName) private val readLock: ReentrantReadWriteLock.ReadLock get() = rwl.readLock() private val writeLock: ReentrantReadWriteLock.WriteLock get() = rwl.writeLock() protected val gson: Gson get() = GsonBuilder().create() init { this.dataDirectory.mkdirs() } /** * Save the object to disk as JSON into the file * @param obj the object to save * @param file the file to save to * @throws IOException if the serialization fails */ @Throws(IOException::class) protected fun saveAsJson(obj: Any, file: File) { writeLock.lock() val fileWriter = FileWriter(file) val writer = JsonWriter(fileWriter) try { val gson = gson gson.toJson(obj, serializedType, writer) } finally { writer.flush() fileWriter.close() writer.close() writeLock.unlock() } } @Throws(IOException::class) protected fun getFromDisk(file: File): T { // file exists... get from disk if (file.exists()) { readLock.lock() val fileReader = FileReader(file) val jsonReader = JsonReader(fileReader) try { return gson.fromJson(jsonReader, serializedType) } finally { fileReader.close() jsonReader.close() readLock.unlock() } } // if file doesn't exist, save bundled file from installation to disk val fileName = String.format("%s/%s", cacheFolderName, file.name) copyStreamToFile(staticData.getInputStreamForFileName(fileName), file) return getFromDisk(file) } @Throws(IOException::class) protected fun copyStreamToFile(reader: InputStreamReader, file: File) { writeLock.lock() try { reader.use { input -> val fileWriter = FileWriter(file) fileWriter.use { input.copyTo(it) } } } finally { writeLock.unlock() } } }
pat-static/src/main/kotlin/com/rectanglel/patstatic/model/AbstractDataManager.kt
2766930906
package com.github.kmizu.kollection import com.github.kmizu.kollection.type_classes.KMonoid infix fun <T> T.cons(other: KList<T>): KList<T> = KList.Cons(this, other) fun <T> KList(vararg elements: T): KList<T> = run { KList.make(*elements) } infix fun <T> KList<T>.concat(right: KList<T>): KList<T> = run { this.reverse().foldLeft(right){result, e -> e cons result} } fun <T> KList<KList<T>>.flatten(): KList<T> = run { this.flatMap {x -> x} } fun <T, U> KList<Pair<T, U>>.unzip(): Pair<KList<T>, KList<U>> = run { tailrec fun loop(rest: KList<Pair<T, U>>, a: KList<T>, b: KList<U>): Pair<KList<T>, KList<U>> = when(rest) { is KList.Nil -> Pair(a.reverse(), b.reverse()) is KList.Cons<Pair<T, U>> -> loop(rest.tl, rest.hd.first cons a, rest.hd.second cons b) } loop(this, KList.Nil, KList.Nil) } infix fun <T> KList<T>.contains(element: T): Boolean = this.exists {e -> e == element}
src/main/kotlin/com/github/kmizu/kollection/KListExtensions.kt
4223558730
package se.ansman.kotshi import com.squareup.moshi.JsonWriter import com.squareup.moshi.Moshi import okio.Buffer import org.junit.Before import org.junit.Test import kotlin.test.assertEquals class TestNullablesWithDefaults { private lateinit var moshi: Moshi @Before fun setup() { moshi = Moshi.Builder() .add(TestFactory) .build() } @Test fun withValues() { val json = """ |{ | "v1": 1, | "v2": "2", | "v3": 3, | "v4": 4, | "v5": 5, | "v6": 6.0, | "v7": 7.0, | "v8": "n/a", | "v9": [ | "Hello" | ] |} """.trimMargin() val expected = NullablesWithDefaults( v1 = 1, v2 = '2', v3 = 3, v4 = 4, v5 = 5L, v6 = 6f, v7 = 7.0, v8 = "n/a", v9 = listOf("Hello") ) expected.testFormatting(json) } @Test fun withNullValues() { val expected = NullablesWithDefaults( v1 = null, v2 = null, v3 = null, v4 = null, v5 = null, v6 = null, v7 = null, v8 = null, v9 = null ) val actual = moshi.adapter(NullablesWithDefaults::class.java).fromJson(""" |{ | "v1": null, | "v2": null, | "v3": null, | "v4": null, | "v5": null, | "v6": null, | "v7": null, | "v8": null, | "v9": null |} """.trimMargin()) assertEquals(expected, actual) } @Test fun withAbsentValues() { val expected = NullablesWithDefaults() val actual = moshi.adapter(NullablesWithDefaults::class.java).fromJson("{}") assertEquals(expected, actual) } private inline fun <reified T> T.testFormatting(json: String) { val adapter = moshi.adapter(T::class.java) val actual = adapter.fromJson(json) assertEquals(this, actual) assertEquals(json, Buffer() .apply { JsonWriter.of(this).run { indent = " " adapter.toJson(this, actual) } } .readUtf8()) } }
tests/src/test/kotlin/se/ansman/kotshi/TestNullablesWithDefaults.kt
2404193832
package de.mkammerer.grpcchat.server import com.google.common.cache.CacheBuilder import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.TimeUnit /** * A user. */ data class User(val username: String, val password: String) { override fun toString(): String = username } /** * A token. */ data class Token(val data: String) { override fun toString() = data } /** * Manages users. */ interface UserService { /** * Registeres a new user. * * @throws UserAlreadyExistsException If the user already exists. */ fun register(username: String, password: String): User /** * Logs the user with the given [username] and [password] in. Returns an access token. */ fun login(username: String, password: String): Token? /** * Validates the [token] and returns the corresponding user. */ fun validateToken(token: Token): User? /** * Determines if the user with the given [username] exists. */ fun exists(username: String): Boolean } /** * Is thrown if the user already exists. */ class UserAlreadyExistsException(username: String) : Exception("User '$username' already exists") class InMemoryUserService( private val tokenGenerator: TokenGenerator ) : UserService { private val users = ConcurrentHashMap<String, User>() private val loggedIn = CacheBuilder.newBuilder().expireAfterAccess(10, TimeUnit.MINUTES).build<Token, User>() override fun exists(username: String): Boolean { return users.containsKey(username) } override fun register(username: String, password: String): User { if (exists(username)) throw UserAlreadyExistsException(username) val user = User(username, password) users.put(user.username, user) return user } override fun login(username: String, password: String): Token? { val user = users[username] ?: return null if (user.password == password) { val token = Token(tokenGenerator.create()) loggedIn.put(token, user) return token } else return null } override fun validateToken(token: Token): User? { return loggedIn.getIfPresent(token) } }
server/src/main/kotlin/de/mkammerer/grpcchat/server/Users.kt
2514486455
package net.pterodactylus.sone.utils import com.fasterxml.jackson.databind.node.ArrayNode import com.fasterxml.jackson.databind.node.ObjectNode import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.equalTo import org.hamcrest.Matchers.instanceOf import org.hamcrest.Matchers.nullValue import org.junit.Test /** * Unit test for JSON utilities. */ class JsonTest { @Test fun `object node is created correctly`() { val objectNode = jsonObject { put("foo", "bar") } assertThat(objectNode, instanceOf(ObjectNode::class.java)) assertThat(objectNode.toString(), equalTo("{\"foo\":\"bar\"}")) } @Test fun `object node is created with correctly-typed properties`() { val objectNode = jsonObject("string" to "foo", "int" to 1, "long" to 2L, "boolean" to true, "other" to Any()) assertThat(objectNode["string"].isTextual, equalTo(true)) assertThat(objectNode["string"].asText(), equalTo("foo")) assertThat(objectNode["int"].isInt, equalTo(true)) assertThat(objectNode["int"].asInt(), equalTo(1)) assertThat(objectNode["long"].isLong, equalTo(true)) assertThat(objectNode["long"].asLong(), equalTo(2L)) assertThat(objectNode["boolean"].isBoolean, equalTo(true)) assertThat(objectNode["boolean"].asBoolean(), equalTo(true)) assertThat(objectNode["other"], nullValue()) } @Test fun `array node is created correctly`() { val arrayNode = listOf( jsonObject { put("foo", "bar") }, jsonObject { put("baz", "quo") } ).toArray() assertThat(arrayNode, instanceOf(ArrayNode::class.java)) assertThat(arrayNode.toString(), equalTo("[{\"foo\":\"bar\"},{\"baz\":\"quo\"}]")) } @Test fun `array is created correctly for strings`() { val arrayNode = jsonArray("foo", "bar", "baz") assertThat(arrayNode.toString(), equalTo("[\"foo\",\"bar\",\"baz\"]")) } }
src/test/kotlin/net/pterodactylus/sone/utils/JsonTest.kt
3699815894
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.collection import com.efficios.jabberwocky.trace.Trace import com.efficios.jabberwocky.trace.TraceIterator import com.efficios.jabberwocky.trace.event.TraceEvent import com.efficios.jabberwocky.utils.RewindingSortedCompoundIterator import com.efficios.jabberwocky.utils.SortedCompoundIterator import java.util.* class BaseTraceCollectionIterator<out E : TraceEvent> (traceCollection: TraceCollection<E, Trace<E>>) : RewindingSortedCompoundIterator<E, TraceIterator<E>>(traceCollection.traces.map { it.iterator() }, compareBy { event -> event.timestamp }), TraceCollectionIterator<E> { override fun seek(timestamp: Long) { iterators.forEach { it.seek(timestamp) } clearCaches() } override fun close() { iterators.forEach { it.close() } } }
jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/collection/BaseTraceCollectionIterator.kt
380317871
package de.ph1b.audiobook.playback.player import com.google.android.exoplayer2.MediaItem import com.google.android.exoplayer2.source.ConcatenatingMediaSource import com.google.android.exoplayer2.source.MediaSource import com.google.android.exoplayer2.source.MediaSourceFactory import de.ph1b.audiobook.data.Book2 import de.ph1b.audiobook.data.Chapter2 import de.ph1b.audiobook.data.toUri import javax.inject.Inject class DataSourceConverter @Inject constructor( private val mediaSourceFactory: MediaSourceFactory ) { fun toMediaSource(content: Book2): MediaSource { return if (content.chapters.size > 1) { val allSources = content.chapters.map { it.toMediaSource() } ConcatenatingMediaSource(*allSources.toTypedArray()) } else { content.currentChapter.toMediaSource() } } private fun Chapter2.toMediaSource(): MediaSource { val item = MediaItem.Builder() .setUri(id.toUri()) .build() return mediaSourceFactory.createMediaSource(item) } }
playback/src/main/kotlin/de/ph1b/audiobook/playback/player/DataSourceConverter.kt
3700841851
package com.github.ysl3000.bukkit.pathfinding.goals import com.github.ysl3000.bukkit.pathfinding.entity.Insentient import com.github.ysl3000.bukkit.pathfinding.pathfinding.Navigation import com.github.ysl3000.bukkit.pathfinding.pathfinding.PathfinderGoal import org.bukkit.Location import org.bukkit.Material class PathfinderGoalMoveToLocation(private val pathfinderGoalEntity: Insentient, private val targetLocation: Location, private val walkSpeed: Double, private val distance: Double) : PathfinderGoal { private val navigation: Navigation = pathfinderGoalEntity.getNavigation() private var isAlreadySet = false override fun shouldExecute(): Boolean { return if (this.isAlreadySet) { false } else pathfinderGoalEntity.getBukkitEntity().location.distanceSquared(targetLocation) > distance } override fun shouldTerminate(): Boolean { isAlreadySet = !pathfinderGoalEntity.getNavigation().isDoneNavigating() return isAlreadySet } override fun init() { if (!this.isAlreadySet) { this.navigation.moveTo(this.targetLocation, walkSpeed) } } override fun execute() { if (pathfinderGoalEntity.getBukkitEntity().location.add(pathfinderGoalEntity.getBukkitEntity().location.direction.normalize()) .block.type != Material.AIR) { pathfinderGoalEntity.jump() } } override fun reset() {} private fun setMessage(message: String) { pathfinderGoalEntity.getBukkitEntity().customName = message pathfinderGoalEntity.getBukkitEntity().isCustomNameVisible = true } }
PathfinderAPI/src/main/java/com/github/ysl3000/bukkit/pathfinding/goals/PathfinderGoalMoveToLocation.kt
1119314588
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.instantexecution.serialization.codecs import org.gradle.api.internal.artifacts.DefaultResolvedArtifact import org.gradle.api.internal.artifacts.PreResolvedResolvableArtifact import org.gradle.api.internal.artifacts.ivyservice.resolveengine.artifact.ResolvableArtifact import org.gradle.api.internal.artifacts.ivyservice.resolveengine.result.ComponentIdentifierSerializer import org.gradle.api.internal.tasks.TaskDependencyContainer import org.gradle.instantexecution.serialization.Codec import org.gradle.instantexecution.serialization.ReadContext import org.gradle.instantexecution.serialization.WriteContext import org.gradle.internal.component.local.model.ComponentFileArtifactIdentifier import org.gradle.internal.component.model.DefaultIvyArtifactName import java.io.File object ResolvableArtifactCodec : Codec<ResolvableArtifact> { private val componentIdSerializer = ComponentIdentifierSerializer() override suspend fun WriteContext.encode(value: ResolvableArtifact) { // TODO - handle other types if (value !is DefaultResolvedArtifact) { throw UnsupportedOperationException("Don't know how to serialize for ${value.javaClass.name}.") } // Write the source artifact writeString(value.file.absolutePath) writeString(value.artifactName.name) writeString(value.artifactName.type) writeNullableString(value.artifactName.extension) writeNullableString(value.artifactName.classifier) // TODO - preserve the artifact id implementation instead of unpacking the component id componentIdSerializer.write(this, value.id.componentIdentifier) // TODO - preserve the artifact's owner id (or get rid of it as it's not used for transforms) } override suspend fun ReadContext.decode(): ResolvableArtifact { val file = File(readString()) val artifactName = DefaultIvyArtifactName(readString(), readString(), readNullableString(), readNullableString()) val componentId = componentIdSerializer.read(this) return PreResolvedResolvableArtifact(null, artifactName, ComponentFileArtifactIdentifier(componentId, file.name), file, TaskDependencyContainer.EMPTY) } }
subprojects/instant-execution/src/main/kotlin/org/gradle/instantexecution/serialization/codecs/ResolvableArtifactCodec.kt
1654904037
package elite.gils.country /** * Continent: (Name) * Country: (Name) */ enum class AO private constructor( //Leave the code below alone (unless optimizing) private val name: String) { //List of State/Province names (Use 2 Letter/Number Combination codes) /** * Name: */ AA("Example"), /** * Name: */ AB("Example"), /** * Name: */ AC("Example"); fun getName(state: AO): String { return state.name } }
ObjectAvoidance/kotlin/src/elite/gils/country/AO.kt
300457392
package org.seasar.doma.jdbc.criteria import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.seasar.doma.jdbc.criteria.entity.Emp import org.seasar.doma.jdbc.criteria.entity.Emp_ import org.seasar.doma.jdbc.criteria.mock.MockConfig import java.math.BigDecimal internal class KEntityqlBatchUpdateTest { private val entityql = org.seasar.doma.kotlin.jdbc.criteria.KEntityql(MockConfig()) @Test fun test() { val emp = Emp() emp.id = 1 emp.name = "aaa" emp.salary = BigDecimal("1000") emp.version = 1 val e = Emp_() val stmt = entityql.update(e, listOf(emp)) val sql = stmt.asSql() Assertions.assertEquals( "update EMP set NAME = 'aaa', SALARY = 1000, VERSION = 1 + 1 where ID = 1 and VERSION = 1", sql.formattedSql ) } @Test fun ignoreVersion() { val emp = Emp() emp.id = 1 emp.name = "aaa" emp.salary = BigDecimal("1000") emp.version = 1 val e = Emp_() val stmt = entityql.update(e, listOf(emp)) { ignoreVersion = true } val sql = stmt.asSql() Assertions.assertEquals( "update EMP set NAME = 'aaa', SALARY = 1000, VERSION = 1 where ID = 1", sql.formattedSql ) } @Test fun empty() { val e = Emp_() val stmt = entityql.update(e, emptyList()) val sql = stmt.asSql() Assertions.assertEquals("This SQL is empty because target entities are empty.", sql.formattedSql) } }
doma-kotlin/src/test/kotlin/org/seasar/doma/jdbc/criteria/KEntityqlBatchUpdateTest.kt
1791473932
package com.thornbirds.repodemo import android.content.ComponentName import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.snackbar.Snackbar import com.thornbirds.framework.activity.ComponentActivity import com.thornbirds.repodemo.MyService.MyServiceImpl class MainActivity : ComponentActivity() { override val TAG: String = "MainActivity" private var mPersistFragment: Fragment? = null private var mAddFragment1: Fragment? = null private var mAddFragment2: Fragment? = null private var mReplaceFragment1: Fragment? = null private var mReplaceFragment2: Fragment? = null private var mMyService: MyServiceImpl? = null private val mServiceConnection: ServiceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { mMyService = service as MyServiceImpl Log.d(TAG, "onServiceDisconnected mMyService") mMyService!!.print("log onServiceConnected") } override fun onServiceDisconnected(name: ComponentName) { mMyService = null Log.d(TAG, "onServiceDisconnected mMyService") } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val fab = findViewById<View>(R.id.fab) as FloatingActionButton fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() // Intent intent = new Intent(MainActivity.this, com.thornbirds.framework.MainActivity.class); // startActivity(intent); val fragmentManager = supportFragmentManager if (mAddFragment1 == null) { val fragment: Fragment = TestFragment() val bundle = Bundle() bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 1) fragment.arguments = bundle fragmentManager.beginTransaction().add(R.id.root_container, fragment).commit() mAddFragment1 = fragment } else if (mAddFragment2 == null) { val fragment: Fragment = TestFragment() val bundle = Bundle() bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 2) fragment.arguments = bundle fragmentManager.beginTransaction().add(R.id.root_container, fragment).commit() mAddFragment2 = fragment } else if (mReplaceFragment1 == null) { val fragment: Fragment = TestFragment() val bundle = Bundle() bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 3) fragment.arguments = bundle fragmentManager.beginTransaction().replace(R.id.root_container, fragment).commit() mReplaceFragment1 = fragment } else if (mReplaceFragment2 == null) { val fragment: Fragment = TestFragment() val bundle = Bundle() bundle.putInt(TestFragment.EXTRA_FRAGMENT_ID, 4) fragment.arguments = bundle fragmentManager.beginTransaction().replace(R.id.root_container, fragment).commit() mReplaceFragment2 = fragment } } mPersistFragment = supportFragmentManager.findFragmentById(R.id.test_fragment) val intent = Intent(this, MyService::class.java) bindService(intent, mServiceConnection, BIND_AUTO_CREATE) } override fun onResume() { super.onResume() Log.d(TAG, "onResume mMyService") if (mMyService != null) { mMyService!!.print("log onResume") } } override fun onStop() { super.onStop() Log.d(TAG, "onStop mMyService") if (mMyService != null) { mMyService!!.print("log onStop") } } override fun onDestroy() { super.onDestroy() Log.d(TAG, "onDestroy mMyService") if (mMyService != null) { mMyService!!.print("log onDestroy") } unbindService(mServiceConnection) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId return if (id == R.id.action_settings) { true } else super.onOptionsItemSelected(item) } }
app/src/main/java/com/thornbirds/repodemo/MainActivity.kt
724986848
package com.github.kory33.signvote.constants /** * Enumeration of statistics modes. * @author Kory */ enum class StatsType(val type: String, val typeMessageNode: String) { VOTES("votes", MessageConfigNodes.STATS_TYPE_VOTES), SCORE("score", MessageConfigNodes.STATS_TYPE_SCORE), MEAN("mean", MessageConfigNodes.STATS_TYPE_MEAN); override fun toString(): String { return this.type } companion object { /** * Get the enum value corresponding to the given type * @param typeString type of the statistics * * * @return enum value corresponding to the given type string */ fun fromString(typeString: String): StatsType { StatsType.values() .filter { it.type.equals(typeString, ignoreCase = true) } .forEach { return it } throw IllegalArgumentException("No stats type \'$typeString\' is available.") } } }
src/main/kotlin/com/github/kory33/signvote/constants/StatsType.kt
143963590
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.example.android.watchnextcodelab.channels import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.support.media.tv.TvContractCompat import android.util.Log import com.example.android.watchnextcodelab.database.MockDatabase import com.example.android.watchnextcodelab.watchlist.WatchlistManager private const val TAG = "WatchNextNotificationReceiver" class WatchNextNotificationReceiver : BroadcastReceiver() { private val watchlistManager = WatchlistManager.get() private val database = MockDatabase.get() override fun onReceive(context: Context, intent: Intent) { val extras = intent.extras // TODO: Step 10 extract the EXTRA_WATCH_NEXT_PROGRAM_ID val watchNextProgramId = extras.getLong(TvContractCompat.EXTRA_WATCH_NEXT_PROGRAM_ID) when(intent.action) { // TODO: Step 11 remove the movie from the watchlist. // A program has been removed from the watch next row. TvContractCompat.ACTION_WATCH_NEXT_PROGRAM_BROWSABLE_DISABLED -> { Log.d(TAG, "Program removed from watch next watch-next: $watchNextProgramId") database.findAllMovieProgramIds(context) .find { it.watchNextProgramId == watchNextProgramId } ?.apply { watchlistManager.removeMovieFromWatchlist(context, movieId) } } // TODO: Step 12 add the movie to the watchlist. TvContractCompat.ACTION_PREVIEW_PROGRAM_ADDED_TO_WATCH_NEXT -> { val programId = extras.getLong(TvContractCompat.EXTRA_PREVIEW_PROGRAM_ID) Log.d(TAG, "Preview program added to watch next program: $programId watch-next: $watchNextProgramId") database.findAllMovieProgramIds(context) .find { it.programIds.contains(programId) } ?.apply { watchlistManager.addToWatchlist(context, movieId) } } } } }
step_final/src/main/java/com/example/android/watchnextcodelab/channels/WatchNextNotificationReceiver.kt
1090012374
package example /** * Documentation for expected class Clock * in common module */ expect open class Clock() { fun getTime(): String /** * Time in minis */ fun getTimesInMillis(): String fun getYear(): String }
plugins/base/src/test/resources/multiplatform/basicMultiplatformTest/commonMain/kotlin/Clock.kt
3169051828
package us.mikeandwan.photos.di import android.app.Application import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import net.openid.appauth.AuthorizationService import us.mikeandwan.photos.authorization.AuthAuthenticator import us.mikeandwan.photos.authorization.AuthInterceptor import us.mikeandwan.photos.authorization.AuthService import us.mikeandwan.photos.authorization.AuthStateManager import us.mikeandwan.photos.database.AuthorizationDao import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) class AuthModule { @Provides @Singleton fun provideAuthService( application: Application, authorizationService: AuthorizationService, authStateManager: AuthStateManager ): AuthService { return AuthService(application, authorizationService, authStateManager) } @Provides @Singleton fun provideAuthStateManager(authorizationDao: AuthorizationDao): AuthStateManager { return AuthStateManager(authorizationDao) } @Provides @Singleton fun provideAuthorizationService(application: Application): AuthorizationService { return AuthorizationService(application) } @Provides @Singleton fun provideAuthAuthenticator( authService: AuthorizationService, authStateManager: AuthStateManager ): AuthAuthenticator { return AuthAuthenticator(authService, authStateManager) } @Provides @Singleton fun provideAuthInterceptor(authStateManager: AuthStateManager): AuthInterceptor { return AuthInterceptor(authStateManager) } }
MaWPhotos/src/main/java/us/mikeandwan/photos/di/AuthModule.kt
387037641
package me.mrkirby153.KirBot.command.executors.`fun` import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.EMOJI_RE import me.mrkirby153.KirBot.utils.HttpUtils import net.dv8tion.jda.api.Permission import okhttp3.Request import java.awt.Image import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import javax.imageio.ImageIO class CommandJumbo { @Command(name = "jumbo", arguments = ["<emojis:string...>"], category = CommandCategory.FUN, permissions = [Permission.MESSAGE_ATTACH_FILES]) @CommandDescription("Sends a bigger version of the given emojis") @IgnoreWhitelist fun execute(context: Context, cmdContext: CommandContext) { val emojis = cmdContext.get<String>("emojis")!! val urls = mutableListOf<String>() emojis.split(" ").forEach { e -> val matcher = EMOJI_RE.toPattern().matcher(e) if (matcher.find()) { val id = matcher.group(2) urls.add("https://discordapp.com/api/emojis/$id.png") } else { urls.add(getEmojiUrl(e)) } } var img: BufferedImage? = null urls.forEach { e -> val request = Request.Builder().url(e).build() val resp = HttpUtils.CLIENT.newCall(request).execute() val r = ImageIO.read(resp.body()?.byteStream()) if (img == null) img = r else img = joinBufferedImage(img!!, r) } val finalImg = img ?: return val os = ByteArrayOutputStream() ImageIO.write(finalImg, "png", os) val `is` = ByteArrayInputStream(os.toByteArray()) context.channel.sendFile(`is`, "emoji.png").queue { os.close() `is`.close() } } private fun getEmojiUrl(emoji: String): String { val first = String.format("%04X", emoji.codePoints().findFirst().asInt) return "https://twemoji.maxcdn.com/2/72x72/${first.toLowerCase()}.png" } private fun joinBufferedImage(img1: BufferedImage, img2: BufferedImage): BufferedImage { val offset = 5 val width = img1.width + img2.width + offset val height = Math.max(img1.height, img2.height) + offset val newImage = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) val g2 = newImage.graphics g2.drawImage(img1, 0, 0, null) g2.drawImage(img2, img1.width + offset, 0, null) g2.dispose() return newImage } fun resizeImage(img: BufferedImage, width: Int, height: Int): BufferedImage { val tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH) val dImg = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) val g2d = dImg.createGraphics() g2d.drawImage(tmp, 0, 0, null) g2d.dispose() return dImg } }
src/main/kotlin/me/mrkirby153/KirBot/command/executors/fun/CommandJumbo.kt
797853490
package org.stt.command import org.antlr.v4.runtime.tree.RuleNode import org.stt.grammar.EnglishCommandsBaseVisitor import org.stt.grammar.EnglishCommandsParser import org.stt.grammar.EnglishCommandsParser.CommandContext import org.stt.model.TimeTrackingItem import java.time.Duration import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeParseException import java.time.temporal.TemporalQueries class CommandTextParser(private val formatters: List<DateTimeFormatter>) { private val parserVisitor = MyEnglishCommandsBaseVisitor() internal fun walk(commandContext: CommandContext): Any { return commandContext.accept(parserVisitor) } private inner class MyEnglishCommandsBaseVisitor : EnglishCommandsBaseVisitor<Any>() { override fun visitDate(ctx: EnglishCommandsParser.DateContext): LocalDate { ctx.text return LocalDate.parse(ctx.text) } override fun visitDateTime(ctx: EnglishCommandsParser.DateTimeContext): LocalDateTime { val temporalAccessor = formatters .mapNotNull { formatter -> try { return@mapNotNull formatter.parse(ctx.text) } catch (e: DateTimeParseException) { return@mapNotNull null } } .firstOrNull() ?: throw DateTimeParseException("Invalid date format", ctx.text, 0) val date = temporalAccessor.query(TemporalQueries.localDate()) val time = temporalAccessor.query(TemporalQueries.localTime()) return LocalDateTime.of(date ?: LocalDate.now(), time) } override fun visitSinceFormat(ctx: EnglishCommandsParser.SinceFormatContext): Array<LocalDateTime?> { return arrayOf(visitDateTime(ctx.start), if (ctx.end != null) visitDateTime(ctx.end) else null) } override fun visitResumeLastCommand(ctx: EnglishCommandsParser.ResumeLastCommandContext): Any { return ResumeLastActivity(LocalDateTime.now()) } override fun visitAgoFormat(ctx: EnglishCommandsParser.AgoFormatContext): Array<LocalDateTime?> { val amount = ctx.amount val timeUnit = ctx.timeUnit() val duration = when { timeUnit.HOURS() != null -> Duration.ofHours(amount.toLong()) timeUnit.MINUTES() != null -> Duration.ofMinutes(amount.toLong()) timeUnit.SECONDS() != null -> Duration.ofSeconds(amount.toLong()) else -> throw IllegalStateException("Unknown ago unit: " + ctx.text) } return arrayOf(LocalDateTime.now().minus(duration), null) } override fun visitFromToFormat(ctx: EnglishCommandsParser.FromToFormatContext): Array<LocalDateTime?> { val start = visitDateTime(ctx.start) val end = if (ctx.end != null) visitDateTime(ctx.end) else null return arrayOf(start, end) } override fun visitTimeFormat(ctx: EnglishCommandsParser.TimeFormatContext): Array<LocalDateTime?> { return super.visitTimeFormat(ctx) as? Array<LocalDateTime?> ?: return arrayOf(LocalDateTime.now(), null) } override fun visitItemWithComment(ctx: EnglishCommandsParser.ItemWithCommentContext): Any { val period = visitTimeFormat(ctx.timeFormat()) return if (period[1] != null) { TimeTrackingItem(ctx.text, period[0]!!, period[1]) } else { TimeTrackingItem(ctx.text, period[0]!!) } } override fun visitFinCommand(ctx: EnglishCommandsParser.FinCommandContext): LocalDateTime { return if (ctx.at != null) { visitDateTime(ctx.at) } else LocalDateTime.now() } override fun shouldVisitNextChild(node: RuleNode?, currentResult: Any?): Boolean { return currentResult == null } } }
src/main/kotlin/org/stt/command/CommandTextParser.kt
2153244351
package wu.seal.jsontokotlin.utils val KOTLIN_KEYWORD_LIST = listOf( "as", "as?", "break", "class", "continue", "do", "else", "false", "for", "fun", "if", "in", "!in", "interface", "is", "!is", "null", "object", "package", "return", "super", "this", "throw", "true", "try", "typealias", "val", "var", "when", "while", "by", "catch", "constructor", "delegate", "dynamic", "field", "file", "finally", "get", "import", "init", "param", "property", "receiver", "set", "setparam", "where", "actual", "abstract", "annotation", "companion", "const", "crossinline", "data", "enum", "expect", "external", "final", "infix", "inline", "inner", "internal", "lateinit", "noinline", "open", "operator", "out", "override", "private", "protected", "public", "reified", "sealed", "suspend", "tailrec", "vararg", "field", "it" )
src/main/kotlin/wu/seal/jsontokotlin/utils/keywordsUtil.kt
910144800
package link.kotlin.scripts.utils import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardOpenOption fun writeFile(path: String, data: String) { Files.write( Paths.get(path), data.toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ) } fun writeFile(path: Path, data: String) { Files.write( path, data.toByteArray(), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING ) }
src/main/kotlin/link/kotlin/scripts/utils/Fs.kt
1754692955
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions class UnwrapToTryIntentionTest : RsIntentionTestBase(UnwrapToTryIntention()) { fun testAvailable1() = doAvailableTest(""" fn main() { let a = a.unwrap/*caret*/(); } """, """ fn main() { let a = a?; } """) fun testAvailable2() = doAvailableTest(""" fn main() { let a = Ok(12).unwrap/*caret*/(); } """, """ fn main() { let a = Ok(12)?; } """) fun testAvailable3() = doAvailableTest(""" fn main() { let a = (a + b).unwrap/*caret*/(); } """, """ fn main() { let a = (a + b)?; } """) fun testAvailable4() = doAvailableTest(""" fn main() { let a = a + b.unwrap/*caret*/(); } """, """ fn main() { let a = a + b?; } """) fun testAvailable5() = doAvailableTest(""" fn main() { let a = a.unwrap/*caret*/().to_string(); } """, """ fn main() { let a = a?.to_string(); } """) fun testAvailable6() = doAvailableTest(""" fn main() { let a = a.unwrap().unwrap/*caret*/().unwrap(); } """, """ fn main() { let a = a.unwrap()?.unwrap(); } """) fun testAvailable7() = doAvailableTest(""" fn main() { let a = a.unwrap /*caret*/ (); } """, """ fn main() { let a = a?; } """) fun testAvailable8() = doAvailableTest(""" fn main() { let a = a.unwrap(b.unwrap(/*caret*/)); } """, """ fn main() { let a = a.unwrap(b?); } """) fun testUnavailable1() = doUnavailableTest(""" fn main() { let a = a.foo/*caret*/(); } """) fun testUnavailable2() = doUnavailableTest(""" fn main() { let a = a.unwrap::<>/*caret*/(); } """) fun testUnavailable3() = doUnavailableTest(""" fn main() { let a = a.unwrap::<i32>/*caret*/(); } """) fun testUnavailable4() = doUnavailableTest(""" fn main() { let a = a.unwrap/*caret*/(12); } """) fun testUnavailable5() = doUnavailableTest(""" fn main() { let a = a.unwrap/*caret*/; } """) }
src/test/kotlin/org/rust/ide/intentions/UnwrapToTryIntentionTest.kt
1084475110
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.core import android.content.Context import android.content.Intent /** A default implementation of [IntentCreator]. */ open class IntentCreatorImpl(private val context: Context) : IntentCreator { override fun create(cls: Class<*>) = Intent(context, cls) override fun create(action: String) = Intent(action) }
android/libraries/rib-android/src/main/kotlin/com/uber/rib/core/IntentCreatorImpl.kt
2663518353
package io.gitlab.arturbosch.detekt.cli.console import io.gitlab.arturbosch.detekt.api.Detektion import io.gitlab.arturbosch.detekt.api.PREFIX import io.gitlab.arturbosch.detekt.api.format internal class ComplexityReportGenerator(private val complexityMetric: ComplexityMetric) { private var numberOfSmells = 0 private var smellPerThousandLines = 0 private var mccPerThousandLines = 0 private var commentSourceRatio = 0 companion object Factory { fun create(detektion: Detektion): ComplexityReportGenerator = ComplexityReportGenerator(ComplexityMetric(detektion)) } fun generate(): String? { if (cannotGenerate()) return null return with(StringBuilder()) { append("Complexity Report:".format()) append("${complexityMetric.loc} lines of code (loc)".format(PREFIX)) append("${complexityMetric.sloc} source lines of code (sloc)".format(PREFIX)) append("${complexityMetric.lloc} logical lines of code (lloc)".format(PREFIX)) append("${complexityMetric.cloc} comment lines of code (cloc)".format(PREFIX)) append("${complexityMetric.mcc} McCabe complexity (mcc)".format(PREFIX)) append("$numberOfSmells number of total code smells".format(PREFIX)) append("$commentSourceRatio % comment source ratio".format(PREFIX)) append("$mccPerThousandLines mcc per 1000 lloc".format(PREFIX)) append("$smellPerThousandLines code smells per 1000 lloc".format(PREFIX)) toString() } } private fun cannotGenerate(): Boolean { return when { complexityMetric.mcc == null -> true complexityMetric.lloc == null || complexityMetric.lloc == 0 -> true complexityMetric.sloc == null || complexityMetric.sloc == 0 -> true complexityMetric.cloc == null -> true else -> { numberOfSmells = complexityMetric.findings.sumBy { it.value.size } smellPerThousandLines = numberOfSmells * 1000 / complexityMetric.lloc mccPerThousandLines = complexityMetric.mcc * 1000 / complexityMetric.lloc commentSourceRatio = complexityMetric.cloc * 100 / complexityMetric.sloc false } } } }
detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/console/ComplexityReportGenerator.kt
612786189
package com.avast.mff.lecture2 import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.Toast import com.google.android.material.textfield.TextInputLayout class MainActivity : AppCompatActivity() { lateinit var btnSubmit: Button lateinit var etUsername: TextInputLayout lateinit var etPassword: TextInputLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Manual view binding btnSubmit = findViewById(R.id.btn_submit) etUsername = findViewById(R.id.txt_username) etPassword = findViewById(R.id.txt_password) /** * Restore the UI state after configuration change. */ savedInstanceState?.let { etUsername.editText?.setText(it.getString(KEY_USERNAME, "")) etPassword.editText?.setText(it.getString(KEY_PASS, "")) } btnSubmit.setOnClickListener { Toast.makeText(this, R.string.txt_sample_toast, Toast.LENGTH_LONG).show() // Pass values to the secondary activity. val intent = Intent(this, SecondActivity::class.java).apply { putExtra(KEY_USERNAME, etUsername.editText?.text.toString()) putExtra(KEY_PASS, etPassword.editText?.text.toString()) } startActivity(intent) } } /** * Save UI state for configuration changes. */ override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putString(KEY_USERNAME, etUsername.editText?.text.toString()) outState.putString(KEY_PASS, etPassword.editText?.text.toString()) } companion object { const val KEY_USERNAME = "username" const val KEY_PASS = "pass" } }
Lecture 2/Demo-app/app/src/main/java/com/avast/mff/lecture2/MainActivity.kt
3513719335
package cases @Suppress("unused") data class ValidDataClass(val i: Int) @Suppress("unused") data class DataClassWithFunctions(val i: Int) { // reports 2 fun f1() { println() } fun f2() { println() } } @Suppress("unused") data class DataClassWithOverriddenMethods(val i: Int) { override fun hashCode(): Int { return super.hashCode() } override fun equals(other: Any?): Boolean { return super.equals(other) } override fun toString(): String { return super.toString() } } @Suppress("unused") class ClassWithRegularFunctions { fun f1() { println() } fun f2() { println() } }
detekt-rules/src/test/resources/cases/DataClassContainsFunctions.kt
3051685185
package org.chapper.chapper.data.model import android.text.format.DateUtils import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.annotation.Unique import com.raizlabs.android.dbflow.structure.BaseModel import org.chapper.chapper.data.database.AppDatabase import org.chapper.chapper.data.status.MessageStatus import org.chapper.chapper.domain.usecase.DateUseCase import java.text.SimpleDateFormat import java.util.* @Table(database = AppDatabase::class) data class Message( @PrimaryKey @Unique var id: String = UUID.randomUUID().toString(), @Column var chatId: String = "", @Column var status: MessageStatus = MessageStatus.INCOMING_UNREAD, @Column var text: String = "", @Column var date: Date = Date() ) : BaseModel() { fun getTimeString(): String = when { DateUtils.isToday(date.time) -> SimpleDateFormat("HH:mm").format(date) DateUseCase.isDateInCurrentWeek(date) -> SimpleDateFormat("EEE").format(date) else -> SimpleDateFormat("MMM d").format(date) } fun isMine(): Boolean { return (status == MessageStatus.OUTGOING_READ || status == MessageStatus.OUTGOING_UNREAD || status == MessageStatus.OUTGOING_NOT_SENT) } fun isAction(): Boolean = status == MessageStatus.ACTION }
app/src/main/java/org/chapper/chapper/data/model/Message.kt
3901259495
package com.zsemberidaniel.egerbuszuj.adapters import android.support.v4.content.res.ResourcesCompat import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.zsemberidaniel.egerbuszuj.R import com.zsemberidaniel.egerbuszuj.realm.objects.Stop import java.util.ArrayList import java.util.Collections import java.util.HashMap import java.util.HashSet import java.util.TreeSet import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractHeaderItem import eu.davidea.flexibleadapter.items.AbstractSectionableItem import eu.davidea.flexibleadapter.items.IFilterable import eu.davidea.viewholders.FlexibleViewHolder import io.realm.Realm /** * Created by zsemberi.daniel on 2017. 05. 12.. */ class ChooseStopAdapter(val items: MutableList<ChooseStopAdapter.ChooseStopItem>) : FlexibleAdapter<ChooseStopAdapter.ChooseStopItem>(ArrayList(items)) { private var filter: String = "" /** * Updates the starred attribute of the ChooseStopItems, sorts them, then updates the display as well * If it is filtered it will remove the filter and update the whole data set */ private fun updateAndSortDataSet() { // remove filter because this function will take the whole list from the constructor into consideration if (isFiltered) { searchText = "" } // Update starred val realm = Realm.getDefaultInstance() for (i in items.indices) items[i].isStarred = realm.where<Stop>(Stop::class.java).equalTo(Stop.CN_ID, items[i].stopId) .findFirst().isStarred realm.close() // sort Collections.sort(items) // update display setNotifyMoveOfFilteredItems(true) super.updateDataSet(ArrayList(items), true) } override fun clear() { super.clear() items.clear() } override fun addItem(item: ChooseStopItem): Boolean { items.add(item) return super.addItem(item) } override fun addItem(position: Int, item: ChooseStopItem): Boolean { items.add(0, item) return super.addItem(position, item) } override fun addItems(position: Int, items: MutableList<ChooseStopItem>): Boolean { this.items.addAll(0, items) return super.addItems(position, items) } /** * @return Is the FlexibleAdapter filtered in any way? */ val isFiltered: Boolean get() = filter != "" override fun setSearchText(searchText: String) { this.filter = searchText super.setSearchText(searchText) } override fun onPostFilter() { super.onPostFilter() // update and sort the data set in case the user starred a stop if (filter == "") updateAndSortDataSet() } class ChooseStopItem(private val letterHeader: ChooseStopHeader, private val starredHeader: ChooseStopHeader, val stopId: String, val stopName: String, starred: Boolean) : AbstractSectionableItem<ChooseStopItem.ChooseStopItemViewHolder, ChooseStopHeader>(if (starred) starredHeader else letterHeader), IFilterable, Comparable<ChooseStopItem> { var isStarred: Boolean = false internal set init { this.isStarred = starred } override fun equals(`object`: Any?): Boolean = if (`object` is ChooseStopItem) `object`.stopId == stopId else false override fun hashCode(): Int = stopId.hashCode() override fun getLayoutRes(): Int = R.layout.stop_list_item override fun createViewHolder(adapter: FlexibleAdapter<*>, inflater: LayoutInflater?, parent: ViewGroup?): ChooseStopItemViewHolder = ChooseStopItemViewHolder(inflater!!.inflate(layoutRes, parent, false), adapter) override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: ChooseStopItemViewHolder, position: Int, payloads: List<*>) { holder.stopNameTextView.text = stopName setStarredImageCorrectly(holder) // setup on click listener for the starred image holder.starredImageView.setOnClickListener { // Toggle starred in database Realm.getDefaultInstance().executeTransaction { realm -> val stop = realm.where<Stop>(Stop::class.java).equalTo(Stop.CN_ID, stopId).findFirst() isStarred = if (isStarred) false else true stop.isStarred = isStarred } // update display setStarredImageCorrectly(holder) if (isStarred) setHeader(starredHeader) else setHeader(letterHeader) // only update and sort the data set if it is not filtered because if it is filtered // it updates it in a way which displays all of the data if (adapter is ChooseStopAdapter && !adapter.isFiltered) adapter.updateAndSortDataSet() } } override fun filter(constraint: String): Boolean { return stopName.toLowerCase().contains(constraint.toLowerCase()) } /** * Sets the starred image of the given viewHolder correctly based on this class' starred * boolean. It gets the drawable from ResourceCompat * @param viewHolder */ private fun setStarredImageCorrectly(viewHolder: ChooseStopItemViewHolder) { if (isStarred) { viewHolder.starredImageView.setImageDrawable( ResourcesCompat.getDrawable(viewHolder.starredImageView.resources, R.drawable.ic_star, null) ) } else { viewHolder.starredImageView.setImageDrawable( ResourcesCompat.getDrawable(viewHolder.starredImageView.resources, R.drawable.ic_star_border, null) ) } } override fun compareTo(o: ChooseStopItem): Int { if (o.isStarred && !isStarred) return 1 if (isStarred && !o.isStarred) return -1 return -o.stopName.compareTo(stopName) } class ChooseStopItemViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, false) { var stopNameTextView: TextView = view.findViewById(R.id.stopNameText) as TextView var starredImageView: ImageView = view.findViewById(R.id.starredImgView) as ImageView } } class ChooseStopHeader(private val letter: Char) : AbstractHeaderItem<ChooseStopHeader.ChooseStopHeaderViewHolder>() { override fun equals(o: Any?): Boolean = if (o is ChooseStopHeader) o.letter == letter else false override fun hashCode(): Int = letter.toString().hashCode() override fun getLayoutRes(): Int = R.layout.letter_item_header override fun createViewHolder(adapter: FlexibleAdapter<*>, inflater: LayoutInflater, parent: ViewGroup): ChooseStopHeaderViewHolder = ChooseStopHeaderViewHolder(inflater.inflate(layoutRes, parent, false), adapter) override fun bindViewHolder(adapter: FlexibleAdapter<*>?, holder: ChooseStopHeaderViewHolder, position: Int, payloads: List<*>) { holder.letterTextView.text = letter.toString() } class ChooseStopHeaderViewHolder(view: View, adapter: FlexibleAdapter<*>) : FlexibleViewHolder(view, adapter, true) { val letterTextView: TextView = view.findViewById(R.id.letterTextView) as TextView } } }
app/src/main/java/com/zsemberidaniel/egerbuszuj/adapters/ChooseStopAdapter.kt
127153339
package com.christianbahl.swapico.dagger import com.christianbahl.swapico.AppModule import com.christianbahl.swapico.api.SwapiApi import dagger.Component import javax.inject.Singleton /** * @author Christian Bahl */ @Singleton @Component(modules = arrayOf(AppModule::class)) interface NetComponent { fun swapiApi(): SwapiApi }
app/src/main/java/com/christianbahl/swapico/dagger/NetComponent.kt
4032598972
package me.sweetll.tucao.business.download import android.content.Context import android.content.Intent import androidx.databinding.DataBindingUtil import android.os.Bundle import androidx.appcompat.widget.Toolbar import android.view.View import me.sweetll.tucao.R import me.sweetll.tucao.base.BaseActivity import me.sweetll.tucao.databinding.ActivityDownloadSettingBinding class DownloadSettingActivity: BaseActivity() { lateinit var binding: ActivityDownloadSettingBinding override fun getToolbar(): Toolbar = binding.toolbar override fun getStatusBar(): View = binding.statusBar override fun initView(savedInstanceState: Bundle?) { binding = DataBindingUtil.setContentView(this, R.layout.activity_download_setting) fragmentManager.beginTransaction() .replace(R.id.contentFrame, DownloadSettingFragment()) .commit() } companion object { fun intentTo(context: Context) { val intent = Intent(context, DownloadSettingActivity::class.java) context.startActivity(intent) } } override fun initToolbar() { super.initToolbar() delegate.supportActionBar?.let { it.title = "离线设置" it.setDisplayHomeAsUpEnabled(true) } } }
app/src/main/kotlin/me/sweetll/tucao/business/download/DownloadSettingActivity.kt
4224921829
package com.christianbahl.swapico.details import android.os.Bundle import android.support.v4.widget.NestedScrollView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import com.christianbahl.swapico.App import com.christianbahl.swapico.R import com.christianbahl.swapico.list.DaggerTypeComponent import com.christianbahl.swapico.list.TypeComponent import com.christianbahl.swapico.list.TypeModule import com.christianbahl.swapico.list.model.ListType import com.christianbahl.swapico.model.IListData import com.hannesdorfmann.fragmentargs.annotation.Arg import com.hannesdorfmann.fragmentargs.annotation.FragmentWithArgs import com.hannesdorfmann.mosby.mvp.viewstate.lce.LceViewState import com.hannesdorfmann.mosby.mvp.viewstate.lce.MvpLceViewStateFragment import com.hannesdorfmann.mosby.mvp.viewstate.lce.data.RetainingLceViewState import kotlinx.android.synthetic.main.fragment_details.* import org.jetbrains.anko.find /** * @author Christian Bahl */ @FragmentWithArgs class DetailsFragment : MvpLceViewStateFragment<NestedScrollView, IListData, DetailsView, DetailsPresenter>() { @Arg var detailsId = 1 @Arg lateinit var listType: ListType lateinit private var typeComponent: TypeComponent private var data: IListData? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true DetailsFragmentBuilder.injectArguments(this) val app = activity.applicationContext as App typeComponent = DaggerTypeComponent.builder() .typeModule(TypeModule(listType)) .netComponent(app.netComponent()).build() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_details, container, false) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) toolbar.navigationIcon = resources.getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha, null) toolbar.setNavigationOnClickListener { activity.onBackPressed() } } override fun getErrorMessage(e: Throwable?, pullToRefresh: Boolean): String? = getString(R.string.cb_error_view_text) override fun createViewState(): LceViewState<IListData, DetailsView>? = RetainingLceViewState() override fun createPresenter(): DetailsPresenter? = typeComponent.detailsPresenter() override fun getData(): IListData? = data override fun loadData(pullToRefresh: Boolean) { presenter.loadData(detailsId, listType, pullToRefresh) } override fun setData(data: IListData?) { this.data = data buildLayout(data?.displayData) } private fun buildLayout(layoutData: Map<String, String>?) { val inflater = LayoutInflater.from(activity) layoutData?.forEach { if (it.key === "Opening Crawl") { toolbarText.text = it.value } else if (it.key === "Title") { toolbar.title = it.value } else { var ll = inflater.inflate(R.layout.row_key_value, scrollViewContainer, false) as LinearLayout ll.find<TextView>(R.id.key).text = it.key ll.find<TextView>(R.id.value).text = it.value scrollViewContainer.addView(ll) } } } }
app/src/main/java/com/christianbahl/swapico/details/DetailsFragment.kt
2401220369
package com.lbbento.pitchupapp.main import com.lbbento.pitchupcore.TuningStatus data class TunerViewModel(val note: String, val tuningStatus: TuningStatus, val expectedFrequency: Double, val diffFrequency: Double, val diffInCents: Double)
app/src/main/kotlin/com/lbbento/pitchupapp/main/TunerViewModel.kt
2493862841
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.data.observers import androidx.paging.ExperimentalPagingApi import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import javax.inject.Inject import kotlinx.coroutines.flow.Flow import tm.alashow.data.PaginatedEntryRemoteMediator import tm.alashow.data.PagingInteractor import tm.alashow.data.db.PaginatedEntryDao import tm.alashow.datmusic.data.interactors.SearchDatmusic import tm.alashow.datmusic.data.repos.search.DatmusicSearchParams import tm.alashow.domain.models.PaginatedEntity @OptIn(ExperimentalPagingApi::class) class ObservePagedDatmusicSearch<T : PaginatedEntity> @Inject constructor( private val searchDatmusic: SearchDatmusic<T>, private val dao: PaginatedEntryDao<DatmusicSearchParams, T> ) : PagingInteractor<ObservePagedDatmusicSearch.Params<T>, T>() { override fun createObservable( params: Params<T> ): Flow<PagingData<T>> { return Pager( config = params.pagingConfig, remoteMediator = PaginatedEntryRemoteMediator { page, refreshing -> try { searchDatmusic.executeSync( SearchDatmusic.Params(searchParams = params.searchParams.copy(page = page), forceRefresh = refreshing) ) } catch (error: Exception) { onError(error) throw error } }, pagingSourceFactory = { dao.entriesPagingSource(params.searchParams) } ).flow } data class Params<T : PaginatedEntity>( val searchParams: DatmusicSearchParams, override val pagingConfig: PagingConfig = DEFAULT_PAGING_CONFIG, ) : Parameters<T> }
modules/data/src/main/java/tm/alashow/datmusic/data/observers/ObservePagedDatmusicSearch.kt
3317044888
package lt.vilnius.tvarkau.entity import android.arch.persistence.room.ColumnInfo import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Entity( tableName = "report_statuses" ) @Parcelize data class ReportStatus( @PrimaryKey @ColumnInfo(name = "id") val id: Int, @ColumnInfo(name = "title") val title: String, @ColumnInfo(name = "color") val color: String ) : Parcelable
app/src/main/java/lt/vilnius/tvarkau/entity/ReportStatus.kt
3256557491
package im.fdx.v2ex.utils import org.junit.Test import java.text.SimpleDateFormat import java.util.* @Suppress("UNUSED_VARIABLE") /** * Created by fdx on 2017/7/16. * fdx will maintain it */ class TimeUtilTest { @Test fun toLong() { val ccc = SimpleDateFormat("yyyy-MM-dd hh:mm:ss a", Locale.US) val date = ccc.parse("2014-08-08 08:56:06 AM") } }
app/src/testDebug/java/im/fdx/v2ex/utils/TimeUtilTest.kt
907089937
package de.westnordost.streetcomplete.settings.questselection import de.westnordost.streetcomplete.data.quest.QuestType import de.westnordost.streetcomplete.data.osmnotes.notequests.OsmNoteQuestType data class QuestVisibility(val questType: QuestType<*>, var visible: Boolean) { val isInteractionEnabled get() = questType !is OsmNoteQuestType }
app/src/main/java/de/westnordost/streetcomplete/settings/questselection/QuestVisibility.kt
904675932
package de.westnordost.streetcomplete.data.osmnotes.edits import de.westnordost.streetcomplete.testutils.* import de.westnordost.streetcomplete.testutils.any import org.junit.Before import org.junit.Test import org.mockito.ArgumentMatchers.anyLong import org.mockito.Mockito.verify import org.mockito.Mockito.never class NoteEditsControllerTest { private lateinit var ctrl: NoteEditsController private lateinit var db: NoteEditsDao private lateinit var listener: NoteEditsSource.Listener @Before fun setUp() { db = mock() on(db.delete(anyLong())).thenReturn(true) on(db.markSynced(anyLong())).thenReturn(true) listener = mock() ctrl = NoteEditsController(db) ctrl.addListener(listener) } @Test fun add() { ctrl.add(1L, NoteEditAction.COMMENT, p(1.0, 1.0)) verify(db).add(any()) verify(listener).onAddedEdit(any()) } @Test fun syncFailed() { val edit = noteEdit(noteId = 1) ctrl.markSyncFailed(edit) verify(db).delete(1) verify(listener).onDeletedEdits(eq(listOf(edit))) } @Test fun synced() { val edit = noteEdit(id = 3, noteId = 1) val note = note(1) ctrl.markSynced(edit, note) verify(db).markSynced(3) verify(db, never()).updateNoteId(anyLong(), anyLong()) verify(listener).onSyncedEdit(edit) } @Test fun `synced with new id`() { val edit = noteEdit(id = 3, noteId = -100) val note = note(123) ctrl.markSynced(edit, note) verify(db).markSynced(3) verify(db).updateNoteId(-100L, 123L) verify(listener).onSyncedEdit(edit) } }
app/src/test/java/de/westnordost/streetcomplete/data/osmnotes/edits/NoteEditsControllerTest.kt
2143545624
// Copyright 2021 [email protected] // // 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 avb.desc import cfig.helper.Helper import cfig.io.Struct3 import org.apache.commons.codec.binary.Hex import org.slf4j.LoggerFactory import java.io.ByteArrayInputStream import java.io.InputStream class UnknownDescriptor(var data: ByteArray = byteArrayOf()) : Descriptor(0, 0, 0) { @Throws(IllegalArgumentException::class) constructor(stream: InputStream, seq: Int = 0) : this() { this.sequence = seq val info = Struct3(FORMAT).unpack(stream) this.tag = (info[0] as ULong).toLong() this.num_bytes_following = (info[1] as ULong).toLong() log.debug("UnknownDescriptor: tag = $tag, len = ${this.num_bytes_following}") this.data = ByteArray(this.num_bytes_following.toInt()) if (this.num_bytes_following.toInt() != stream.read(data)) { throw IllegalArgumentException("descriptor SIZE mismatch") } } override fun encode(): ByteArray { return Helper.join(Struct3(FORMAT).pack(this.tag, this.data.size.toLong()), data) } override fun toString(): String { return "UnknownDescriptor(tag=$tag, SIZE=${data.size}, data=${Hex.encodeHexString(data)}" } fun analyze(): Descriptor { return when (this.tag.toUInt()) { 0U -> { PropertyDescriptor(ByteArrayInputStream(this.encode()), this.sequence) } 1U -> { HashTreeDescriptor(ByteArrayInputStream(this.encode()), this.sequence) } 2U -> { HashDescriptor(ByteArrayInputStream(this.encode()), this.sequence) } 3U -> { KernelCmdlineDescriptor(ByteArrayInputStream(this.encode()), this.sequence) } 4U -> { ChainPartitionDescriptor(ByteArrayInputStream(this.encode()), this.sequence) } else -> { this } } } companion object { private const val SIZE = 16 private const val FORMAT = "!QQ" private val log = LoggerFactory.getLogger(UnknownDescriptor::class.java) fun parseDescriptors(stream: InputStream, totalSize: Long): List<UnknownDescriptor> { log.debug("Parse descriptors stream, SIZE = $totalSize") val ret: MutableList<UnknownDescriptor> = mutableListOf() var currentSize = 0L while (true) { val desc = UnknownDescriptor(stream) currentSize += desc.data.size + SIZE log.debug("current SIZE = $currentSize") ret.add(desc) if (currentSize == totalSize) { log.debug("parse descriptor done") break } else if (currentSize > totalSize) { log.error("Read more than expected") throw IllegalStateException("Read more than expected") } else { log.debug(desc.toString()) log.debug("read another descriptor") } } return ret } fun parseDescriptors2(stream: InputStream, totalSize: Long): List<Descriptor> { log.debug("Parse descriptors stream, SIZE = $totalSize") val ret: MutableList<Descriptor> = mutableListOf() var currentSize = 0L var seq = 0 while (true) { val desc = UnknownDescriptor(stream, ++seq) currentSize += desc.data.size + SIZE log.debug("current SIZE = $currentSize") log.debug(desc.toString()) ret.add(desc.analyze()) if (currentSize == totalSize) { log.debug("parse descriptor done") break } else if (currentSize > totalSize) { log.error("Read more than expected") throw IllegalStateException("Read more than expected") } else { log.debug(desc.toString()) log.debug("read another descriptor") } } return ret } init { assert(SIZE == Struct3(FORMAT).calcSize()) } } }
bbootimg/src/main/kotlin/avb/desc/UnknownDescriptor.kt
2087788834
package app.youkai.ui.feature.media import android.app.AlertDialog import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.design.widget.AppBarLayout import android.support.design.widget.Snackbar import android.widget.Toast import app.youkai.R import app.youkai.data.models.BaseMedia import app.youkai.data.models.Titles import app.youkai.data.models.ext.MediaType import app.youkai.ui.feature.media.summary.SummaryFragment import app.youkai.util.ext.snackbar import app.youkai.util.ext.toVisibility import app.youkai.util.ext.whenNotNull import app.youkai.util.string import com.hannesdorfmann.mosby.mvp.viewstate.MvpViewStateActivity import com.hannesdorfmann.mosby.mvp.viewstate.ViewState import kotlinx.android.synthetic.main.activity_media.* class MediaActivity : MvpViewStateActivity<MediaView, BaseMediaPresenter>(), MediaView { override fun createPresenter(): BaseMediaPresenter = BaseMediaPresenter() override fun createViewState(): ViewState<MediaView> = MediaState() override fun onNewViewStateInstance() { /* do nothing */ } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_media) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) /* Set up title show/hide */ appbar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener { var isShow = false var scrollRange = -1 override fun onOffsetChanged(appBarLayout: AppBarLayout, verticalOffset: Int) { if (scrollRange == -1) { scrollRange = appBarLayout.totalScrollRange } if (scrollRange + verticalOffset == 0) { toolbar.setTitleTextColor(resources.getColor(android.R.color.white)) isShow = true } else if (isShow) { toolbar.setTitleTextColor(resources.getColor(android.R.color.transparent)) isShow = false } } }) var mediaId: String = "" var type = MediaType.NO_IDEA whenNotNull(intent.extras) { mediaId = it.getString(ARG_ID) type = MediaType.fromString(it.getString(ARG_TYPE)) } when (type) { MediaType.ANIME -> setPresenter(AnimePresenter()) MediaType.MANGA -> setPresenter(MangaPresenter()) } presenter.attachView(this) presenter.set(mediaId) titleView.setOnClickListener { presenter.onTitleClicked() } alternativeTitles.setOnClickListener { presenter.onAlternativeTitlesClicked() } trailer.setOnClickListener { presenter.onTrailerClicked() } fab.setOnClickListener { presenter } } override fun onSupportNavigateUp(): Boolean { finish() return true } override fun setSummary(media: BaseMedia?) { (summaryFragment as SummaryFragment).setMedia(media, onTablet()) } override fun setPoster(url: String?) { poster.setImageURI(url) } override fun setCover(url: String?) { cover.setImageURI(url) } override fun setTitle(title: String) { toolbar.title = title this.titleView.text = title } override fun setAlternativeTitlesButtonVisible(visible: Boolean) { alternativeTitles.visibility = visible.toVisibility() } override fun setTrailerButtonVisible(visible: Boolean) { trailer.visibility = visible.toVisibility() } override fun setFavorited(favorited: Boolean) { // TODO: Implement later } override fun setType(type: String) { this.type.text = type } override fun setReleaseSummary(summary: String) { releaseSummary.text = summary } override fun setAgeRating(rating: String) { ageRating.text = rating } override fun setFabIcon(res: Int) { fab.setImageResource(res) } override fun enableFab(enable: Boolean) { fab?.imageAlpha = if (!enable) { 153 // 60% } else { 255 // 100% } fab?.isEnabled = enable } override fun showFullscreenCover() { // TODO: Implement later } override fun showFullscreenPoster() { // TODO: Implement later } override fun showAlternativeTitles(titles: Titles?, abbreviatedTitles: List<String>?) { AlertDialog.Builder(this@MediaActivity) .setTitle(R.string.title_alternative_titles) .setMessage([email protected]( R.string.content_alternative_titles_message, titles?.en ?: "?", titles?.enJp ?: "?", titles?.jaJp ?: "?", abbreviatedTitles?.joinToString(", ") )) .setPositiveButton(R.string.ok, null) .show() } override fun showTrailer(videoId: String) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://youtube.com/watch?v=$videoId"))) } override fun showLibraryEdit() { /*val bottomSheetDialogFragment = EditBottomSheetFragment() bottomSheetDialogFragment.show(supportFragmentManager, bottomSheetDialogFragment.tag)*/ } override fun showToast(text: String) { Toast.makeText(this@MediaActivity, text, Toast.LENGTH_LONG).show() } override fun showErrorSnackbar(text: String, actionListener: () -> Unit) { nestedScrollView.snackbar(text, Snackbar.LENGTH_INDEFINITE) { setAction(string(R.string.retry), { actionListener() }) // setActionTextColor(color) } } override fun onTablet(): Boolean { // TODO: Real check return false } companion object { private const val ARG_ID = "id" private const val ARG_TYPE = "type" fun getLaunchIntent(context: Context, id: String?, type: MediaType): Intent { val intent = Intent(context, MediaActivity::class.java) intent.putExtra(ARG_ID, id ?: "-1") intent.putExtra(ARG_TYPE, type.toString()) return intent } } }
app/src/main/kotlin/app/youkai/ui/feature/media/MediaActivity.kt
917999039
/** * Created by [email protected] on 11/24/16. * * Copyright (c) <2016> <H, llc> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.thelandscape.krawler.crawler.History import io.thelandscape.krawler.http.KrawlUrl import java.time.LocalDateTime interface KrawlHistoryIf { /** * Inserts an entry into the history tracker * * @param url KrawlUrl: The KrawlUrl to insert * * @returns KrawlHistoryEntry that was inserted into the history store with generated ID */ fun insert(url: KrawlUrl): KrawlHistoryEntry /** * Returns true if a URL has been seen (visited or checked) during this crawl * * @param url KrawlUrl: The URL to visit * * @return true if URL HAS been visited previously, false otherwise */ fun hasBeenSeen(url: KrawlUrl): Boolean /** * Clears the Krawl history prior to the timestamp specified by beforeTime. * * @param beforeTime LocalDateTime: Timestamp before which the history should be cleared * * @return the number of history entries that were cleared */ fun clearHistory(beforeTime: LocalDateTime = LocalDateTime.now()): Int }
src/main/kotlin/io/thelandscape/krawler/crawler/History/KrawlHistory.kt
1983617630
/* * Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.jetbrains.python.inspections import com.intellij.codeInspection.LocalInspectionToolSession import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.psi.PsiElementVisitor import com.intellij.psi.PsiNameIdentifierOwner import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.PyNames import com.jetbrains.python.codeInsight.stdlib.* import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider import com.jetbrains.python.psi.* import com.jetbrains.python.psi.impl.PyCallExpressionHelper import com.jetbrains.python.psi.impl.PyEvaluator import com.jetbrains.python.psi.impl.stubs.PyDataclassFieldStubImpl import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.stubs.PyDataclassFieldStub import com.jetbrains.python.psi.types.* class PyDataclassInspection : PyInspection() { companion object { private val ORDER_OPERATORS = setOf("__lt__", "__le__", "__gt__", "__ge__") private val DATACLASSES_HELPERS = setOf("dataclasses.fields", "dataclasses.asdict", "dataclasses.astuple", "dataclasses.replace") private val ATTRS_HELPERS = setOf("attr.__init__.fields", "attr.__init__.fields_dict", "attr.__init__.asdict", "attr.__init__.astuple", "attr.__init__.assoc", "attr.__init__.evolve") } override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor = Visitor(holder, session) private class Visitor(holder: ProblemsHolder, session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) { override fun visitPyTargetExpression(node: PyTargetExpression?) { super.visitPyTargetExpression(node) if (node != null) checkMutatingFrozenAttribute(node) } override fun visitPyDelStatement(node: PyDelStatement?) { super.visitPyDelStatement(node) if (node != null) { node .targets .asSequence() .filterIsInstance<PyReferenceExpression>() .forEach { checkMutatingFrozenAttribute(it) } } } override fun visitPyClass(node: PyClass?) { super.visitPyClass(node) if (node != null) { val dataclassParameters = parseDataclassParameters(node, myTypeEvalContext) if (dataclassParameters != null) { if (dataclassParameters.type == PyDataclassParameters.Type.STD) { processDataclassParameters(node, dataclassParameters) val postInit = node.findMethodByName(DUNDER_POST_INIT, false, myTypeEvalContext) val initVars = mutableListOf<PyTargetExpression>() node.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression) { if (!PyTypingTypeProvider.isClassVar(element, myTypeEvalContext)) { processDefaultFieldValue(element) processAsInitVar(element, postInit)?.let { initVars.add(it) } } processFieldFunctionCall(element) } true } if (postInit != null) { processPostInitDefinition(postInit, dataclassParameters, initVars) } } else if (dataclassParameters.type == PyDataclassParameters.Type.ATTRS) { processAttrsParameters(node, dataclassParameters) node .findMethodByName(DUNDER_ATTRS_POST_INIT, false, myTypeEvalContext) ?.also { processAttrsPostInitDefinition(it, dataclassParameters) } processAttrsDefaultThroughDecorator(node) processAttrsInitializersAndValidators(node) processAttrsAutoAttribs(node, dataclassParameters) processAttrIbFunctionCalls(node) } PyNamedTupleInspection.inspectFieldsOrder( node, this::registerProblem, { val stub = it.stub val fieldStub = if (stub == null) PyDataclassFieldStubImpl.create(it) else stub.getCustomStub(PyDataclassFieldStub::class.java) fieldStub?.initValue() != false && !PyTypingTypeProvider.isClassVar(it, myTypeEvalContext) }, { val fieldStub = PyDataclassFieldStubImpl.create(it) if (fieldStub != null) { fieldStub.hasDefault() || fieldStub.hasDefaultFactory() || dataclassParameters.type == PyDataclassParameters.Type.ATTRS && node.methods.any { m -> m.decoratorList?.findDecorator("${it.name}.default") != null } } else { val assignedValue = it.findAssignedValue() assignedValue != null && !resolvesToOmittedDefault(assignedValue, dataclassParameters.type) } } ) } } } override fun visitPyBinaryExpression(node: PyBinaryExpression?) { super.visitPyBinaryExpression(node) if (node != null && ORDER_OPERATORS.contains(node.referencedName)) { val leftClass = getInstancePyClass(node.leftExpression) ?: return val rightClass = getInstancePyClass(node.rightExpression) ?: return val leftDataclassParameters = parseDataclassParameters(leftClass, myTypeEvalContext) if (leftClass != rightClass && leftDataclassParameters != null && parseDataclassParameters(rightClass, myTypeEvalContext) != null) { registerProblem(node.psiOperator, "'${node.referencedName}' not supported between instances of '${leftClass.name}' and '${rightClass.name}'", ProblemHighlightType.GENERIC_ERROR) } if (leftClass == rightClass && leftDataclassParameters?.order == false) { registerProblem(node.psiOperator, "'${node.referencedName}' not supported between instances of '${leftClass.name}'", ProblemHighlightType.GENERIC_ERROR) } } } override fun visitPyCallExpression(node: PyCallExpression?) { super.visitPyCallExpression(node) if (node != null) { val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(myTypeEvalContext) val markedCallee = node.multiResolveCallee(resolveContext).singleOrNull() val callee = markedCallee?.element val calleeQName = callee?.qualifiedName if (markedCallee != null && callee != null) { val dataclassType = when { DATACLASSES_HELPERS.contains(calleeQName) -> PyDataclassParameters.Type.STD ATTRS_HELPERS.contains(calleeQName) -> PyDataclassParameters.Type.ATTRS else -> return } val mapping = PyCallExpressionHelper.mapArguments(node, markedCallee, myTypeEvalContext) val dataclassParameter = callee.getParameters(myTypeEvalContext).firstOrNull() val dataclassArgument = mapping.mappedParameters.entries.firstOrNull { it.value == dataclassParameter }?.key if (dataclassType == PyDataclassParameters.Type.STD) { processHelperDataclassArgument(dataclassArgument, calleeQName!!) } else if (dataclassType == PyDataclassParameters.Type.ATTRS) { processHelperAttrsArgument(dataclassArgument, calleeQName!!) } } } } override fun visitPyReferenceExpression(node: PyReferenceExpression?) { super.visitPyReferenceExpression(node) if (node != null && node.isQualified) { val cls = getInstancePyClass(node.qualifier) ?: return if (parseStdDataclassParameters(cls, myTypeEvalContext) != null) { cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression && element.name == node.name && isInitVar(element)) { registerProblem(node.lastChild, "'${cls.name}' object could have no attribute '${element.name}' because it is declared as init-only", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) return@processClassLevelDeclarations false } true } } } } private fun checkMutatingFrozenAttribute(expression: PyQualifiedExpression) { val cls = getInstancePyClass(expression.qualifier) ?: return if (parseDataclassParameters(cls, myTypeEvalContext)?.frozen == true) { registerProblem(expression, "'${cls.name}' object attribute '${expression.name}' is read-only", ProblemHighlightType.GENERIC_ERROR) } } private fun getInstancePyClass(element: PyTypedElement?): PyClass? { val type = element?.let { myTypeEvalContext.getType(it) } as? PyClassType return if (type != null && !type.isDefinition) type.pyClass else null } private fun processDataclassParameters(cls: PyClass, dataclassParameters: PyDataclassParameters) { if (!dataclassParameters.eq && dataclassParameters.order) { registerProblem(dataclassParameters.eqArgument, "'eq' must be true if 'order' is true", ProblemHighlightType.GENERIC_ERROR) } var initMethodExists = false var reprMethodExists = false var eqMethodExists = false var orderMethodsExist = false var mutatingMethodsExist = false var hashMethodExists = false cls.methods.forEach { when (it.name) { PyNames.INIT -> initMethodExists = true "__repr__" -> reprMethodExists = true "__eq__" -> eqMethodExists = true in ORDER_OPERATORS -> orderMethodsExist = true "__setattr__", "__delattr__" -> mutatingMethodsExist = true PyNames.HASH -> hashMethodExists = true } } hashMethodExists = hashMethodExists || cls.findClassAttribute(PyNames.HASH, false, myTypeEvalContext) != null // argument to register problem, argument name and method name val useless = mutableListOf<Triple<PyExpression?, String, String>>() if (dataclassParameters.init && initMethodExists) { useless.add(Triple(dataclassParameters.initArgument, "init", PyNames.INIT)) } if (dataclassParameters.repr && reprMethodExists) { useless.add(Triple(dataclassParameters.reprArgument, "repr", "__repr__")) } if (dataclassParameters.eq && eqMethodExists) { useless.add(Triple(dataclassParameters.eqArgument, "eq", "__eq__")) } useless.forEach { registerProblem(it.first, "'${it.second}' is ignored if the class already defines '${it.third}' method", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } if (dataclassParameters.order && orderMethodsExist) { registerProblem(dataclassParameters.orderArgument, "'order' should be false if the class defines one of order methods", ProblemHighlightType.GENERIC_ERROR) } if (dataclassParameters.frozen && mutatingMethodsExist) { registerProblem(dataclassParameters.frozenArgument, "'frozen' should be false if the class defines '__setattr__' or '__delattr__'", ProblemHighlightType.GENERIC_ERROR) } if (dataclassParameters.unsafeHash && hashMethodExists) { registerProblem(dataclassParameters.unsafeHashArgument, "'unsafe_hash' should be false if the class defines '${PyNames.HASH}'", ProblemHighlightType.GENERIC_ERROR) } } private fun processAttrsParameters(cls: PyClass, dataclassParameters: PyDataclassParameters) { var initMethod: PyFunction? = null var reprMethod: PyFunction? = null var strMethod: PyFunction? = null val cmpMethods = mutableListOf<PyFunction>() val mutatingMethods = mutableListOf<PyFunction>() var hashMethod: PsiNameIdentifierOwner? = null cls.methods.forEach { when (it.name) { PyNames.INIT -> initMethod = it "__repr__" -> reprMethod = it "__str__" -> strMethod = it "__eq__", in ORDER_OPERATORS -> cmpMethods.add(it) "__setattr__", "__delattr__" -> mutatingMethods.add(it) PyNames.HASH -> hashMethod = it } } hashMethod = hashMethod ?: cls.findClassAttribute(PyNames.HASH, false, myTypeEvalContext) // element to register problem and corresponding attr.s parameter val problems = mutableListOf<Pair<PsiNameIdentifierOwner?, String>>() if (dataclassParameters.init && initMethod != null) { problems.add(initMethod to "init") } if (dataclassParameters.repr && reprMethod != null) { problems.add(reprMethod to "repr") } if (PyEvaluator.evaluateAsBoolean(PyUtil.peelArgument(dataclassParameters.others["str"]), false) && strMethod != null) { problems.add(strMethod to "str") } if (dataclassParameters.order && cmpMethods.isNotEmpty()) { cmpMethods.forEach { problems.add(it to "cmp") } } if (dataclassParameters.frozen && mutatingMethods.isNotEmpty()) { mutatingMethods.forEach { problems.add(it to "frozen") } } if (dataclassParameters.unsafeHash && hashMethod != null) { problems.add(hashMethod to "hash") } problems.forEach { it.first?.apply { registerProblem(nameIdentifier, "'$name' is ignored if the class already defines '${it.second}' parameter", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } } if (dataclassParameters.order && dataclassParameters.frozen && hashMethod != null) { registerProblem(hashMethod?.nameIdentifier, "'${PyNames.HASH}' is ignored if the class already defines 'cmp' and 'frozen' parameters", ProblemHighlightType.GENERIC_ERROR_OR_WARNING) } } private fun processDefaultFieldValue(field: PyTargetExpression) { if (field.annotationValue == null) return val value = field.findAssignedValue() if (PyUtil.isForbiddenMutableDefault(value, myTypeEvalContext)) { registerProblem(value, "Mutable default '${value?.text}' is not allowed. Use 'default_factory'", ProblemHighlightType.GENERIC_ERROR) } } private fun processAttrsDefaultThroughDecorator(cls: PyClass) { val initializers = mutableMapOf<String, MutableList<PyFunction>>() cls.methods.forEach { method -> val decorators = method.decoratorList?.decorators if (decorators != null) { decorators .asSequence() .mapNotNull { it.qualifiedName } .filter { it.componentCount == 2 && it.endsWith("default") } .mapNotNull { it.firstComponent } .firstOrNull() ?.also { name -> val attribute = cls.findClassAttribute(name, false, myTypeEvalContext) if (attribute != null) { initializers.computeIfAbsent(name, { _ -> mutableListOf() }).add(method) val stub = PyDataclassFieldStubImpl.create(attribute) if (stub != null && (stub.hasDefault() || stub.hasDefaultFactory())) { registerProblem(method.nameIdentifier, "A default is set using 'attr.ib()'", ProblemHighlightType.GENERIC_ERROR) } } } } } initializers.values.forEach { sameAttrInitializers -> val first = sameAttrInitializers[0] sameAttrInitializers .asSequence() .drop(1) .forEach { registerProblem(it.nameIdentifier, "A default is set using '${first.name}'", ProblemHighlightType.GENERIC_ERROR) } } } private fun processAttrsInitializersAndValidators(cls: PyClass) { cls.visitMethods( { method -> val decorators = method.decoratorList?.decorators if (decorators != null) { decorators .asSequence() .mapNotNull { it.qualifiedName } .filter { it.componentCount == 2 } .mapNotNull { it.lastComponent } .forEach { val expectedParameters = when (it) { "default" -> 1 "validator" -> 3 else -> return@forEach } val actualParameters = method.parameterList if (actualParameters.parameters.size != expectedParameters) { val message = "'${method.name}' should take only $expectedParameters parameter" + if (expectedParameters > 1) "s" else "" registerProblem(actualParameters, message, ProblemHighlightType.GENERIC_ERROR) } } } true }, false, myTypeEvalContext ) } private fun processAttrsAutoAttribs(cls: PyClass, dataclassParameters: PyDataclassParameters) { if (PyEvaluator.evaluateAsBoolean(PyUtil.peelArgument(dataclassParameters.others["auto_attribs"]), false)) { cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression && element.annotation == null && PyDataclassFieldStubImpl.create(element) != null) { registerProblem(element, "Attribute '${element.name}' lacks a type annotation", ProblemHighlightType.GENERIC_ERROR) } true } } } private fun processAttrIbFunctionCalls(cls: PyClass) { cls.processClassLevelDeclarations { element, _ -> if (element is PyTargetExpression) { val call = element.findAssignedValue() as? PyCallExpression val stub = PyDataclassFieldStubImpl.create(element) if (call != null && stub != null) { if (stub.hasDefaultFactory()) { if (stub.hasDefault()) { registerProblem(call.argumentList, "Cannot specify both 'default' and 'factory'", ProblemHighlightType.GENERIC_ERROR) } else { // at least covers the following case: `attr.ib(default=attr.Factory(...), factory=...)` val default = call.getKeywordArgument("default") val factory = call.getKeywordArgument("factory") if (default != null && factory != null && !resolvesToOmittedDefault(default, PyDataclassParameters.Type.ATTRS)) { registerProblem(call.argumentList, "Cannot specify both 'default' and 'factory'", ProblemHighlightType.GENERIC_ERROR) } } } } } true } } private fun processAsInitVar(field: PyTargetExpression, postInit: PyFunction?): PyTargetExpression? { if (isInitVar(field)) { if (postInit == null) { registerProblem(field, "Attribute '${field.name}' is useless until '$DUNDER_POST_INIT' is declared", ProblemHighlightType.LIKE_UNUSED_SYMBOL) } return field } return null } private fun processFieldFunctionCall(field: PyTargetExpression) { val fieldStub = PyDataclassFieldStubImpl.create(field) ?: return val call = field.findAssignedValue() as? PyCallExpression ?: return if (PyTypingTypeProvider.isClassVar(field, myTypeEvalContext) || isInitVar(field)) { if (fieldStub.hasDefaultFactory()) { registerProblem(call.getKeywordArgument("default_factory"), "Field cannot have a default factory", ProblemHighlightType.GENERIC_ERROR) } } else if (fieldStub.hasDefault() && fieldStub.hasDefaultFactory()) { registerProblem(call.argumentList, "Cannot specify both 'default' and 'default_factory'", ProblemHighlightType.GENERIC_ERROR) } } private fun processPostInitDefinition(postInit: PyFunction, dataclassParameters: PyDataclassParameters, initVars: List<PyTargetExpression>) { if (!dataclassParameters.init) { registerProblem(postInit.nameIdentifier, "'$DUNDER_POST_INIT' would not be called until 'init' parameter is set to True", ProblemHighlightType.LIKE_UNUSED_SYMBOL) } val implicitParameters = postInit.getParameters(myTypeEvalContext) val parameters = if (implicitParameters.isEmpty()) emptyList<PyCallableParameter>() else ContainerUtil.subList(implicitParameters, 1) val message = "'$DUNDER_POST_INIT' should take all init-only variables in the same order as they are defined" if (parameters.size != initVars.size) { registerProblem(postInit.parameterList, message, ProblemHighlightType.GENERIC_ERROR) } else { parameters .asSequence() .zip(initVars.asSequence()) .all { it.first.name == it.second.name } .also { if (!it) registerProblem(postInit.parameterList, message) } } } private fun processAttrsPostInitDefinition(postInit: PyFunction, dataclassParameters: PyDataclassParameters) { if (!dataclassParameters.init) { registerProblem(postInit.nameIdentifier, "'$DUNDER_ATTRS_POST_INIT' would not be called until 'init' parameter is set to True", ProblemHighlightType.LIKE_UNUSED_SYMBOL) } if (postInit.getParameters(myTypeEvalContext).size != 1) { registerProblem(postInit.parameterList, "'$DUNDER_ATTRS_POST_INIT' should not take any parameters except '${PyNames.CANONICAL_SELF}'", ProblemHighlightType.GENERIC_ERROR) } } private fun processHelperDataclassArgument(argument: PyExpression?, calleeQName: String) { if (argument == null) return val allowDefinition = calleeQName == "dataclasses.fields" if (isNotExpectedDataclass(myTypeEvalContext.getType(argument), PyDataclassParameters.Type.STD, allowDefinition, true)) { val message = "'$calleeQName' method should be called on dataclass instances" + if (allowDefinition) " or types" else "" registerProblem(argument, message) } } private fun processHelperAttrsArgument(argument: PyExpression?, calleeQName: String) { if (argument == null) return val instance = calleeQName != "attr.__init__.fields" && calleeQName != "attr.__init__.fields_dict" if (isNotExpectedDataclass(myTypeEvalContext.getType(argument), PyDataclassParameters.Type.ATTRS, !instance, instance)) { val presentableCalleeQName = calleeQName.replaceFirst(".__init__.", ".") val message = "'$presentableCalleeQName' method should be called on attrs " + if (instance) "instances" else "types" registerProblem(argument, message) } } private fun isInitVar(field: PyTargetExpression): Boolean { return (myTypeEvalContext.getType(field) as? PyClassType)?.classQName == DATACLASSES_INITVAR_TYPE } private fun isNotExpectedDataclass(type: PyType?, dataclassType: PyDataclassParameters.Type, allowDefinition: Boolean, allowInstance: Boolean): Boolean { if (type is PyStructuralType || PyTypeChecker.isUnknown(type, myTypeEvalContext)) return false if (type is PyUnionType) return type.members.all { isNotExpectedDataclass(it, dataclassType, allowDefinition, allowInstance) } return type !is PyClassType || !allowDefinition && type.isDefinition || !allowInstance && !type.isDefinition || parseDataclassParameters(type.pyClass, myTypeEvalContext)?.type != dataclassType } } }
python/src/com/jetbrains/python/inspections/PyDataclassInspection.kt
1856669257
package com.mercadopago.android.px.font import com.mercadolibre.android.ui.font.TypefaceHelper class FontConfigurator { companion object { @JvmStatic fun configure() { val sampleFontTypefaceMapper = NunitoSansFontTypefaceMapper() val sampleTypefaceSetter = SampleTypefaceSetter(sampleFontTypefaceMapper) TypefaceHelper.attachTypefaceSetter(sampleTypefaceSetter) } } }
example/src/main/java/com/mercadopago/android/px/font/FontConfigurator.kt
2933161827
/* * Copyright (c) 2016. KESTI co, ltd * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package debop4k.core.asyncs.kovenant.examples import debop4k.core.AbstractCoreKotlinTest import nl.komponents.kovenant.Kovenant import nl.komponents.kovenant.jvm.asExecutorService import org.junit.Test import java.util.concurrent.* class ExecutorsTest : AbstractCoreKotlinTest() { @Test fun customContext() { val executorService = Kovenant.context.workerContext.dispatcher.asExecutorService() val tasks = Array(5) { x -> Callable { Pair(25 - x, fib(25 - x)) } }.toList() val (n, fib) = executorService.invokeAny(tasks) log.debug("invokeAny: fib($n) = $fib") val results = executorService.invokeAll(tasks) results.forEach { future -> val (i, res) = future.get() log.debug("invokeAll: fib($i) = $res") } } }
debop4k-core/src/test/kotlin/debop4k/core/asyncs/kovenant/examples/ExecutorsTest.kt
3854058021
package net.torvald.terranvm.runtime.compiler.tbasic /** * Created by minjaesong on 2018-05-08. */ class Tbasic { private val keywords = hashSetOf<String>( "ABORT", "ABORTM", "ABS", "ASC", "BACKCOL", "BEEP", "CBRT", "CEIL", "CHR", "CLR", "CLS", "COS", "DEF FN", "DELETE", "DIM", "END", "FLOOR", "FOR", "GET", "GOSUB", "GOTO", "HTAB", "IF", "INPUT", "INT", "INV", "LABEL", "LEFT", "LEN", "LIST", "LOAD", "LOG", "MAX", "MID", "MIN", "NEW", "NEXT", "PRINT", "RAD", "REM", "RENUM", "RETURN", "RIGHT", "RND", "ROUND", "RUN", "SAVE", "SCROLL", "SGN", "SIN", "SQRT", "STR", "TAB", "TAN", "TEXTCOL", "TEMIT", "VAL", "VTAB", "PEEK", "POKE" ) private val delimeters = hashSetOf<Char>( '(',')',',',':','"',' ' ) fun tokeniseLine(line: String): LineStructure { var charIndex = 0 val sb = StringBuilder() val tokensList = ArrayList<String>() val lineNumber: Int fun appendToList(s: String) { if (s.isNotBlank()) tokensList.add(s) } if (line[0] !in '0'..'9') { throw IllegalArgumentException("Line number not prepended to this BASIC statement: $line") } // scan for the line number while (true) { if (line[charIndex] !in '0'..'9') { lineNumber = sb.toString().toInt() sb.delete(0, sb.length) charIndex++ break } sb.append(line[charIndex]) charIndex++ } // the real tokenise // --> scan until meeting numbers or delimeters while (charIndex <= line.length) { while (true) { if (charIndex == line.length || line[charIndex] in delimeters) { appendToList(sb.toString()) sb.delete(0, sb.length) charIndex++ break } sb.append(line[charIndex]) charIndex++ } } return LineStructure(lineNumber, tokensList) } data class LineStructure(var lineNum: Int, val tokens: MutableList<String>) }
src/net/torvald/terranvm/runtime/compiler/tbasic/Compiler.kt
3417740947
package six.ca.crashcases.fragment.biz import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.core.view.GravityCompat import androidx.core.view.get import androidx.core.view.iterator import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import com.google.android.material.bottomnavigation.BottomNavigationView import kotlinx.coroutines.flow.collect import kotlinx.coroutines.launch import six.ca.crashcases.R import six.ca.crashcases.databinding.ActHomeBinding import six.ca.crashcases.fragment.core.BaseActivity import six.ca.crashcases.fragment.core.TeApplication import six.ca.crashcases.fragment.data.AccountType import six.ca.crashcases.fragment.data.AppEventCenterInterface import six.ca.crashcases.fragment.data.Event import javax.inject.Inject import kotlin.random.Random /** * @author hellenxu * @date 2020-08-20 * Copyright 2020 Six. All rights reserved. */ class HomeActivity: BaseActivity(), BottomNavigationView.OnNavigationItemSelectedListener { private lateinit var homeBinding: ActHomeBinding private lateinit var homeViewModel: HomeViewModel private lateinit var contentAdapter: ContentAdapter private val tabs: MutableList<String> = mutableListOf() @set:Inject internal lateinit var vmFactory: ViewModelProvider.Factory @set:Inject internal lateinit var appEventCenter: AppEventCenterInterface override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) TeApplication.instance.appComponent.inject(this) homeBinding = ActHomeBinding.inflate(layoutInflater) setContentView(homeBinding.root) initViews() initViewModel() } override fun onResume() { super.onResume() } override fun onPause() { super.onPause() } override fun onStop() { super.onStop() appEventCenter.reset() } override fun onDestroy() { super.onDestroy() } private fun initViews() { homeBinding.contentVp2.isUserInputEnabled = false homeBinding.slidingNav.setNavigationItemSelectedListener { switchAccount() homeBinding.drawer.closeDrawer(GravityCompat.START) true } } private fun switchAccount() { val accountType = when (Random.Default.nextInt(3)) { 0 -> AccountType.VIP 1 -> AccountType.STANDARD else -> AccountType.GUEST } setSelectedAccount(accountType) } private fun setSelectedAccount(accountType: AccountType) { profileManager.setSelectedAccountType(accountType) contentAdapter.initData(accountType) homeBinding.bottomNav.menu.clear() homeBinding.bottomNav.inflateMenu(getMenuResId(accountType)) tabs.clear() homeBinding.bottomNav.menu.iterator().forEach { tabs.add(it.title.toString()) } val pos = contentAdapter.currentIndex.coerceAtLeast(0).coerceAtMost(homeBinding.bottomNav.menu.size() - 1) val selectedItem = homeBinding.bottomNav.menu.getItem(pos) homeBinding.bottomNav.selectedItemId = selectedItem.itemId homeBinding.contentVp2.setCurrentItem(pos, false) } private fun initData() { homeBinding.bottomNav.setOnNavigationItemSelectedListener(this) contentAdapter = ContentAdapter(this) homeBinding.contentVp2.adapter = contentAdapter setSelectedAccount(profileManager.accountType) lifecycleScope.launch { appEventCenter.subscribe().collect {event -> when (event) { is Event.SwitchTab -> { // trigger scenario: click text -> back press -> click app bringing back to foreground contentAdapter.updateCurrentTab(event.tab) val pos = contentAdapter.currentIndex .coerceAtLeast(0) .coerceAtMost(homeBinding.bottomNav.menu.size() - 1) homeBinding.bottomNav.selectedItemId = homeBinding.bottomNav.menu.getItem(pos).itemId homeBinding.contentVp2.setCurrentItem(pos, false) } Event.Update -> { } } } } } private fun initViewModel() { homeViewModel = vmFactory.create(HomeViewModel::class.java) homeViewModel.currentState.observe(::getLifecycle, ::updateUI) homeViewModel.retrieveProfile() } private fun updateUI(state: ScreenState){ when (state) { ScreenState.Loading -> { homeBinding.loading.visibility = View.VISIBLE homeBinding.error.visibility = View.GONE } ScreenState.Success -> { homeBinding.loading.visibility = View.GONE homeBinding.error.visibility = View.GONE initData() } ScreenState.Error -> { homeBinding.loading.visibility = View.GONE homeBinding.error.visibility = View.VISIBLE } } } override fun onNavigationItemSelected(item: MenuItem): Boolean { val pos = tabs.indexOf(item.title) contentAdapter.updateCurrentTab(pos) homeBinding.contentVp2.setCurrentItem(contentAdapter.currentIndex, false) return true } private fun getMenuResId(accountType: AccountType): Int { return when(accountType) { AccountType.VIP -> R.menu.vip_bottom_menu AccountType.STANDARD -> R.menu.standard_bottom_menu AccountType.GUEST -> R.menu.guest_bottom_menu } } } // use viewpager2, no crash when bringing it back from background after one night in background.
CrashCases/app/src/main/java/six/ca/crashcases/fragment/biz/HomeActivity.kt
2412568745
package com.linroid.airhockey.utils /** * @author linroid <[email protected]> * @since 12/05/2017 */ object Sizeof { val INT = 4 val SHORT = 2 val FLOAT = 4 val DOUBLE = 8 val CHAR = 1 }
OpenGL/AirHockey/app/src/main/java/com/linroid/airhockey/utils/Sizeof.kt
2244432695
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.generators import java.awt.Component import java.awt.Point import java.awt.event.MouseEvent /** * An abstract class for contexts such as ProjectView, ToolWindow, Editor and others. * * @author Sergey Karashevich */ abstract class LocalContextCodeGenerator<C : Component> : ContextCodeGenerator<C> { override fun priority(): Int = 0 // prioritize component code generators 0 - for common, (n) - for the most specific @Suppress("UNCHECKED_CAST") fun generateCode(cmp: Component, me: MouseEvent, cp: Point): String { return generate(typeSafeCast(cmp), me, cp) } fun findComponentInHierarchy(componentDeepest: Component): Component? { val myAcceptor: (Component) -> Boolean = acceptor() var curCmp = componentDeepest while (!myAcceptor(curCmp) && curCmp.parent != null) curCmp = curCmp.parent if (myAcceptor(curCmp)) return curCmp else return null } abstract fun acceptor(): (Component) -> Boolean override fun accept(cmp: Component) = (findComponentInHierarchy(cmp) != null) override fun buildContext(component: Component, mouseEvent: MouseEvent, convertedPoint: Point) = Context(originalGenerator = this, component = typeSafeCast(findComponentInHierarchy(component)!!), code = generate(typeSafeCast(findComponentInHierarchy(component)!!), mouseEvent, convertedPoint)) }
platform/testGuiFramework/src/com/intellij/testGuiFramework/generators/LocalContextCodeGenerator.kt
3993851083
package io.github.flank.gradle.tasks import com.android.build.api.variant.BuiltArtifactsLoader import org.gradle.api.DefaultTask import org.gradle.api.file.Directory import org.gradle.api.file.RegularFile import org.gradle.api.provider.Property import org.gradle.api.provider.Provider import org.gradle.api.tasks.Nested abstract class BaseFlankApkTask : DefaultTask() { @get:Nested internal abstract val appApk: Property<Apk> fun appApk(apk: Provider<RegularFile>) = appApk.set(Apk.from(apk)) fun appApk(apkDir: Provider<Directory>, loader: BuiltArtifactsLoader) = appApk.set(Apk.from(apkDir, loader)) @get:Nested internal abstract val testApk: Property<Apk> fun testApk(apk: Provider<RegularFile>) = testApk.set(Apk.from(apk)) fun testApk(apkDir: Provider<Directory>, loader: BuiltArtifactsLoader) = testApk.set(Apk.from(apkDir, loader)) }
src/main/kotlin/io/github/flank/gradle/tasks/BaseFlankApkTask.kt
1360246178
/* * ************************************************************************ * LiveDataMap.kt * ************************************************************************* * Copyright © 2020 VLC authors and VideoLAN * Author: Nicolas POMEPUY * 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 2 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, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.tools.livedata import androidx.lifecycle.MutableLiveData class LiveDataMap<K, V> : MutableLiveData<MutableMap<K, V>>() { private val emptyMap = mutableMapOf<K, V>() override fun getValue(): MutableMap<K, V> { return super.getValue() ?: emptyMap } fun clear() { value = value.apply { clear() } } fun add(key: K, item: V) { value = value.apply { put(key, item) } } fun remove(key: K) { value = value.apply { remove(key) } } fun get(key: K): V? = value[key] }
application/tools/src/main/java/org/videolan/tools/livedata/LiveDataMap.kt
4179156924
/* * Copyright 2022, TeamDev. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.gradle.javascript.plugin import io.spine.internal.gradle.javascript.JsContext import io.spine.internal.gradle.javascript.JsEnvironment import org.gradle.api.Project import org.gradle.api.plugins.ExtensionContainer import org.gradle.api.plugins.PluginContainer import org.gradle.api.tasks.TaskContainer /** * A scope for applying and configuring JavaScript-related plugins. * * The scope extends [JsContext] and provides shortcuts for key project's containers: * * 1. [plugins]. * 2. [extensions]. * 3. [tasks]. * * Let's imagine one wants to apply and configure `FooBar` plugin. To do that, several steps * should be completed: * * 1. Declare the corresponding extension function upon [JsPlugins] named after the plugin. * 2. Apply and configure the plugin inside that function. * 3. Call the resulted extension in your `build.gradle.kts` file. * * Here's an example of `javascript/plugin/FooBar.kt`: * * ``` * fun JsPlugins.fooBar() { * plugins.apply("com.fooBar") * extensions.configure<FooBarExtension> { * // ... * } * } * ``` * * And here's how to apply it in `build.gradle.kts`: * * ``` * import io.spine.internal.gradle.javascript.javascript * import io.spine.internal.gradle.javascript.plugins.fooBar * * // ... * * javascript { * plugins { * fooBar() * } * } * ``` */ class JsPlugins(jsEnv: JsEnvironment, project: Project) : JsContext(jsEnv, project) { internal val plugins = project.plugins internal val extensions = project.extensions internal val tasks = project.tasks internal fun plugins(configurations: PluginContainer.() -> Unit) = plugins.run(configurations) internal fun extensions(configurations: ExtensionContainer.() -> Unit) = extensions.run(configurations) internal fun tasks(configurations: TaskContainer.() -> Unit) = tasks.run(configurations) }
buildSrc/src/main/kotlin/io/spine/internal/gradle/javascript/plugin/JsPlugins.kt
1965685888
package org.tasks.location import android.app.Activity import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.os.Parcelable import android.view.MenuItem import android.view.View import androidx.activity.viewModels import androidx.appcompat.widget.SearchView import androidx.appcompat.widget.Toolbar import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.content.ContextCompat import androidx.core.widget.ContentLoadingProgressBar import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.appbar.AppBarLayout import com.google.android.material.appbar.AppBarLayout.Behavior.DragCallback import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener import com.google.android.material.appbar.CollapsingToolbarLayout import com.todoroo.andlib.utility.AndroidUtilities import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.tasks.Event import org.tasks.PermissionUtil.verifyPermissions import org.tasks.R import org.tasks.Strings.isNullOrEmpty import org.tasks.activities.PlaceSettingsActivity import org.tasks.analytics.Firebase import org.tasks.billing.Inventory import org.tasks.caldav.GeoUtils.toLikeString import org.tasks.data.LocationDao import org.tasks.data.Place import org.tasks.data.Place.Companion.newPlace import org.tasks.data.PlaceUsage import org.tasks.databinding.ActivityLocationPickerBinding import org.tasks.dialogs.DialogBuilder import org.tasks.extensions.Context.toast import org.tasks.extensions.setOnQueryTextListener import org.tasks.injection.InjectingAppCompatActivity import org.tasks.location.LocationPickerAdapter.OnLocationPicked import org.tasks.location.LocationSearchAdapter.OnPredictionPicked import org.tasks.location.MapFragment.MapFragmentCallback import org.tasks.preferences.ActivityPermissionRequestor import org.tasks.preferences.PermissionChecker import org.tasks.preferences.PermissionRequestor import org.tasks.preferences.Preferences import org.tasks.themes.ColorProvider import org.tasks.themes.Theme import timber.log.Timber import javax.inject.Inject import kotlin.math.abs @AndroidEntryPoint class LocationPickerActivity : InjectingAppCompatActivity(), Toolbar.OnMenuItemClickListener, MapFragmentCallback, OnLocationPicked, SearchView.OnQueryTextListener, OnPredictionPicked, MenuItem.OnActionExpandListener { private lateinit var toolbar: Toolbar private lateinit var appBarLayout: AppBarLayout private lateinit var toolbarLayout: CollapsingToolbarLayout private lateinit var coordinatorLayout: CoordinatorLayout private lateinit var searchView: View private lateinit var loadingIndicator: ContentLoadingProgressBar private lateinit var chooseRecentLocation: View private lateinit var recyclerView: RecyclerView @Inject lateinit var theme: Theme @Inject lateinit var locationDao: LocationDao @Inject lateinit var permissionChecker: PermissionChecker @Inject lateinit var permissionRequestor: ActivityPermissionRequestor @Inject lateinit var dialogBuilder: DialogBuilder @Inject lateinit var map: MapFragment @Inject lateinit var geocoder: Geocoder @Inject lateinit var inventory: Inventory @Inject lateinit var colorProvider: ColorProvider @Inject lateinit var locationService: LocationService @Inject lateinit var firebase: Firebase @Inject lateinit var preferences: Preferences private var mapPosition: MapPosition? = null private var recentsAdapter: LocationPickerAdapter? = null private var searchAdapter: LocationSearchAdapter? = null private var places: List<PlaceUsage> = emptyList() private var offset = 0 private lateinit var search: MenuItem private var searchJob: Job? = null private val viewModel: PlaceSearchViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) theme.applyTheme(this) window.statusBarColor = ContextCompat.getColor(this, android.R.color.transparent) val binding = ActivityLocationPickerBinding.inflate(layoutInflater) setContentView(binding.root) toolbar = binding.toolbar appBarLayout = binding.appBarLayout toolbarLayout = binding.collapsingToolbarLayout coordinatorLayout = binding.coordinator searchView = binding.search.apply { setOnClickListener { searchPlace() } } loadingIndicator = binding.loadingIndicator chooseRecentLocation = binding.chooseRecentLocation recyclerView = binding.recentLocations val configuration = resources.configuration if (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE && configuration.smallestScreenWidthDp < 480) { searchView.visibility = View.GONE } val currentPlace: Place? = intent.getParcelableExtra(EXTRA_PLACE) if (savedInstanceState == null) { mapPosition = currentPlace?.mapPosition ?: intent.getParcelableExtra(EXTRA_MAP_POSITION) } else { mapPosition = savedInstanceState.getParcelable(EXTRA_MAP_POSITION) offset = savedInstanceState.getInt(EXTRA_APPBAR_OFFSET) viewModel.restoreState(savedInstanceState) } toolbar.setNavigationIcon(R.drawable.ic_outline_arrow_back_24px) toolbar.setNavigationOnClickListener { collapseToolbar() } toolbar.inflateMenu(R.menu.menu_location_picker) val menu = toolbar.menu search = menu.findItem(R.id.menu_search) search.setOnActionExpandListener(this) toolbar.setOnMenuItemClickListener(this) val themeColor = theme.themeColor themeColor.applyToNavigationBar(this) val dark = preferences.mapTheme == 2 || preferences.mapTheme == 0 && theme.themeBase.isDarkTheme(this) map.init(this, this, dark) val params = appBarLayout.layoutParams as CoordinatorLayout.LayoutParams val behavior = AppBarLayout.Behavior() behavior.setDragCallback( object : DragCallback() { override fun canDrag(appBarLayout: AppBarLayout): Boolean { return false } }) params.behavior = behavior appBarLayout.addOnOffsetChangedListener( OnOffsetChangedListener { appBarLayout: AppBarLayout, offset: Int -> if (offset == 0 && this.offset != 0) { closeSearch() AndroidUtilities.hideKeyboard(this) } this.offset = offset toolbar.alpha = abs(offset / appBarLayout.totalScrollRange.toFloat()) }) coordinatorLayout.addOnLayoutChangeListener( object : View.OnLayoutChangeListener { override fun onLayoutChange( v: View, l: Int, t: Int, r: Int, b: Int, ol: Int, ot: Int, or: Int, ob: Int) { coordinatorLayout.removeOnLayoutChangeListener(this) locationDao .getPlaceUsage() .observe(this@LocationPickerActivity) { places: List<PlaceUsage> -> updatePlaces(places) } } }) if (offset != 0) { appBarLayout.post { expandToolbar(false) } } findViewById<View>(R.id.google_marker).visibility = View.VISIBLE searchAdapter = LocationSearchAdapter(viewModel.getAttributionRes(dark), this) recentsAdapter = LocationPickerAdapter(this, inventory, colorProvider, this) recentsAdapter!!.setHasStableIds(true) recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = if (search.isActionViewExpanded) searchAdapter else recentsAdapter binding.currentLocation.setOnClickListener { currentLocation() } binding.selectThisLocation.setOnClickListener { selectLocation() } } override fun onMapReady(mapFragment: MapFragment) { map = mapFragment updateMarkers() if (permissionChecker.canAccessForegroundLocation()) { mapFragment.showMyLocation() } mapPosition ?.let { map.movePosition(it, false) } ?: moveToCurrentLocation(false) } override fun onBackPressed() { if (closeSearch()) { return } if (offset != 0) { collapseToolbar() return } super.onBackPressed() } private fun closeSearch(): Boolean = search.isActionViewExpanded && search.collapseActionView() override fun onPlaceSelected(place: Place) { returnPlace(place) } private fun currentLocation() { if (permissionRequestor.requestForegroundLocation()) { moveToCurrentLocation(true) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == PermissionRequestor.REQUEST_FOREGROUND_LOCATION) { if (verifyPermissions(grantResults)) { map.showMyLocation() moveToCurrentLocation(true) } else { dialogBuilder .newDialog(R.string.missing_permissions) .setMessage(R.string.location_permission_required_location) .setPositiveButton(R.string.ok, null) .show() } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults) } } private fun selectLocation() { val mapPosition = map.mapPosition ?: return loadingIndicator.visibility = View.VISIBLE lifecycleScope.launch { try { returnPlace(geocoder.reverseGeocode(mapPosition) ?: newPlace(mapPosition)) } catch (e: Exception) { loadingIndicator.visibility = View.GONE firebase.reportException(e) toast(e.message) } } } private fun searchPlace() { mapPosition = map.mapPosition expandToolbar(true) search.expandActionView() } private fun moveToCurrentLocation(animate: Boolean) { if (!permissionChecker.canAccessForegroundLocation()) { return } lifecycleScope.launch { try { locationService.currentLocation()?.let { map.movePosition(it, animate) } } catch (e: Exception) { toast(e.message) } } } private fun returnPlace(place: Place?) { if (place == null) { Timber.e("Place is null") return } AndroidUtilities.hideKeyboard(this) lifecycleScope.launch { var place = place if (place.id <= 0) { val existing = locationDao.findPlace( place.latitude.toLikeString(), place.longitude.toLikeString()) if (existing == null) { place.id = locationDao.insert(place) } else { place = existing } } setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_PLACE, place as Parcelable?)) finish() } } override fun onResume() { super.onResume() map.onResume() viewModel.observe( this, { searchAdapter!!.submitList(it) }, { returnPlace(it) }, { handleError(it) } ) } override fun onDestroy() { super.onDestroy() map.onDestroy() } private fun handleError(error: Event<String>) { val message = error.ifUnhandled if (!isNullOrEmpty(message)) { toast(message) } } private fun updatePlaces(places: List<PlaceUsage>) { this.places = places updateMarkers() recentsAdapter!!.submitList(places) val params = appBarLayout.layoutParams as CoordinatorLayout.LayoutParams val height = coordinatorLayout.height if (this.places.isEmpty()) { params.height = height chooseRecentLocation.visibility = View.GONE collapseToolbar() } else { params.height = height * 75 / 100 chooseRecentLocation.visibility = View.VISIBLE } } private fun updateMarkers() { map.setMarkers(places.map(PlaceUsage::place)) } private fun collapseToolbar() { appBarLayout.setExpanded(true, true) } private fun expandToolbar(animate: Boolean) { appBarLayout.setExpanded(false, animate) } override fun onPause() { super.onPause() map.onPause() } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) outState.putParcelable(EXTRA_MAP_POSITION, map.mapPosition) outState.putInt(EXTRA_APPBAR_OFFSET, offset) viewModel.saveState(outState) } override fun onMenuItemClick(item: MenuItem): Boolean = if (item.itemId == R.id.menu_search) { searchPlace() true } else false override fun picked(place: Place) { returnPlace(place) } override fun settings(place: Place) { val intent = Intent(this, PlaceSettingsActivity::class.java) intent.putExtra(PlaceSettingsActivity.EXTRA_PLACE, place as Parcelable) startActivity(intent) } override fun onQueryTextSubmit(query: String): Boolean = false override fun onQueryTextChange(query: String): Boolean { searchJob?.cancel() searchJob = lifecycleScope.launch { delay(SEARCH_DEBOUNCE_TIMEOUT) viewModel.query(query, map.mapPosition) } return true } override fun picked(prediction: PlaceSearchResult) { viewModel.fetch(prediction) } override fun onMenuItemActionExpand(item: MenuItem): Boolean { search.setOnQueryTextListener(this) searchAdapter!!.submitList(emptyList()) recyclerView.adapter = searchAdapter return true } override fun onMenuItemActionCollapse(item: MenuItem): Boolean { search.setOnQueryTextListener(null) recyclerView.adapter = recentsAdapter if (places.isEmpty()) { collapseToolbar() } return true } companion object { const val EXTRA_PLACE = "extra_place" private const val EXTRA_MAP_POSITION = "extra_map_position" private const val EXTRA_APPBAR_OFFSET = "extra_appbar_offset" private const val SEARCH_DEBOUNCE_TIMEOUT = 300L } }
app/src/main/java/org/tasks/location/LocationPickerActivity.kt
1434929986
@file:Suppress("ClassName") package tested.overrides import com.nextfaze.devfun.function.DeveloperFunction import com.nextfaze.devfun.inject.InstanceProvider import com.nextfaze.devfun.test.ExpectedItemCount import com.nextfaze.devfun.test.NeverRun import com.nextfaze.devfun.test.TestInstanceProviders import kotlin.reflect.KClass import kotlin.reflect.full.isSubclassOf object OverriddenFunctions : TestInstanceProviders { override val testProviders: List<KClass<out InstanceProvider>> get() = listOf(OverriddenFunctionsInstanceProvider::class) } @Suppress("UNCHECKED_CAST") private class OverriddenFunctionsInstanceProvider : InstanceProvider { @Suppress("IMPLICIT_CAST_TO_ANY") override fun <T : Any> get(clazz: KClass<out T>): T? = when { clazz.isSubclassOf(of_BaseClass::class) -> of_SubClass() clazz.isSubclassOf(of_InternalBaseClass::class) -> of_InternalSubClass() clazz.isSubclassOf(of_PrivateBaseClass::class) -> of_PrivateSubClass() else -> null } as T? } open class of_BaseClass { @DeveloperFunction open fun overriddenFunction(): Any? = NeverRun() @DeveloperFunction protected open fun protectedOverriddenFunction(): Any? = NeverRun() } class of_SubClass : of_BaseClass() { override fun overriddenFunction(): Any? = ExpectedItemCount(1) override fun protectedOverriddenFunction(): Any? = ExpectedItemCount(1) } internal open class of_InternalBaseClass { @DeveloperFunction open fun overriddenFunction(): Any? = NeverRun() @DeveloperFunction protected open fun protectedOverriddenFunction(): Any? = NeverRun() } internal class of_InternalSubClass : of_InternalBaseClass() { override fun overriddenFunction(): Any? = ExpectedItemCount(1) override fun protectedOverriddenFunction(): Any? = ExpectedItemCount(1) } private open class of_PrivateBaseClass { @DeveloperFunction open fun overriddenFunction(): Any? = NeverRun() @DeveloperFunction protected open fun protectedOverriddenFunction(): Any? = NeverRun() } private class of_PrivateSubClass : of_PrivateBaseClass() { override fun overriddenFunction(): Any? = ExpectedItemCount(1) override fun protectedOverriddenFunction(): Any? = ExpectedItemCount(1) }
test/src/testData/kotlin/tested/overrides/OverriddenFunctions.kt
482401104
package io.gitlab.arturbosch.detekt.api.internal private val identifierRegex = Regex("[aA-zZ]+([-][aA-zZ]+)*") /** * Checks if given string matches the criteria of an id - [aA-zZ]+([-][aA-zZ]+)* . */ internal fun validateIdentifier(id: String) { require(id.matches(identifierRegex)) { "id '$id' must match ${identifierRegex.pattern}" } }
detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/internal/Validation.kt
2686056349
package com.example.alexeyglushkov.authorization.requestbuilder import org.junit.Assert import java.util.* import kotlin.collections.ArrayList /** * @author Pablo Fernandez */ class ParameterList { private val params: MutableList<Parameter> constructor() { params = ArrayList() } internal constructor(params: List<Parameter>?) { this.params = ArrayList(params) } constructor(map: Map<String, String>) : this() { for ((key, value) in map) { params.add(Parameter(key, value)) } } fun add(key: String, value: String) { params.add(Parameter(key, value)) } fun appendTo(url: String): String { val queryString = asFormUrlEncodedString() return if (queryString == EMPTY_STRING) { url } else { var resultUrl = url + if (url.indexOf(QUERY_STRING_SEPARATOR) != -1) PARAM_SEPARATOR else QUERY_STRING_SEPARATOR resultUrl += queryString resultUrl } } fun asOauthBaseString(): String? { return OAuthEncoder.encode(asFormUrlEncodedString()) } fun asFormUrlEncodedString(): String { if (params.size == 0) return EMPTY_STRING val builder = StringBuilder() for (p in params) { builder.append('&').append(p.asUrlEncodedPair()) } return builder.toString().substring(1) } fun addAll(other: ParameterList) { params.addAll(other.params) } fun addQuerystring(queryString: String) { if (queryString.length > 0) { for (param in queryString.split(PARAM_SEPARATOR).toTypedArray()) { val pair = param.split(PAIR_SEPARATOR).toTypedArray() val key = OAuthEncoder.decode(pair[0]) val value = if (pair.size > 1) OAuthEncoder.decode(pair[1]) else EMPTY_STRING if (key != null && value != null) { params.add(Parameter(key, value)) } } } } operator fun contains(param: Parameter?): Boolean { return params.contains(param) } fun size(): Int { return params.size } fun sort(): ParameterList { val sorted = ParameterList(params) Collections.sort(sorted.params) return sorted } companion object { private const val QUERY_STRING_SEPARATOR = '?' private const val PARAM_SEPARATOR = "&" private const val PAIR_SEPARATOR = "=" private const val EMPTY_STRING = "" } }
authorization/src/main/java/com/example/alexeyglushkov/authorization/requestbuilder/ParameterList.kt
373043040
package apoc.nlp.aws import apoc.graph.document.builder.DocumentToGraph import apoc.nlp.NLPHelperFunctions import apoc.nlp.NLPVirtualGraph import apoc.result.VirtualGraph import apoc.result.VirtualNode import com.amazonaws.services.comprehend.model.BatchDetectKeyPhrasesResult import org.neo4j.graphdb.Label import org.neo4j.graphdb.Node import org.neo4j.graphdb.Relationship import org.neo4j.graphdb.RelationshipType import org.neo4j.graphdb.Transaction data class AWSVirtualKeyPhrasesGraph(private val detectEntitiesResult: BatchDetectKeyPhrasesResult, private val sourceNodes: List<Node>, val relType: RelationshipType, val relProperty: String, val cutoff: Number): NLPVirtualGraph() { override fun extractDocument(index: Int, sourceNode: Node) : ArrayList<Map<String, Any>> = AWSProcedures.transformResults(index, sourceNode, detectEntitiesResult).value["keyPhrases"] as ArrayList<Map<String, Any>> companion object { const val SCORE_PROPERTY = "score" val KEYS = listOf("text") val LABEL = Label { "KeyPhrase" } val ID_KEYS = listOf("text") } override fun createVirtualGraph(transaction: Transaction?): VirtualGraph { val storeGraph = transaction != null val allNodes: MutableSet<Node> = mutableSetOf() val nonSourceNodes: MutableSet<Node> = mutableSetOf() val allRelationships: MutableSet<Relationship> = mutableSetOf() sourceNodes.forEachIndexed { index, sourceNode -> val document = extractDocument(index, sourceNode) as List<Map<String, Any>> val virtualNodes = LinkedHashMap<MutableSet<String>, MutableSet<Node>>() val virtualNode = VirtualNode(sourceNode, sourceNode.propertyKeys.toList()) val documentToNodes = DocumentToGraph.DocumentToNodes(nonSourceNodes, transaction) val entityNodes = mutableSetOf<Node>() val relationships = mutableSetOf<Relationship>() for (item in document) { val labels: Array<Label> = labels(item) val idValues: Map<String, Any> = idValues(item) val score = item[SCORE_PROPERTY] as Number if(score.toDouble() >= cutoff.toDouble()) { val node = if (storeGraph) { val keyPhraseNode = documentToNodes.getOrCreateRealNode(labels, idValues) setProperties(keyPhraseNode, item) entityNodes.add(keyPhraseNode) val nodeAndScore = Pair(keyPhraseNode, score) relationships.add(NLPHelperFunctions.mergeRelationship(sourceNode, nodeAndScore, relType, relProperty)) sourceNode } else { val keyPhraseNode = documentToNodes.getOrCreateVirtualNode(virtualNodes, labels, idValues) setProperties(keyPhraseNode, item) entityNodes.add(keyPhraseNode) DocumentToGraph.getNodesWithSameLabels(virtualNodes, labels).add(keyPhraseNode) val nodeAndScore = Pair(keyPhraseNode, score) relationships.add(NLPHelperFunctions.mergeRelationship(virtualNode, nodeAndScore, relType, relProperty)) virtualNode } allNodes.add(node) } } nonSourceNodes.addAll(entityNodes) allNodes.addAll(entityNodes) allRelationships.addAll(relationships) } return VirtualGraph("Graph", allNodes, allRelationships, emptyMap()) } private fun idValues(item: Map<String, Any>) = ID_KEYS.map { it to item[it].toString() }.toMap() private fun labels(item: Map<String, Any>) = arrayOf(LABEL) private fun setProperties(entityNode: Node, item: Map<String, Any>) { KEYS.forEach { key -> entityNode.setProperty(key, item[key].toString()) } } }
extended/src/main/kotlin/apoc/nlp/aws/AWSVirtualKeyPhrasesGraph.kt
1385192018
package com.jraska.github.client.analytics interface AnalyticsProperty { fun setUserProperty(key: String, value: String) }
core-api/src/main/java/com/jraska/github/client/analytics/AnalyticsProperty.kt
548193656
package org.tvheadend.data.dao import androidx.room.* import org.tvheadend.data.entity.TagAndChannelEntity @Dao internal abstract class TagAndChannelDao { @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(tagAndChannel: TagAndChannelEntity) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(tagAndChannel: List<TagAndChannelEntity>) @Update abstract fun update(tagAndChannel: TagAndChannelEntity) @Delete abstract fun delete(tagAndChannel: TagAndChannelEntity) @Delete abstract fun delete(tagAndChannel: List<TagAndChannelEntity>) @Transaction open fun insertAndDelete(newTagAndChannels: List<TagAndChannelEntity>, oldTagAndChannels: List<TagAndChannelEntity>) { delete(oldTagAndChannels) insert(newTagAndChannels) } @Query("DELETE FROM tags_and_channels " + " WHERE connection_id IN (SELECT id FROM connections WHERE active = 1) " + " AND tag_id = :id") abstract fun deleteByTagId(id: Int) @Query("DELETE FROM tags_and_channels") abstract fun deleteAll() }
data/src/main/java/org/tvheadend/data/dao/TagAndChannelDao.kt
3884843091
package org.tvheadend.tvhclient.ui.features.dvr.timer_recordings import android.app.Application import android.content.Context import android.content.Intent import androidx.lifecycle.LiveData import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.MutableLiveData import org.tvheadend.data.entity.Channel import org.tvheadend.data.entity.ServerProfile import org.tvheadend.data.entity.TimerRecording import org.tvheadend.tvhclient.R import org.tvheadend.tvhclient.service.ConnectionService import org.tvheadend.tvhclient.ui.base.BaseViewModel import timber.log.Timber import java.util.* class TimerRecordingViewModel(application: Application) : BaseViewModel(application) { var selectedListPosition = 0 val currentIdLiveData = MutableLiveData("") var recording = TimerRecording() var recordingLiveData = MediatorLiveData<TimerRecording>() val recordings: LiveData<List<TimerRecording>> = appRepository.timerRecordingData.getLiveDataItems() var recordingProfileNameId = 0 private val defaultChannelSortOrder = application.applicationContext.resources.getString(R.string.pref_default_channel_sort_order) /** * Returns an intent with the recording data */ fun getIntentData(context: Context, recording: TimerRecording): Intent { val intent = Intent(context, ConnectionService::class.java) intent.putExtra("directory", recording.directory) intent.putExtra("title", recording.title) intent.putExtra("name", recording.name) if (isTimeEnabled) { intent.putExtra("start", recording.start) intent.putExtra("stop", recording.stop) } else { intent.putExtra("start", (0).toLong()) intent.putExtra("stop", (0).toLong()) } intent.putExtra("daysOfWeek", recording.daysOfWeek) intent.putExtra("priority", recording.priority) intent.putExtra("enabled", if (recording.isEnabled) 1 else 0) if (recording.channelId > 0) { intent.putExtra("channelId", recording.channelId) } return intent } var isTimeEnabled: Boolean = false set(value) { field = value if (!value) { startTimeInMillis = Calendar.getInstance().timeInMillis stopTimeInMillis = Calendar.getInstance().timeInMillis } } init { recordingLiveData.addSource(currentIdLiveData) { value -> if (value.isNotEmpty()) { recordingLiveData.value = appRepository.timerRecordingData.getItemById(value) } } } fun loadRecordingByIdSync(id: String) { recording = appRepository.timerRecordingData.getItemById(id) ?: TimerRecording() isTimeEnabled = recording.start > 0 && recording.stop > 0 } var startTimeInMillis: Long = 0 get() { return recording.startTimeInMillis } set(milliSeconds) { field = milliSeconds recording.start = getMinutesFromTime(milliSeconds) } var stopTimeInMillis: Long = 0 get() { return recording.stopTimeInMillis } set(milliSeconds) { field = milliSeconds recording.stop = getMinutesFromTime(milliSeconds) } /** * The start and stop time handling is done in milliseconds within the app, but the * server requires and provides minutes instead. In case the start and stop times of * a recording need to be updated the milliseconds will be converted to minutes. */ private fun getMinutesFromTime(milliSeconds : Long) : Long { val calendar = Calendar.getInstance() calendar.timeInMillis = milliSeconds val hour = calendar.get(Calendar.HOUR_OF_DAY) val minute = calendar.get(Calendar.MINUTE) val minutes = (hour * 60 + minute).toLong() Timber.d("Time in millis is $milliSeconds, start minutes are $minutes") return minutes } fun getChannelList(): List<Channel> { val channelSortOrder = Integer.valueOf(sharedPreferences.getString("channel_sort_order", defaultChannelSortOrder) ?: defaultChannelSortOrder) return appRepository.channelData.getChannels(channelSortOrder) } fun getRecordingProfileNames(): Array<String> { return appRepository.serverProfileData.recordingProfileNames } fun getRecordingProfile(): ServerProfile? { return appRepository.serverProfileData.getItemById(appRepository.serverStatusData.activeItem.timerRecordingServerProfileId) } }
app/src/main/java/org/tvheadend/tvhclient/ui/features/dvr/timer_recordings/TimerRecordingViewModel.kt
4125974831
package be.florien.anyflow.data.user import be.florien.anyflow.data.TimeOperations class AuthPersistenceFake : AuthPersistence() { override val serverUrl = InMemorySecret() override val authToken = InMemorySecret() override val user = InMemorySecret() override val password = InMemorySecret() inner class InMemorySecret() : ExpirationSecret { override var secret: String = "" get() = if (TimeOperations.getCurrentDate().after(TimeOperations.getDateFromMillis(expiration))) "" else field override var expiration: Long = 0L override fun setSecretData(secret: String, expiration: Long) { this.expiration = expiration this.secret = secret } override fun hasSecret(): Boolean = secret.isNotEmpty() override fun isDataValid(): Boolean = TimeOperations.getDateFromMillis(expiration).after(TimeOperations.getCurrentDate()) } }
app/src/sharedTest/java/be/florien/anyflow/data/user/AuthPersistenceFake.kt
4213138619
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.bukkit import com.demonwav.mcdev.asset.PlatformAssets import com.demonwav.mcdev.facet.MinecraftFacet import com.demonwav.mcdev.platform.AbstractModuleType import com.demonwav.mcdev.platform.PlatformType import com.demonwav.mcdev.platform.bukkit.generation.BukkitEventGenerationPanel import com.demonwav.mcdev.platform.bukkit.util.BukkitConstants import com.demonwav.mcdev.platform.bungeecord.util.BungeeCordConstants import com.demonwav.mcdev.util.CommonColors import com.intellij.psi.PsiClass object PaperModuleType : AbstractModuleType<BukkitModule<PaperModuleType>>("com.destroystokyo.paper", "paper-api") { private const val ID = "PAPER_MODULE_TYPE" init { CommonColors.applyStandardColors(colorMap, BukkitConstants.CHAT_COLOR_CLASS) CommonColors.applyStandardColors(colorMap, BungeeCordConstants.CHAT_COLOR_CLASS) } override val platformType = PlatformType.PAPER override val icon = PlatformAssets.PAPER_ICON override val id = ID override val ignoredAnnotations = BukkitModuleType.IGNORED_ANNOTATIONS override val listenerAnnotations = BukkitModuleType.LISTENER_ANNOTATIONS override val isEventGenAvailable = true override fun generateModule(facet: MinecraftFacet): BukkitModule<PaperModuleType> = BukkitModule(facet, this) override fun getEventGenerationPanel(chosenClass: PsiClass) = BukkitEventGenerationPanel(chosenClass) }
src/main/kotlin/platform/bukkit/PaperModuleType.kt
1769156101
/* * Copyright (c) 2019 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.upnp.internal.server import io.mockk.every import io.mockk.mockk import io.mockk.mockkConstructor import io.mockk.spyk import io.mockk.unmockkConstructor import io.mockk.verify import net.mm2d.upnp.Http import net.mm2d.upnp.HttpRequest import net.mm2d.upnp.internal.thread.TaskExecutors import net.mm2d.upnp.internal.thread.ThreadCondition import net.mm2d.upnp.internal.util.closeQuietly import net.mm2d.upnp.util.NetworkUtils import org.junit.After import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.ByteArrayOutputStream import java.net.MulticastSocket import java.net.SocketTimeoutException @Suppress("TestFunctionName", "NonAsciiCharacters") @RunWith(JUnit4::class) class MulticastEventReceiverTest { private lateinit var taskExecutors: TaskExecutors @Before fun setUp() { taskExecutors = TaskExecutors() } @After fun tearDown() { taskExecutors.terminate() } @Test(timeout = 20000L) fun `start stop デッドロックしない`() { val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()) receiver.start() receiver.stop() } @Test(timeout = 20000L) fun `stop デッドロックしない`() { val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk()) receiver.stop() } @Test(timeout = 20000L) fun `run 正常動作`() { mockkConstructor(ThreadCondition::class) every { anyConstructed<ThreadCondition>().isCanceled() } returns false val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())) val socket: MulticastSocket = mockk(relaxed = true) every { receiver.createMulticastSocket(any()) } returns socket every { receiver.receiveLoop(any()) } answers { nothing } receiver.run() verify { socket.joinGroup(any()) receiver.receiveLoop(any()) socket.leaveGroup(any()) socket.closeQuietly() } unmockkConstructor(ThreadCondition::class) } @Test(timeout = 20000L) fun `run すでにcancel`() { mockkConstructor(ThreadCondition::class) every { anyConstructed<ThreadCondition>().isCanceled() } returns true val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())) val socket: MulticastSocket = mockk(relaxed = true) every { receiver.createMulticastSocket(any()) } returns socket every { receiver.receiveLoop(any()) } answers { nothing } receiver.run() verify(inverse = true) { socket.joinGroup(any()) receiver.receiveLoop(any()) socket.leaveGroup(any()) socket.closeQuietly() } unmockkConstructor(ThreadCondition::class) } @Test(timeout = 20000L) fun `receiveLoop 1ループ`() { mockkConstructor(ThreadCondition::class) every { anyConstructed<ThreadCondition>().isCanceled() } returns false val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())) val socket: MulticastSocket = mockk(relaxed = true) every { receiver.onReceive(any(), any()) } answers { every { anyConstructed<ThreadCondition>().isCanceled() } returns true } receiver.receiveLoop(socket) verify(exactly = 1) { receiver.onReceive(any(), any()) } unmockkConstructor(ThreadCondition::class) } @Test(timeout = 20000L) fun `receiveLoop SocketTimeoutExceptionが発生しても次のループに入る`() { mockkConstructor(ThreadCondition::class) every { anyConstructed<ThreadCondition>().isCanceled() } returns false val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())) val socket: MulticastSocket = mockk(relaxed = true) every { receiver.onReceive(any(), any()) } throws (SocketTimeoutException()) andThenAnswer { every { anyConstructed<ThreadCondition>().isCanceled() } returns true } receiver.receiveLoop(socket) verify(exactly = 2) { receiver.onReceive(any(), any()) } unmockkConstructor(ThreadCondition::class) } @Test(timeout = 20000L) fun `receiveLoop receiveの時点でcancelされればonReceiveはコールされない`() { mockkConstructor(ThreadCondition::class) every { anyConstructed<ThreadCondition>().isCanceled() } returns false val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = spyk(MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, mockk())) val socket: MulticastSocket = mockk(relaxed = true) every { socket.receive(any()) } throws (SocketTimeoutException()) andThenAnswer { every { anyConstructed<ThreadCondition>().isCanceled() } returns true } receiver.receiveLoop(socket) verify(exactly = 2) { socket.receive(any()) } verify(inverse = true) { receiver.onReceive(any(), any()) } unmockkConstructor(ThreadCondition::class) } @Test fun `onReceive 条件がそろわなければ通知されない`() { val listener: (uuid: String, svcid: String, lvl: String, seq: Long, properties: List<Pair<String, String>>) -> Unit = mockk(relaxed = true) val networkInterface = NetworkUtils.getAvailableInet4Interfaces()[0] val receiver = MulticastEventReceiver(taskExecutors, Address.IP_V4, networkInterface, listener) val request = HttpRequest.create() request.setStartLine("NOTIFY * HTTP/1.0") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.NT, Http.UPNP_EVENT) request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.NTS, Http.UPNP_PROPCHANGE) request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.LVL, "") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.LVL, "upnp:/info") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.SEQ, "hoge") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.SEQ, "1") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.SVCID, "") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.SVCID, "svcid") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setHeader(Http.USN, "uuid:01234567-89ab-cdef-0123-456789abcdef") request.toByteArray().also { receiver.onReceive(it, it.size) } verify(inverse = true) { listener.invoke(any(), any(), any(), any(), any()) } request.setBody( "<e:propertyset xmlns:e=\"urn:schemas-upnp-org:event-1-0\">\n" + "<e:property>\n" + "<SystemUpdateID>0</SystemUpdateID>\n" + "</e:property>\n" + "<e:property>\n" + "<ContainerUpdateIDs></ContainerUpdateIDs>\n" + "</e:property>\n" + "</e:propertyset>", true ) request.toByteArray().also { receiver.onReceive(it, it.size) } verify(exactly = 1) { listener.invoke(any(), any(), any(), any(), any()) } } private fun HttpRequest.toByteArray(): ByteArray = ByteArrayOutputStream().also { writeData(it) }.toByteArray() }
mmupnp/src/test/java/net/mm2d/upnp/internal/server/MulticastEventReceiverTest.kt
3816513837
// Copyright 2020 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package examples; object Library { fun sayHello(): String { return listOf("Hello", "World").joinToString(" ") } }
testdata/Library.kt
1912765611