content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.test.platform.view.inspector.fixtures import android.app.Activity import android.app.AlertDialog import android.os.Bundle class ActivityWithDialog : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.simple_activity) AlertDialog.Builder(this) .setMessage("This is a dialog") .setTitle("Dialog Title") .create() .show() } }
runner/monitor/javatests/androidx/test/platform/view/inspector/fixtures/ActivityWithDialog.kt
2760879875
// 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.openapi.vcs.changes.savedPatches import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.changes.ui.ChangesTree import com.intellij.openapi.vcs.changes.ui.SimpleTreeEditorDiffPreview import com.intellij.openapi.wm.IdeFocusManager import com.intellij.util.containers.isEmpty import java.awt.Component import javax.swing.JComponent abstract class SavedPatchesEditorDiffPreview(diffProcessor: SavedPatchesDiffPreview, tree: ChangesTree, targetComponent: JComponent, private val focusMainComponent: (Component?) -> Unit) : SimpleTreeEditorDiffPreview(diffProcessor, tree, targetComponent, false) { private var lastFocusOwner: Component? = null init { Disposer.register(diffProcessor, Disposable { lastFocusOwner = null }) } override fun openPreview(requestFocus: Boolean): Boolean { lastFocusOwner = IdeFocusManager.getInstance(project).focusOwner return super.openPreview(requestFocus) } override fun returnFocusToTree() { val focusOwner = lastFocusOwner lastFocusOwner = null focusMainComponent(focusOwner) } override fun updateDiffAction(event: AnActionEvent) { event.presentation.isVisible = true event.presentation.isEnabled = !changeViewProcessor.allChanges.isEmpty() } }
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/SavedPatchesEditorDiffPreview.kt
3184165821
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.workspaceModel.ide import com.intellij.ProjectTopics import com.intellij.openapi.application.runWriteActionAndWait import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.use import com.intellij.testFramework.ApplicationRule import com.intellij.testFramework.rules.ProjectModelRule import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.bridgeEntities.addModuleEntity import com.intellij.workspaceModel.storage.bridgeEntities.api.ModuleEntity import junit.framework.Assert.* import org.junit.Assert import org.junit.ClassRule import org.junit.Rule import org.junit.Test class WorkspaceModelTest { companion object { @JvmField @ClassRule val appRule = ApplicationRule() } @Rule @JvmField val projectModel = ProjectModelRule(forceEnableWorkspaceModel = true) @Test fun `do not fire rootsChanged if there were no changes`() { val disposable = Disposer.newDisposable() projectModel.project.messageBus.connect(disposable).subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { Assert.fail("rootsChanged must not be called if there are no changes") } }) disposable.use { runWriteActionAndWait { WorkspaceModel.getInstance(projectModel.project).updateProjectModel { } } } } @Test fun `async model update`() { val model = WorkspaceModel.getInstance(projectModel.project) val builderSnapshot = model.getBuilderSnapshot() builderSnapshot.builder.addModuleEntity("MyModule", emptyList(), object : EntitySource {}) val replacement = builderSnapshot.getStorageReplacement() val updated = runWriteActionAndWait { model.replaceProjectModel(replacement) } assertTrue(updated) val moduleEntity = WorkspaceModel.getInstance(projectModel.project).entityStorage.current.entities(ModuleEntity::class.java).single() assertEquals("MyModule", moduleEntity.name) } @Test fun `async model update with fail`() { val model = WorkspaceModel.getInstance(projectModel.project) val builderSnapshot = model.getBuilderSnapshot() builderSnapshot.builder.addModuleEntity("MyModule", emptyList(), object : EntitySource {}) val replacement = builderSnapshot.getStorageReplacement() runWriteActionAndWait { model.updateProjectModel { it.addModuleEntity("AnotherModule", emptyList(), object : EntitySource {}) } } val updated = runWriteActionAndWait { WorkspaceModel.getInstance(projectModel.project).replaceProjectModel(replacement) } assertFalse(updated) } }
platform/workspaceModel/jps/tests/testSrc/com/intellij/workspaceModel/ide/WorkspaceModelTest.kt
464032820
/* * Copyright (C) 2022 Yubico. * * 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.yubico.authenticator.oath.keystore import android.os.Build import android.security.keystore.KeyProperties import com.yubico.authenticator.SdkVersion import com.yubico.yubikit.oath.AccessKey interface KeyProvider { fun hasKey(deviceId: String): Boolean fun getKey(deviceId: String): AccessKey? fun putKey(deviceId: String, secret: ByteArray) fun removeKey(deviceId: String) fun clearAll() } fun getAlias(deviceId: String) = "$deviceId,0" val KEY_ALGORITHM_HMAC_SHA1 = if (SdkVersion.ge(Build.VERSION_CODES.M)) { KeyProperties.KEY_ALGORITHM_HMAC_SHA1 } else { "HmacSHA1" }
android/app/src/main/kotlin/com/yubico/authenticator/oath/keystore/KeyProvider.kt
367552907
package com.bajdcc.LALR1.grammar.semantic import com.bajdcc.LALR1.grammar.error.SemanticException.SemanticError import com.bajdcc.LALR1.grammar.symbol.BlockType import com.bajdcc.LALR1.grammar.symbol.IManageSymbol import com.bajdcc.LALR1.grammar.symbol.IQuerySymbol import com.bajdcc.LALR1.grammar.tree.* import com.bajdcc.LALR1.grammar.type.TokenTools import com.bajdcc.LALR1.semantic.token.IIndexedData import com.bajdcc.LALR1.semantic.token.IRandomAccessOfTokens import com.bajdcc.util.lexer.token.KeywordType import com.bajdcc.util.lexer.token.OperatorType import com.bajdcc.util.lexer.token.Token import com.bajdcc.util.lexer.token.TokenType import com.bajdcc.util.lexer.token.TokenType.ID /** * 【语义分析】语义处理器集合 * * @author bajdcc */ class SemanticHandler { /** * 语义分析动作映射表 */ private val semanticAnalyzier = mutableMapOf<String, ISemanticAnalyzer>() /** * 语义执行动作映射表 */ private val semanticAction = mutableMapOf<String, ISemanticAction>() init { initializeAction() initializeHandler() } /** * 初始化动作 */ private fun initializeAction() { /* 进入块 */ semanticAction["do_enter_scope"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { manage.manageScopeService.enterScope() } } /* 离开块 */ semanticAction["do_leave_scope"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { manage.manageScopeService.leaveScope() } } /* 声明过程名 */ semanticAction["predeclear_funcname"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { val token = access.relativeGet(0) val funcName = token.toRealString() if (token.type === ID) { if (manage.queryScopeService.entryName == funcName) { recorder.add(SemanticError.DUP_ENTRY, token) } } else if (manage.queryScopeService.isRegisteredFunc( funcName)) { recorder.add(SemanticError.DUP_FUNCNAME, token) } val func = Func(token) manage.manageScopeService.registerFunc(func) if (token.type !== ID) { token.obj = func.realName token.type = ID } } } /* 声明变量名 */ semanticAction["declear_variable"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { val spec = access.relativeGet(-1).obj as KeywordType val token = access.relativeGet(0) val name = token.toRealString() if (spec == KeywordType.VARIABLE) { if (!manage.queryScopeService.findDeclaredSymbol(name)) { if (!manage.queryScopeService.isRegisteredFunc( name)) { manage.manageScopeService.registerSymbol(name) } else { recorder.add(SemanticError.VAR_FUN_CONFLICT, token) } } else if (!TokenTools.isExternalName(name) && manage.queryScopeService .findDeclaredSymbolDirect(name)) { recorder.add(SemanticError.VARIABLE_REDECLARAED, token) } } else if (spec == KeywordType.LET) { if (!manage.queryScopeService.findDeclaredSymbol(name)) { recorder.add(SemanticError.VARIABLE_NOT_DECLARAED, token) } } } } /* 声明参数 */ semanticAction["declear_param"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { val token = access.relativeGet(0) if (!manage.manageScopeService.registerFutureSymbol( token.toRealString())) { recorder.add(SemanticError.DUP_PARAM, token) } } } /* 清除参数 */ semanticAction["func_clearargs"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { manage.manageScopeService.clearFutureArgs() val token = access.relativeGet(0) val type = token.obj as KeywordType if (type === KeywordType.YIELD) { manage.queryBlockService.enterBlock(BlockType.kYield) } } } /* CATCH 清除参数 */ semanticAction["clear_catch"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { manage.manageScopeService.clearFutureArgs() } } /* 循环体 */ semanticAction["do_enter_cycle"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { manage.queryBlockService.enterBlock(BlockType.kCycle) } } /* 匿名函数处理 */ semanticAction["lambda"] = object : ISemanticAction { override fun handle(indexed: IIndexedData, manage: IManageSymbol, access: IRandomAccessOfTokens, recorder: ISemanticRecorder) { val token = access.relativeGet(0) val func = Func(token) manage.manageScopeService.registerLambda(func) token.obj = func.realName } } } /** * 初始化语义 */ private fun initializeHandler() { /* 复制 */ semanticAnalyzier["copy"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { return indexed[0].obj!! } } semanticAnalyzier["scope"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { query.manageService.manageScopeService.leaveScope() return indexed[0].obj!! } } /* 表达式 */ semanticAnalyzier["exp"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { if (indexed.exists(2)) {// 双目运算 val token = indexed[2].token if (token!!.type === TokenType.OPERATOR) { if (token!!.obj === OperatorType.DOT && indexed[0].obj is ExpInvokeProperty) { val invoke = indexed[0].obj as ExpInvokeProperty invoke.obj = indexed[1].toExp() return invoke } else if (TokenTools.isAssignment(token!!.obj as OperatorType)) { if (indexed[1].obj is ExpBinop) { val bin = indexed[1].obj as ExpBinop if (bin.token.obj === OperatorType.DOT) { val assign = ExpAssignProperty() assign.setToken(token) assign.obj = bin.leftOperand assign.property = bin.rightOperand assign.exp = indexed[0].toExp() if (assign.property is ExpValue && assign.exp is ExpFunc) { val v = assign.property as ExpValue val f = assign.exp as ExpFunc f.func!!.setMethodName(v.toString().replace("\"", "")) } return assign } } else if (indexed[1].obj is ExpIndex) { val bin = indexed[1].obj as ExpIndex val assign = ExpIndexAssign() assign.setToken(token) assign.exp = bin.exp assign.index = bin.index assign.obj = indexed[0].toExp() return assign } } } val binop = ExpBinop(indexed[2].token!!) binop.leftOperand = indexed[1].toExp() binop.rightOperand = indexed[0].toExp() return binop.simplify(recorder) } else if (indexed.exists(3)) {// 单目运算 val token = indexed[3].token if (token!!.type === TokenType.OPERATOR) { if ((token!!.obj === OperatorType.PLUS_PLUS || token!!.obj === OperatorType.MINUS_MINUS) && indexed[1].obj is ExpBinop) { val bin = indexed[1].obj as ExpBinop if (bin.token.obj === OperatorType.DOT) { val assign = ExpAssignProperty() assign.setToken(token!!) assign.obj = bin.leftOperand assign.property = bin.rightOperand return assign } } } val sinop = ExpSinop(indexed[3].token!!, indexed[1].toExp()) return sinop.simplify(recorder) } else if (indexed.exists(4)) {// 三目运算 val triop = ExpTriop() triop.firstToken = indexed[4].token triop.secondToken = indexed[5].token triop.firstOperand = indexed[0].toExp() triop.secondOperand = indexed[6].toExp() triop.thirdOperand = indexed[7].toExp() return triop.simplify(recorder) } else if (indexed.exists(5)) { val exp = ExpIndex() exp.exp = indexed[1].toExp() exp.index = indexed[5].toExp() return exp } else if (!indexed.exists(10)) { val obj = indexed[0].obj if (obj is ExpValue) { if (!obj.isConstant() && !query .queryScopeService .findDeclaredSymbol( obj.token.toRealString())) { recorder.add(SemanticError.VARIABLE_NOT_DECLARAED, obj.token) } } return obj!! } else { val token = indexed[10].token val num = Token() if (token!!.type === TokenType.INTEGER) { val n = token!!.obj as Long if (n > 0L) { recorder.add(SemanticError.INVALID_OPERATOR, token) return indexed[0].obj!! } num.obj = -n num.type = TokenType.INTEGER } else { val n = token!!.obj as Double if (n > 0.0) { recorder.add(SemanticError.INVALID_OPERATOR, token) return indexed[0].obj!! } num.obj = -n num.type = TokenType.DECIMAL } val minus = Token() minus.obj = OperatorType.MINUS minus.type = TokenType.OPERATOR minus.position = token.position val binop = ExpBinop(minus) binop.leftOperand = indexed[0].toExp() num.position = token.position num.position.column = num.position.column + 1 binop.rightOperand = ExpValue(num) return binop.simplify(recorder) } } } /* 基本数据结构 */ semanticAnalyzier["type"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { if (indexed.exists(1)) { return indexed[1].obj!! } else if (indexed.exists(2)) { return indexed[2].obj!! } else if (indexed.exists(3)) { val token = indexed[0].token!! if (token.type === ID) { val invoke = ExpInvoke() invoke.name = token val func = query.queryScopeService.getFuncByName( token.toRealString()) if (func == null) { when { TokenTools.isExternalName(token) -> invoke.extern = token query.queryScopeService .findDeclaredSymbol(token.toRealString()) -> { invoke.extern = token invoke.isInvoke = true } else -> recorder.add(SemanticError.MISSING_FUNCNAME, token) } } else { invoke.func = func } if (indexed.exists(4)) { invoke.params = indexed[4].toExps() } return invoke } else { val invoke = ExpInvokeProperty(token) invoke.property = ExpValue(token) if (indexed.exists(4)) { invoke.params = indexed[4].toExps() } return invoke } } else { val token = indexed[0].token!! return ExpValue(token) } } } /* 入口 */ semanticAnalyzier["main"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val func = Func(query.queryScopeService.entryToken) func.realName = func.name.toRealString() val block = Block(indexed[0].toStmts()) block.stmts.add(StmtReturn()) func.block = block return func } } /* 块 */ semanticAnalyzier["block"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { if (!indexed.exists(0)) { return Block() } return Block(indexed[0].toStmts()) } } /* 语句集合 */ semanticAnalyzier["stmt_list"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val stmts = if (indexed.exists(1)) { indexed[1].toStmts() } else { mutableListOf() } stmts.add(0, indexed[0].toStmt()) return stmts } } /* 变量定义 */ semanticAnalyzier["var"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val assign = ExpAssign() val token = indexed[0].token assign.name = token if (indexed.exists(11)) { assign.isDecleared = true } if (indexed.exists(1)) { val func = ExpFunc() func.func = indexed[1].toFunc() func.genClosure() if (assign.isDecleared) { val funcName = func.func!!.realName if (!query.queryScopeService.isLambda(funcName) && funcName != token!!.toRealString()) { recorder.add(SemanticError.DIFFERENT_FUNCNAME, token) } func.func!!.realName = token!!.toRealString() } assign.exp = func } else if (indexed.exists(2)) { assign.exp = indexed[2].toExp() } else { if (!assign.isDecleared) { recorder.add(SemanticError.INVALID_ASSIGNMENT, token!!) } } return assign } } /* 属性设置 */ semanticAnalyzier["set"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val assign = ExpAssignProperty() assign.obj = indexed[3].toExp() assign.property = indexed[4].toExp() assign.exp = indexed[2].toExp() return assign } } /* 调用表达式 */ semanticAnalyzier["call_exp"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val invoke = ExpInvoke() if (indexed.exists(1)) { val token = indexed[1].token invoke.name = token val func = query.queryScopeService.getFuncByName( token!!.toRealString()) if (func == null) { when { TokenTools.isExternalName(token) -> invoke.extern = token query.queryScopeService .findDeclaredSymbol(token.toRealString()) -> { invoke.extern = token invoke.isInvoke = true } else -> recorder.add(SemanticError.MISSING_FUNCNAME, token) } } else { invoke.func = func } } else if (indexed.exists(3)) { invoke.invokeExp = indexed[3].toExp() } else { invoke.func = indexed[0].toFunc() invoke.name = invoke.func!!.name } if (indexed.exists(2)) { invoke.params = indexed[2].toExps() } return invoke } } /* 类方法调用表达式 */ semanticAnalyzier["invoke"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val invoke = ExpInvokeProperty(indexed[0].token!!) invoke.obj = indexed[1].toExp() invoke.property = indexed[2].toExp() if (indexed.exists(3)) { invoke.params = indexed[3].toExps() } return invoke } } /* 单词集合 */ semanticAnalyzier["token_list"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val tokens = if (indexed.exists(1)) { indexed[1].toTokens() } else { mutableListOf() } tokens.add(0, indexed[0].token!!) return tokens } } /* 表达式集合 */ semanticAnalyzier["exp_list"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val exps = if (indexed.exists(1)) { indexed[1].toExps() } else { mutableListOf() } exps.add(0, indexed[0].toExp()) return exps } } /* 过程 */ semanticAnalyzier["func"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val token = indexed[1].token val func = query.queryScopeService.getFuncByName( token!!.toRealString()) if (!indexed.exists(10)) { func!!.isYield = true query.queryBlockService.leaveBlock(BlockType.kYield) } if (indexed.exists(2)) { func!!.params = indexed[2].toTokens() } if (indexed.exists(0)) { func!!.setDoc(indexed[0].toTokens()) } val ret = StmtReturn() if (func!!.isYield) { ret.isYield = true } if (indexed.exists(3)) { val stmts = mutableListOf<IStmt>() ret.exp = indexed[3].toExp() stmts.add(ret) val block = Block(stmts) func.block = block } else { val block = indexed[4].toBlock() val stmts = block.stmts if (func.isYield) { if (stmts.isEmpty()) { stmts.add(ret) } else if (stmts[stmts.size - 1] is StmtReturn) { val preRet = stmts[stmts.size - 1] as StmtReturn if (preRet.exp != null) { stmts.add(ret) } } else { stmts.add(ret) } } else if (stmts.isEmpty() || stmts[stmts.size - 1] !is StmtReturn) { stmts.add(ret) } func.block = block } return func } } /* 匿名函数 */ semanticAnalyzier["lambda"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val token = indexed[1].token!! val func = query.queryScopeService.lambda func.name = token if (indexed.exists(2)) { func.params = indexed[2].toTokens() } val ret = StmtReturn() if (indexed.exists(3)) { val stmts = mutableListOf<IStmt>() ret.exp = indexed[3].toExp() stmts.add(ret) val block = Block(stmts) func.block = block } else { val block = indexed[4].toBlock() val stmts = block.stmts if (stmts.isEmpty() || stmts[stmts.size - 1] !is StmtReturn) stmts.add(ret) func.block = block } query.manageService.manageScopeService.clearFutureArgs() val exp = ExpFunc() exp.func = func exp.genClosure() return exp } } /* 返回语句 */ semanticAnalyzier["return"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val ret = StmtReturn() if (indexed.exists(0)) { ret.exp = indexed[0].toExp() } if (query.queryBlockService.isInBlock(BlockType.kYield)) { ret.isYield = true } return ret } } /* 导入/导出 */ semanticAnalyzier["port"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val port = StmtPort() val token = indexed[0].token port.name = token if (!indexed.exists(1)) { port.isImported = false val func = query.queryScopeService .getFuncByName(token!!.obj!!.toString()) if (func == null) { recorder.add(SemanticError.WRONG_EXTERN_SYMBOL, token) } else { func.isExtern = true } } return port } } /* 表达式语句 */ semanticAnalyzier["stmt_exp"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val exp = StmtExp() if (indexed.exists(0)) { exp.exp = indexed[0].toExp() } return exp } } /* 条件语句 */ semanticAnalyzier["if"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val stmt = StmtIf() stmt.exp = indexed[0].toExp() stmt.trueBlock = indexed[1].toBlock() if (indexed.exists(2)) { stmt.falseBlock = indexed[2].toBlock() } else if (indexed.exists(3)) { val block = Block() block.stmts.add(indexed[3].toStmt()) stmt.falseBlock = block } return stmt } } /* 循环语句 */ semanticAnalyzier["for"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { query.queryBlockService.leaveBlock(BlockType.kCycle) val stmt = StmtFor() if (indexed.exists(0)) { stmt.variable = indexed[0].toExp() } if (indexed.exists(1)) { stmt.cond = indexed[1].toExp() } if (indexed.exists(2)) { stmt.ctrl = indexed[2].toExp() } stmt.block = indexed[3].toBlock() return stmt } } semanticAnalyzier["while"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { query.queryBlockService.leaveBlock(BlockType.kCycle) val stmt = StmtWhile() stmt.cond = indexed[0].toExp() stmt.block = indexed[1].toBlock() return stmt } } semanticAnalyzier["foreach"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { query.queryBlockService.leaveBlock(BlockType.kCycle) val stmt = StmtForeach() stmt.variable = indexed[0].token stmt.enumerator = indexed[1].toExp() stmt.block = indexed[2].toBlock() if (!stmt.enumerator!!.isEnumerable()) { recorder.add(SemanticError.WRONG_ENUMERABLE, stmt.variable!!) } stmt.enumerator!!.setYield() return stmt } } /* 循环控制表达式 */ semanticAnalyzier["cycle"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val exp = ExpCycleCtrl() if (indexed.exists(0)) { exp.name = indexed[0].token } if (!query.queryBlockService.isInBlock(BlockType.kCycle)) { recorder.add(SemanticError.WRONG_CYCLE, exp.name!!) } return exp } } /* 块语句 */ semanticAnalyzier["block_stmt"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val block = StmtBlock() block.block = indexed[0].toBlock() return block } } /* 数组 */ semanticAnalyzier["array"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val exp = ExpArray() if (indexed.exists(0)) { exp.setParams(indexed[0].toExps()) } return exp } } /* 字典 */ semanticAnalyzier["map_list"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val exps = if (indexed.exists(0)) { indexed[0].toExps() } else { mutableListOf() } val binop = ExpBinop(indexed[3].token!!) val value = ExpValue(indexed[1].token!!) binop.leftOperand = value binop.rightOperand = indexed[2].toExp() exps.add(0, binop.simplify(recorder)) return exps } } semanticAnalyzier["map"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val exp = ExpMap() if (indexed.exists(0)) { exp.params = indexed[0].toExps() } return exp } } /* 异常处理 */ semanticAnalyzier["try"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any { val stmt = StmtTry(indexed[1].toBlock(), indexed[2].toBlock()) if (indexed.exists(0)) { stmt.token = indexed[0].token } return stmt } } semanticAnalyzier["throw"] = object : ISemanticAnalyzer { override fun handle(indexed: IIndexedData, query: IQuerySymbol, recorder: ISemanticRecorder): Any = StmtThrow(indexed[0].toExp()) } } /** * 获得语义分析动作 * * @param name 语义分析动作名称 * @return 语义分析动作 */ fun getSemanticHandler(name: String): ISemanticAnalyzer { return semanticAnalyzier[name]!! } /** * 获得语义执行动作 * * @param name 语义执行动作名称 * @return 语义执行动作 */ fun getActionHandler(name: String): ISemanticAction { return semanticAction[name]!! } }
src/main/kotlin/com/bajdcc/LALR1/grammar/semantic/SemanticHandler.kt
770921632
package com.nytclient import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getTargetContext() assertEquals("com.nytclient", appContext.packageName) } }
app/src/androidTest/java/com/nytclient/ExampleInstrumentedTest.kt
90028219
package nl.jstege.adventofcode.aoccommon.utils.machine /** * Represents a Program, which is an iterable list of Instructions belonging to a machine. * @author Jelle Stege */ class Program( var instructions: MutableList<Instruction>, val machine: Machine ) : Iterable<Instruction> { init { machine.program = this } /** * The amount of instructions in this program. */ val size = instructions.size /** * Returns a [ProgramIterator], which iterates over the program. Do note that this iterator may * have an infinite amount of elements due to jumping to previous instructions. * @return The [ProgramIterator] */ override fun iterator(): Iterator<Instruction> { return ProgramIterator() } /** * An [Iterator] used to iterator over a [Program]. */ inner class ProgramIterator : Iterator<Instruction> { /** * Returns the next [Instruction] * @return The [Instruction] */ override fun next(): Instruction = instructions[machine.ir] /** * Checks whether there is a next [Instruction], this is the case when the [Machine]'s ir * is larger than or equal to 0 and smaller than the [Program]'s size. */ override fun hasNext(): Boolean = machine.ir in (0..(size - 1)) } companion object Assembler { // /** // * Assembles a List of Strings to a [Program]. // * @param rawInstructions A list of [Instruction] representations // * @param machine The machine the resulting [Program] will belong to. // * @param instructionParser The function that parses the given input to instructions. // * @return A [Program] corresponding to the given list of [Instruction] representations // */ // @JvmStatic fun assemble(rawInstructions: List<String>, machine: Machine, // instructionParser: (List<String>) -> List<Instruction>) = // Program(instructionParser(rawInstructions).map { // it.machine = machine // it // }.toMutableList(), machine) /** * Assembles a List of Strings to a [Program]. Will also optimize the resulting program to * run more efficiently. * @param rawInstructions A list of [Instruction] representations * @param machine The machine the resulting [Program] will belong to. * @param instructionParser The function that parses the given input to instructions. * @param optimizer The optimizer to use. * @return A [Program] corresponding to the given list of [Instruction] representations */ @JvmStatic fun assemble( rawInstructions: List<String>, machine: Machine, instructionParser: (List<String>) -> List<Instruction>, optimizer: (MutableList<Instruction>) -> MutableList<Instruction> = { it } ) = Program(optimizer(instructionParser(rawInstructions) .onEach { it.machine = machine } .toMutableList() ), machine) } }
aoc-common/src/main/kotlin/nl/jstege/adventofcode/aoccommon/utils/machine/Program.kt
3577598326
package org.wordpress.android.annotation @Target(AnnotationTarget.CLASS) @Retention(AnnotationRetention.SOURCE) @MustBeDocumented annotation class Feature(val remoteField: String, val defaultValue: Boolean = false)
libs/annotations/src/main/java/org/wordpress/android/annotation/Feature.kt
3623228454
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.functionalities.initializers import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import java.io.Serializable /** * An initializer of the values of dense arrays. */ interface Initializer : Serializable { /** * Initialize the values of the given [array]. * * @param array a dense array */ fun initialize(array: DenseNDArray) }
src/main/kotlin/com/kotlinnlp/simplednn/core/functionalities/initializers/Initializer.kt
2371293194
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.deeplearning.sequenceencoder import com.kotlinnlp.simplednn.core.neuralprocessor.NeuralProcessor import com.kotlinnlp.simplednn.core.optimizer.ParamsErrorsList import com.kotlinnlp.simplednn.simplemath.ndarray.Shape import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArray import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory import kotlin.math.pow /** * Fixed-size Ordinally-Forgetting Encoding (Zhang et al., 2015b). * * @param alpha the forgetting factor (0 < α ≤ 0.5) */ class FOFE( val alpha: Double, override val id: Int = 0 ) : NeuralProcessor< List<DenseNDArray>, // InputType List<DenseNDArray>, // OutputType List<DenseNDArray>, // ErrorsType List<DenseNDArray> // InputErrorsType > { companion object { /** * Build a T-order lower triangular matrix. * Each row vector of the matrix represents a FOFE code of the partial sequence. */ private fun buildMatrix(alpha: Double, length: Int): DenseNDArray { val matrix = DenseNDArrayFactory.zeros(Shape(length, length)) for (i in 0 until matrix.rows) { for (j in 0 until matrix.columns) { when { i == j -> matrix[i, j] = 1.0 i >= j -> matrix[i, j] = alpha.pow(i - j) else -> matrix[i, j] = 0.0 } } } return matrix } } /** * TODO: write documentation */ override val propagateToInput: Boolean = true /** * TODO: write documentation */ private lateinit var matrix: DenseNDArray /** * TODO: write documentation */ private lateinit var inputErrors: List<DenseNDArray> /** * The Forward. * * @param input the input * * @return the result of the forward */ override fun forward(input: List<DenseNDArray>): List<DenseNDArray> { val inputMatrix: DenseNDArray = DenseNDArrayFactory.fromRows(input) this.matrix = buildMatrix(this.alpha, input.size) return this.matrix.dot(inputMatrix).getRows().map { it.t } } /** * The Backward. * * @param outputErrors the output errors */ override fun backward(outputErrors: List<DenseNDArray>) { val errors: DenseNDArray = DenseNDArrayFactory.fromRows(outputErrors) this.inputErrors = errors.dot(this.matrix.t).getRows().map { it.t } } /** * Return the input errors of the last backward. * Before calling this method make sure that [propagateToInput] is enabled. * * @param copy whether to return by value or by reference (default true) * * @return the input errors */ override fun getInputErrors(copy: Boolean): List<DenseNDArray> = this.inputErrors.map { if (copy) it.copy() else it } /** * @param copy a Boolean indicating whether the returned errors must be a copy or a reference * * @return the errors of the network parameters */ override fun getParamsErrors(copy: Boolean): ParamsErrorsList = emptyList() }
src/main/kotlin/com/kotlinnlp/simplednn/deeplearning/sequenceencoder/FOFE.kt
3914580390
package com.asurasdevelopment.ihh.server.comparator import org.javers.core.JaversBuilder import com.asurasdevelopment.ihh.server.persistence.dao.* class LeagueComparator { companion object { private val javers = JaversBuilder.javers().build() fun compareLeagues(working: League, base: League): LeagueChanges { if (working.leagueData == null || base.leagueData == null) { return LeagueChanges.empty() } val diff = javers.compare(working, base) return LeagueChanges(diff.changes) } } }
ihh-server/src/main/kotlin/com/asurasdevelopment/ihh/server/comparator/LeagueComparator.kt
2475157706
// PROBLEM: none class Test(val test: Int) { fun foo() = test } // Receiver unused but still inapplicable (infix) infix fun <caret>Test.build(x: Int) = Test(x * x) fun main(args: Array<String>) { val x = Test(0) build 7 x.foo() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/unusedReceiverParameter/infix.kt
1066130293
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.plugins import com.intellij.testFramework.PlatformTestUtil.getCommunityPath import com.intellij.testFramework.TestDataPath import com.intellij.testFramework.assertions.Assertions.assertThat import com.intellij.testFramework.assertions.CleanupSnapshots import com.intellij.testFramework.rules.InMemoryFsRule import com.intellij.util.io.sanitizeFileName import com.intellij.util.io.write import org.intellij.lang.annotations.Language import org.junit.ClassRule import org.junit.Rule import org.junit.Test import org.junit.rules.TestName import java.nio.file.Path import kotlin.io.path.div private val testSnapshotDir = Path.of(getCommunityPath(), "platform/platform-tests/testSnapshots/plugin-validator") private const val TEST_PLUGIN_ID = "plugin" @TestDataPath("\$CONTENT_ROOT/testSnapshots/plugin-validator") class PluginModelValidatorTest { @Rule @JvmField val inMemoryFs = InMemoryFsRule() @Rule @JvmField val testName = TestName() private val snapshot: Path get() = testSnapshotDir / "${sanitizeFileName(testName.methodName)}.json" private val root: Path get() = inMemoryFs.fs.getPath("/") companion object { @ClassRule @JvmField val cleanupSnapshots = CleanupSnapshots(testSnapshotDir) } @Test fun `dependency on a plugin in a new format must be in a plugin with package prefix`() { val modules = produceDependencyAndDependentPlugins { it.replace(" package=\"dependentPackagePrefix\"", "") } val errors = PluginModelValidator(modules).errorsAsString assertWithMatchSnapshot(errors) } @Test fun `dependency on a plugin is specified as a plugin`() { val modules = produceDependencyAndDependentPlugins() val validator = PluginModelValidator(modules) assertThat(validator.errors).isEmpty() assertWithMatchSnapshot(validator.graphAsString()) } @Test fun `dependency on a plugin must be specified as a plugin`() { val modules = produceDependencyAndDependentPlugins { it.replace("<plugin id=\"dependency\"/>", "<module name=\"intellij.dependent\"/>") } val errors = PluginModelValidator(modules).errorsAsString assertWithMatchSnapshot(errors) } @Test fun `dependency on a plugin must be resolvable`() { val modules = produceDependencyAndDependentPlugins { it.replace("<plugin id=\"dependency\"/>", "<plugin id=\"incorrectId\"/>") } val errors = PluginModelValidator(modules).errorsAsString assertWithMatchSnapshot(errors) } @Test fun `module must not depend on a parent plugin`() { val modules = producePluginWithContentModule { it.replace("<plugin id=\"com.intellij.modules.lang\"/>", "<plugin id=\"$TEST_PLUGIN_ID\"/>") } val errors = PluginModelValidator(modules) .errors .joinToString { it.message!! } assertThat(errors).isEqualTo(""" Do not add dependency on a parent plugin ( entry=XmlElement(name=plugin, attributes={id=plugin}, children=[], content=null), referencingDescriptorFile=/intellij.plugin.module/intellij.plugin.module.xml ) """.trimIndent()) } @Test fun `content module in the same source module`() { val modules = producePluginWithContentModuleInTheSameSourceModule() val validator = PluginModelValidator(modules) assertThat(validator.errors).isEmpty() assertWithMatchSnapshot(validator.graphAsString()) } @Test fun `validate dependencies of content module in the same source module`() { val modules = producePluginWithContentModuleInTheSameSourceModule { it.replace("<dependencies>", "<dependencies><module name=\"com.intellij.diagram\"/>") } val charSequence = PluginModelValidator(modules) assertWithMatchSnapshot(charSequence.errorsAsString) } private fun producePluginWithContentModuleInTheSameSourceModule( mutator: (String) -> String = { it }, ): List<PluginModelValidator.Module> { val module = writeIdeaPluginXml( name = "intellij.angularJs", sourceRoot = root / "intellij.angularJs", content = """ <!--suppress PluginXmlValidity --> <idea-plugin> <id>AngularJs</id> <content> <module name="intellij.angularJs/diagram"/> </content> </idea-plugin> """, ) (root / "intellij.angularJs" / "intellij.angularJs.diagram.xml").writeIdeaPluginXml( content = """ <idea-plugin package="org.angularjs.diagram"> <dependencies> </dependencies> </idea-plugin> """, mutator = mutator, ) return listOf(module) } @Test fun `module must not have dependencies in old format`() { val modules = producePluginWithContentModule { it.replace("</dependencies>", "</dependencies><depends>com.intellij.modules.lang</depends>") } val validator = PluginModelValidator(modules) assertThat(validator.errors.joinToString { it.message!! }).isEqualTo(""" Old format must be not used for a module but `depends` tag is used ( descriptorFile=/intellij.plugin.module/intellij.plugin.module.xml, depends=XmlElement(name=depends, attributes={}, children=[], content=com.intellij.modules.lang) ) """.trimIndent()) } private fun produceDependencyAndDependentPlugins(mutator: (String) -> String = { it }): List<PluginModelValidator.Module> { return listOf( writeIdeaPluginXml( name = "intellij.dependency", sourceRoot = root / "dependency", content = """ <!--suppress PluginXmlValidity --> <idea-plugin package="dependencyPackagePrefix"> <id>dependency</id> </idea-plugin> """, ), writeIdeaPluginXml( name = "intellij.dependent", sourceRoot = root / "dependent", content = """ <idea-plugin package="dependentPackagePrefix"> <id>dependent</id> <dependencies> <plugin id="dependency"/> </dependencies> </idea-plugin> """, mutator = mutator, ), ) } private fun producePluginWithContentModule(mutator: (String) -> String = { it }): List<PluginModelValidator.Module> { return listOf( writeIdeaPluginXml( name = "intellij.plugin", sourceRoot = root / "plugin", content = """ <!--suppress PluginXmlValidity --> <idea-plugin package="plugin"> <id>${TEST_PLUGIN_ID}</id> <content> <module name="intellij.plugin.module"/> </content> </idea-plugin> """, ), writeIdeaPluginXml( name = "intellij.plugin.module", sourceRoot = root / "intellij.plugin.module", path = "intellij.plugin.module", content = """ <idea-plugin package="plugin.module"> <dependencies> <plugin id="com.intellij.modules.lang"/> </dependencies> </idea-plugin> """, mutator = mutator, ) ) } private fun assertWithMatchSnapshot(charSequence: CharSequence) = assertThat(charSequence).toMatchSnapshot(snapshot) } private fun Path.writeIdeaPluginXml( @Language("xml") content: String, mutator: (String) -> String, ) = write(mutator(content).trimIndent()) private fun writeIdeaPluginXml( name: String, sourceRoot: Path, path: String = "META-INF/plugin", @Language("xml") content: String, mutator: (String) -> String = { it }, ) = object : PluginModelValidator.Module { init { (sourceRoot / "$path.xml") .writeIdeaPluginXml(content, mutator) } override val name: String = name override val sourceRoots: List<Path> = listOf(sourceRoot) }
platform/platform-tests/testSrc/com/intellij/ide/plugins/PluginModelValidatorTest.kt
2513386832
package com.yubico.yubioath.exc import java.io.IOException class KeyTooLongException : IOException("Credential name too long.")
app/src/main/kotlin/com/yubico/yubioath/exc/KeyTooLongException.kt
645460515
/* * Copyright 2018 Google LLC. 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 com.example.subscriptions.data.network.firebase import com.example.subscriptions.data.ContentResource import com.example.subscriptions.data.SubscriptionStatus import com.example.subscriptions.data.network.retrofit.ServerFunctionsImpl import kotlinx.coroutines.flow.StateFlow /** * Interface to perform the remote API calls. * * Server updates for loading, basicContent, premiumContent will be communicated * through [StateFlow] variables. */ interface ServerFunctions { /** * True when there are pending network requests. */ val loading: StateFlow<Boolean> /** * The basic content URL. */ val basicContent: StateFlow<ContentResource?> /** * The premium content URL. */ val premiumContent: StateFlow<ContentResource?> /** * Fetch basic content and post results to [basicContent]. * This will fail if the user does not have a basic subscription. */ suspend fun updateBasicContent() /** * Fetch premium content and post results to [premiumContent]. * This will fail if the user does not have a premium subscription. */ suspend fun updatePremiumContent() /** * Fetches subscription data from the server. */ suspend fun fetchSubscriptionStatus(): List<SubscriptionStatus> /** * Register a subscription with the server and return results. */ suspend fun registerSubscription( product: String, purchaseToken: String ): List<SubscriptionStatus> /** * Transfer subscription to this account posts */ suspend fun transferSubscription( product: String, purchaseToken: String ): List<SubscriptionStatus> /** * Register Instance ID when the user signs in or the token is refreshed. */ suspend fun registerInstanceId(instanceId: String) /** * Unregister when the user signs out. */ suspend fun unregisterInstanceId(instanceId: String) /** * Send a purchase object to server for acknowledgement. */ suspend fun acknowledgeSubscription( product: String, purchaseToken: String ): List<SubscriptionStatus> companion object { @Volatile private var INSTANCE: ServerFunctions? = null fun getInstance(): ServerFunctions = INSTANCE ?: synchronized(this) { INSTANCE ?: ServerFunctionsImpl().also { INSTANCE = it } } } }
ClassyTaxiAppKotlin/app/src/main/java/com/example/subscriptions/data/network/firebase/ServerFunctions.kt
2519721398
package ii_collections fun example5() { val result = listOf("a", "bbb", "cc").sortedBy { it.length } result == listOf("a", "cc", "bbb") } fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> { return customers.sortedBy { it.orders.size } }
src/ii_collections/n18Sort.kt
447478702
package com.mobilesolutionworks.android.app import android.content.res.Configuration import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.mobilesolutionworks.android.app.controller.WorksControllerManager /** * Activity host for WorksController. * * Created by yunarta on 19/11/15. */ open class WorksActivity : AppCompatActivity(), WorkControllerHost { var loader: WorksControllerManager.ControllerManager? = null /** * Get controller manager to create individual controller. * @return controller manager. */ override val controllerManager: WorksControllerManager get() { return loader!!.controller } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) loader = supportLoaderManager.initLoader(0, null, WorksControllerManager.ControllerManagerLoaderCallbacks(this)) as WorksControllerManager.ControllerManager } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) controllerManager.getLifecycleHook().onRestoreInstanceState(savedInstanceState) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) controllerManager.getLifecycleHook().onConfigurationChanged(newConfig) } public override fun onResume() { super.onResume() controllerManager.getLifecycleHook().dispatchResume() } public override fun onPause() { super.onPause() controllerManager.getLifecycleHook().dispatchPause() } override fun onSaveInstanceState(outState: Bundle) { controllerManager.getLifecycleHook().dispatchSaveInstanceState(outState) super.onSaveInstanceState(outState) } }
library/src/main/kotlin/com/mobilesolutionworks/android/app/WorksActivity.kt
1202439976
/* * Copyright (c) 2020 * * 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.acra.security import android.os.Build import java.io.IOException import java.net.InetAddress import java.net.Socket import java.net.UnknownHostException import javax.net.ssl.SSLSocket import javax.net.ssl.SSLSocketFactory class ProtocolSocketFactoryWrapper(private val delegate: SSLSocketFactory, protocols: List<TLS>) : SSLSocketFactory() { private val protocols: List<String> init { val list = protocols.toMutableList() if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { list.remove(TLS.V1_3) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { list.remove(TLS.V1_2) list.remove(TLS.V1_1) } } this.protocols = list.map { it.id } } private fun setProtocols(socket: Socket): Socket { if (socket is SSLSocket && isTLSServerEnabled(socket)) { socket.enabledProtocols = protocols.toTypedArray() } return socket } private fun isTLSServerEnabled(sslSocket: SSLSocket): Boolean { for (protocol in sslSocket.supportedProtocols) { if (protocols.contains(protocol)) { return true } } return false } override fun getDefaultCipherSuites(): Array<String> = delegate.defaultCipherSuites override fun getSupportedCipherSuites(): Array<String> = delegate.supportedCipherSuites @Throws(IOException::class) override fun createSocket(socket: Socket, s: String, i: Int, b: Boolean): Socket = setProtocols(delegate.createSocket(socket, s, i, b)) @Throws(IOException::class, UnknownHostException::class) override fun createSocket(s: String, i: Int): Socket = setProtocols(delegate.createSocket(s, i)) @Throws(IOException::class, UnknownHostException::class) override fun createSocket(s: String, i: Int, inetAddress: InetAddress, i1: Int): Socket = setProtocols(delegate.createSocket(s, i, inetAddress, i1)) @Throws(IOException::class) override fun createSocket(inetAddress: InetAddress, i: Int): Socket = setProtocols(delegate.createSocket(inetAddress, i)) @Throws(IOException::class) override fun createSocket(inetAddress: InetAddress, i: Int, inetAddress1: InetAddress, i1: Int): Socket = setProtocols(delegate.createSocket(inetAddress, i, inetAddress1, i1)) }
acra-http/src/main/java/org/acra/security/ProtocolSocketFactoryWrapper.kt
3166945018
// PROBLEM: none val <caret>foo: Any = ""
plugins/kotlin/idea/tests/testData/inspectionsLocal/mayBeConstant/explicitType4.kt
3118298034
fun <R> String.fold(initial: R, operation: (acc: R, Char) -> R): R = TODO() fun foo(p: Int) { "abc".fold(1) { <caret> } } // ORDER: "acc, c ->" // ORDER: "acc: Int, c: Char ->"
plugins/kotlin/completion/testData/weighers/basic/LambdaSignature.kt
1162431634
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.plugins.groovy.codeInsight.hint import com.intellij.testFramework.LightProjectDescriptor import com.intellij.testFramework.utils.inlays.InlayHintsProviderTestCase import org.jetbrains.plugins.groovy.GroovyProjectDescriptors import org.jetbrains.plugins.groovy.codeInsight.hint.types.GroovyLocalVariableTypeHintsInlayProvider class GroovyLocalVariableTypeHintsInlayProviderTest : InlayHintsProviderTestCase() { override fun getProjectDescriptor(): LightProjectDescriptor { return GroovyProjectDescriptors.GROOVY_3_0 } private fun testTypeHints(text: String, drawHintBefore: Boolean = false) { doTestProvider("test.groovy", text, GroovyLocalVariableTypeHintsInlayProvider(), GroovyLocalVariableTypeHintsInlayProvider.Settings(insertBeforeIdentifier = drawHintBefore)) } fun `test basic cases`() { val text = """ def x<# [: Integer] #> = 1 def y<# [: String] #> = "abc" """.trimIndent() testTypeHints(text) } fun `test no type hint for object or null`() { testTypeHints(""" def x = null def foo() {} def y = foo() """.trimIndent()) } fun `test no type hint for casted expression`() { testTypeHints(""" def x = 1 as Number def y = (Number)1 """.trimIndent()) } fun `test no type hint for constructor calls`() { testTypeHints(""" def x = new File() """.trimIndent() ) } fun `test var keyword`() { testTypeHints(""" def x<# [: Integer] #> = 1 """.trimIndent()) } fun `test tuples`() { testTypeHints(""" def (a<# [: Integer] #>, b<# [: String] #>) = new Tuple2<>(1, "") """.trimIndent()) } fun `test draw hint before`() { testTypeHints(""" def <# [Integer ] #>a = 1 """.trimIndent(), true) } fun `test no type hint for variable with explicit type`() { testTypeHints(""" String s = "" """.trimIndent()) } fun `test no type hints for fields`() { testTypeHints(""" class A { def foo = 1 } """.trimIndent()) } }
plugins/groovy/test/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyLocalVariableTypeHintsInlayProviderTest.kt
1839351017
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.io.webSocket import io.netty.channel.Channel import io.netty.channel.ChannelHandlerContext import io.netty.channel.ChannelInboundHandlerAdapter import io.netty.handler.codec.http.FullHttpResponse import io.netty.handler.codec.http.websocketx.* import io.netty.util.CharsetUtil import io.netty.util.ReferenceCountUtil import org.jetbrains.builtInWebServer.LOG import org.jetbrains.io.NettyUtil abstract class WebSocketProtocolHandler : ChannelInboundHandlerAdapter() { final override fun channelRead(context: ChannelHandlerContext, message: Any) { // Pong frames need to get ignored when (message) { !is WebSocketFrame, is PongWebSocketFrame -> ReferenceCountUtil.release(message) is PingWebSocketFrame -> context.channel().writeAndFlush(PongWebSocketFrame(message.content())) is CloseWebSocketFrame -> closeFrameReceived(context.channel(), message) is TextWebSocketFrame -> { try { textFrameReceived(context.channel(), message) } finally { // client should release buffer as soon as possible, so, message could be released already if (message.refCnt() > 0) { message.release() } } } else -> throw UnsupportedOperationException("${message.javaClass.name} frame types not supported") } } protected abstract fun textFrameReceived(channel: Channel, message: TextWebSocketFrame) protected open fun closeFrameReceived(channel: Channel, message: CloseWebSocketFrame) { channel.close() message.release() } @Suppress("OverridingDeprecatedMember") override fun exceptionCaught(context: ChannelHandlerContext, cause: Throwable) { NettyUtil.logAndClose(cause, LOG, context.channel()) } } open class WebSocketProtocolHandshakeHandler(private val handshaker: WebSocketClientHandshaker) : ChannelInboundHandlerAdapter() { final override fun channelRead(context: ChannelHandlerContext, message: Any) { val channel = context.channel() if (!handshaker.isHandshakeComplete) { try { handshaker.finishHandshake(channel, message as FullHttpResponse) val pipeline = channel.pipeline() pipeline.replace(this, "aggregator", WebSocketFrameAggregator(NettyUtil.MAX_CONTENT_LENGTH)) // https codec is removed by finishHandshake completed() return } finally { ReferenceCountUtil.release(message) } } if (message is FullHttpResponse) { throw IllegalStateException("Unexpected FullHttpResponse (getStatus=${message.status()}, content=${message.content().toString(CharsetUtil.UTF_8)})") } context.fireChannelRead(message) } protected open fun completed() { } }
platform/built-in-server/src/org/jetbrains/io/webSocket/WebSocketProtocolHandler.kt
2188502179
/* * Copyright 2020 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.google.maps.android.ktx.utils import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.Polygon import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test internal class PolygonTest { @Test fun testContainsTrue() { val polygon = mockPolygon(listOf(LatLng(1.0, 2.2), LatLng(0.0, 1.0))) assertTrue(polygon.contains(LatLng(1.0, 2.2))) } @Test fun testContainsFalse() { val polygon = mockPolygon(listOf(LatLng(1.0, 2.2), LatLng(0.0, 1.0))) assertFalse(polygon.contains(LatLng(1.01, 2.2))) } @Test fun testIsOnEdgeTrue() { val polygon = mockPolygon(listOf(LatLng(1.0, 2.2), LatLng(0.0, 1.0))) assertTrue(polygon.isOnEdge(LatLng(1.0, 2.2))) // Tolerance assertTrue(polygon.isOnEdge(LatLng(1.0000005, 2.2))) } @Test fun testIsOnEdgeFalse() { val polygon = mockPolygon(listOf(LatLng(1.0, 2.2), LatLng(0.0, 1.0))) assertFalse(polygon.isOnEdge(LatLng(3.0, 2.2))) } private fun mockPolygon(p: List<LatLng>, geodesic: Boolean = true) = mock<Polygon> { on { points } doReturn p on { isGeodesic } doReturn geodesic } }
maps-utils-ktx/src/test/java/com/google/maps/android/ktx/utils/PolygonTest.kt
2345312981
// AFTER-WARNING: Parameter 'a' is never used fun <T> doSomething(a: T) {} fun foo() { val a = true val b = false val c = true <caret>if (a && b || c) { doSomething("test") } }
plugins/kotlin/idea/tests/testData/intentions/splitIf/onIfWithOr.kt
2908097296
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.websocket import io.ktor.util.* import kotlin.jvm.* /** * Websocket close reason * @property code - close reason code as per RFC 6455, recommended to be one of [CloseReason.Codes] * @property message - a close reason message, could be empty */ public data class CloseReason(val code: Short, val message: String) { public constructor(code: Codes, message: String) : this(code.code, message) /** * An enum value for this [code] or `null` if the [code] is not listed in [Codes] */ val knownReason: Codes? get() = Codes.byCode(code) override fun toString(): String { return "CloseReason(reason=${knownReason ?: code}, message=$message)" } /** * Standard close reason codes * * see https://tools.ietf.org/html/rfc6455#section-7.4 for list of codes */ @Suppress("KDocMissingDocumentation") public enum class Codes(public val code: Short) { NORMAL(1000), GOING_AWAY(1001), PROTOCOL_ERROR(1002), CANNOT_ACCEPT(1003), @InternalAPI @Deprecated("This code MUST NOT be set as a status code in a Close control frame by an endpoint") CLOSED_ABNORMALLY(1006), NOT_CONSISTENT(1007), VIOLATED_POLICY(1008), TOO_BIG(1009), NO_EXTENSION(1010), INTERNAL_ERROR(1011), SERVICE_RESTART(1012), TRY_AGAIN_LATER(1013); public companion object { private val byCodeMap = values().associateBy { it.code } @Deprecated( "Use INTERNAL_ERROR instead.", ReplaceWith( "INTERNAL_ERROR", "io.ktor.websocket.CloseReason.Codes.INTERNAL_ERROR" ) ) @JvmField @Suppress("UNUSED") public val UNEXPECTED_CONDITION: Codes = INTERNAL_ERROR /** * Get enum value by close reason code * @return enum instance or null if [code] is not in standard */ public fun byCode(code: Short): Codes? = byCodeMap[code] } } }
ktor-shared/ktor-websockets/common/src/io/ktor/websocket/CloseReason.kt
2969843271
package lt.markmerkk import lt.markmerkk.utils.LogFormatters class LogFormatterStringRes(private val strings: Strings) : LogFormatters.StringRes { override fun resTomorrow(): String = strings.getString("generic_tomorrow") }
components/src/main/java/lt/markmerkk/LogFormatterStringRes.kt
3724986616
/* * Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.client.tests import io.ktor.client.call.* import io.ktor.client.engine.mock.* import io.ktor.client.plugins.logging.* import io.ktor.client.request.* import io.ktor.client.request.forms.* import io.ktor.client.statement.* import io.ktor.client.tests.utils.* import io.ktor.http.* import io.ktor.util.* import io.ktor.utils.io.core.* import kotlin.test.* class LoggingMockedTests { @Test fun testLogRequestWithException() = testWithEngine(MockEngine) { val testLogger = TestLogger( "REQUEST: ${URLBuilder.origin}", "METHOD: HttpMethod(value=GET)", "COMMON HEADERS", "-> Accept: */*", "-> Accept-Charset: UTF-8", "CONTENT HEADERS", "-> Content-Length: 0", "BODY Content-Type: null", "BODY START", "", "BODY END", "REQUEST ${URLBuilder.origin} failed with exception: CustomError[BAD REQUEST]" ) config { engine { addHandler { throw CustomError("BAD REQUEST") } } install(Logging) { level = LogLevel.ALL logger = testLogger } } test { client -> var failed = false try { client.get { url(port = DEFAULT_PORT) } } catch (_: Throwable) { failed = true } assertTrue(failed, "Exception is missing.") } after { testLogger.verify() } } @Test fun testLogResponseWithException() = testWithEngine(MockEngine) { val testLogger = TestLogger( "REQUEST: ${URLBuilder.origin}", "METHOD: HttpMethod(value=GET)", "COMMON HEADERS", "-> Accept: */*", "-> Accept-Charset: UTF-8", "CONTENT HEADERS", "-> Content-Length: 0", "BODY Content-Type: null", "BODY START", "", "BODY END", "RESPONSE: 200 OK", "METHOD: HttpMethod(value=GET)", "FROM: ${URLBuilder.origin}", "COMMON HEADERS", "+++RESPONSE ${URLBuilder.origin} failed with exception: CustomError[PARSE ERROR]", "BODY Content-Type: null", "BODY START", "Hello", "BODY END" ) config { engine { addHandler { respondOk("Hello") } } install("BadInterceptor") { responsePipeline.intercept(HttpResponsePipeline.Transform) { throw CustomError("PARSE ERROR") } } install(Logging) { level = LogLevel.ALL logger = testLogger } } test { client -> if (PlatformUtils.IS_NATIVE) return@test var failed = false client.prepareGet { url(port = DEFAULT_PORT) }.execute { try { it.body<String>() } catch (_: CustomError) { failed = true } } assertTrue(failed, "Exception is missing.") } after { if (PlatformUtils.IS_NATIVE) return@after testLogger.verify() } } @Test fun testLogResponseWithExceptionSingle() = testWithEngine(MockEngine) { val testLogger = TestLogger( "REQUEST: ${URLBuilder.origin}", "METHOD: HttpMethod(value=GET)", "COMMON HEADERS", "-> Accept: */*", "-> Accept-Charset: UTF-8", "CONTENT HEADERS", "-> Content-Length: 0", "BODY Content-Type: null", "BODY START", "", "BODY END", "RESPONSE: 200 OK", "METHOD: HttpMethod(value=GET)", "FROM: ${URLBuilder.origin}", "COMMON HEADERS", "RESPONSE ${URLBuilder.origin} failed with exception: CustomError[PARSE ERROR]", "REQUEST ${URLBuilder.origin} failed with exception: CustomError[PARSE ERROR]" ) config { engine { addHandler { respondOk("Hello") } } install("BadInterceptor") { receivePipeline.intercept(HttpReceivePipeline.State) { throw CustomError("PARSE ERROR") } } install(Logging) { level = LogLevel.ALL logger = testLogger } } test { client -> var failed = false try { client.get { url(port = DEFAULT_PORT) } } catch (_: CustomError) { failed = true } assertTrue(failed, "Exception is missing.") } after { testLogger.verify() } } @Test fun testLoggingWithForm() = testWithEngine(MockEngine) { val testLogger = TestLogger( "REQUEST: http://localhost/", "METHOD: HttpMethod(value=POST)", "COMMON HEADERS", "-> Accept: */*", "-> Accept-Charset: UTF-8", "CONTENT HEADERS", "!!!-> Content-Type: multipart/form-data; " + "boundary=27e7dfaa-451f2057-3dabbd0c2b3cae572a4935af6a57b2d4bb335c34480373360863", "!!! BODY Content-Type: multipart/form-data; " + "boundary=41a55fb5-2ae7bc4b-5b124e524086ca1e-6879a99a75b8a0a028a6a7d7-63d38251-5", "BODY START", "!!!--41a55fb5-2ae7bc4b-5b124e524086ca1e-6879a99a75b8a0a028a6a7d7-63d38251-5", """Content-Disposition: form-data; name=file; file; name=""; filename=""""", "", "Hello", """!!!--41a55fb5-2ae7bc4b-5b124e524086ca1e-6879a99a75b8a0a028a6a7d7-63d38251-5--""", "", "BODY END", "RESPONSE: 200 OK", "METHOD: HttpMethod(value=POST)", "FROM: http://localhost/", "COMMON HEADERS", "BODY Content-Type: null", "BODY START", "", "BODY END" ) config { engine { addHandler { val body = it.body.toByteReadPacket().readText() assertTrue { body.contains("Hello") } respondOk() } } Logging { level = LogLevel.ALL logger = testLogger } } test { client -> val input = buildPacket { writeText("Hello") } client.submitFormWithBinaryData( "http://localhost/", formData { appendInput( "file", headersOf( HttpHeaders.ContentDisposition, ContentDisposition.File.withParameter(ContentDisposition.Parameters.Name, "") .withParameter(ContentDisposition.Parameters.FileName, "") .toString() ) ) { input } } ).body<String>() } after { testLogger.verify() } } @Test fun testFilterRequest() = testWithEngine(MockEngine) { val testLogger = TestLogger( "REQUEST: http://somewhere/filtered_path", "METHOD: HttpMethod(value=GET)", "COMMON HEADERS", "-> Accept: */*", "-> Accept-Charset: UTF-8", "CONTENT HEADERS", "-> Content-Length: 0", "BODY Content-Type: null", "BODY START", "", "BODY END", "RESPONSE: 200 OK", "METHOD: HttpMethod(value=GET)", "FROM: http://somewhere/filtered_path", "COMMON HEADERS", "BODY Content-Type: null", "BODY START", "", "BODY END" ) config { engine { addHandler { respondOk() } } install(Logging) { level = LogLevel.ALL logger = testLogger filter { it.url.encodedPath == "/filtered_path" } } } test { client -> client.get(urlString = "http://somewhere/filtered_path") client.get(urlString = "http://somewhere/not_filtered_path") } after { testLogger.verify() } } }
ktor-client/ktor-client-tests/common/test/io/ktor/client/tests/LoggingMockedTests.kt
1848233138
package com.ledboot.toffee.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import javax.inject.Inject import javax.inject.Provider class ToffeeViewModelFactory @Inject constructor(private val creators: @JvmSuppressWildcards Map<Class<out ViewModel>, Provider<ViewModel>>) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { val found = creators.entries.find { modelClass.isAssignableFrom(it.key) } val creator = found?.value ?: throw IllegalArgumentException("unknown model class " + modelClass) try { return creator.get() as T } catch (e: Exception) { throw RuntimeException(e) } } }
app/src/main/java/com/ledboot/toffee/di/ToffeeViewModelFactory.kt
908536284
@file:Suppress("NOTHING_TO_INLINE", "IntroduceWhenSubject") package io.ktor.utils.io.bits import io.ktor.utils.io.core.internal.* import kotlinx.cinterop.* import platform.posix.* public actual class Memory constructor( public val pointer: CPointer<ByteVar>, public actual inline val size: Long ) { init { requirePositiveIndex(size, "size") } /** * Size of memory range in bytes represented as signed 32bit integer * @throws IllegalStateException when size doesn't fit into a signed 32bit integer */ public actual inline val size32: Int get() = size.toIntOrFail("size") /** * Returns byte at [index] position. */ public actual inline fun loadAt(index: Int): Byte = pointer[assertIndex(index, 1)] /** * Returns byte at [index] position. */ public actual inline fun loadAt(index: Long): Byte = pointer[assertIndex(index, 1)] /** * Write [value] at the specified [index]. */ public actual inline fun storeAt(index: Int, value: Byte) { pointer[assertIndex(index, 1)] = value } /** * Write [value] at the specified [index] */ public actual inline fun storeAt(index: Long, value: Byte) { pointer[assertIndex(index, 1)] = value } public actual fun slice(offset: Long, length: Long): Memory { assertIndex(offset, length) if (offset == 0L && length == size) { return this } return Memory(pointer.plus(offset)!!, length) } public actual fun slice(offset: Int, length: Int): Memory { assertIndex(offset, length) if (offset == 0 && length.toLong() == size) { return this } return Memory(pointer.plus(offset)!!, length.toLong()) } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. * Copying bytes from a memory to itself is allowed. */ @OptIn(UnsafeNumber::class) public actual fun copyTo(destination: Memory, offset: Int, length: Int, destinationOffset: Int) { require(offset >= 0) { "offset shouldn't be negative: $offset" } require(length >= 0) { "length shouldn't be negative: $length" } require(destinationOffset >= 0) { "destinationOffset shouldn't be negative: $destinationOffset" } if (offset + length > size) { throw IndexOutOfBoundsException("offset + length > size: $offset + $length > $size") } if (destinationOffset + length > destination.size) { throw IndexOutOfBoundsException( "dst offset + length > size: $destinationOffset + $length > ${destination.size}" ) } if (length == 0) return memcpy( destination.pointer + destinationOffset, pointer + offset, length.convert() ) } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. * Copying bytes from a memory to itself is allowed. */ @OptIn(UnsafeNumber::class) public actual fun copyTo(destination: Memory, offset: Long, length: Long, destinationOffset: Long) { require(offset >= 0L) { "offset shouldn't be negative: $offset" } require(length >= 0L) { "length shouldn't be negative: $length" } require(destinationOffset >= 0L) { "destinationOffset shouldn't be negative: $destinationOffset" } if (offset + length > size) { throw IndexOutOfBoundsException("offset + length > size: $offset + $length > $size") } if (destinationOffset + length > destination.size) { throw IndexOutOfBoundsException( "dst offset + length > size: $destinationOffset + $length > ${destination.size}" ) } if (length == 0L) return memcpy( destination.pointer + destinationOffset, pointer + offset, length.convert() ) } public actual companion object { public actual val Empty: Memory = Memory(nativeHeap.allocArray(0), 0L) } } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. */ public actual fun Memory.copyTo( destination: ByteArray, offset: Int, length: Int, destinationOffset: Int ) { if (destination.isEmpty() && destinationOffset == 0 && length == 0) { // NOTE: this is required since pinned.getAddressOf(0) will crash with exception return } destination.usePinned { pinned -> copyTo( destination = Memory(pinned.addressOf(0), destination.size.toLong()), offset = offset, length = length, destinationOffset = destinationOffset ) } } /** * Copies bytes from this memory range from the specified [offset] and [length] * to the [destination] at [destinationOffset]. */ public actual fun Memory.copyTo( destination: ByteArray, offset: Long, length: Int, destinationOffset: Int ) { if (destination.isEmpty() && destinationOffset == 0 && length == 0) { // NOTE: this is required since pinned.getAddressOf(0) will crash with exception return } destination.usePinned { pinned -> copyTo( destination = Memory(pinned.addressOf(0), destination.size.toLong()), offset = offset, length = length.toLong(), destinationOffset = destinationOffset.toLong() ) } } @PublishedApi internal inline fun Memory.assertIndex(offset: Int, valueSize: Int): Int { assert(offset in 0..size - valueSize) { throw IndexOutOfBoundsException("offset $offset outside of range [0; ${size - valueSize})") } return offset } @PublishedApi internal inline fun Memory.assertIndex(offset: Long, valueSize: Long): Long { assert(offset in 0..size - valueSize) { throw IndexOutOfBoundsException("offset $offset outside of range [0; ${size - valueSize})") } return offset } @PublishedApi internal inline fun Short.toBigEndian(): Short { return when { !Platform.isLittleEndian -> this else -> reverseByteOrder() } } @PublishedApi internal inline fun Int.toBigEndian(): Int = when { !Platform.isLittleEndian -> this else -> reverseByteOrder() } @PublishedApi internal inline fun Long.toBigEndian(): Long = when { !Platform.isLittleEndian -> this else -> reverseByteOrder() } @PublishedApi internal inline fun Float.toBigEndian(): Float = when { !Platform.isLittleEndian -> this else -> reverseByteOrder() } @PublishedApi internal inline fun Double.toBigEndian(): Double = when { !Platform.isLittleEndian -> this else -> reverseByteOrder() } /** * Fill memory range starting at the specified [offset] with [value] repeated [count] times. */ @OptIn(UnsafeNumber::class) public actual fun Memory.fill(offset: Long, count: Long, value: Byte) { requirePositiveIndex(offset, "offset") requirePositiveIndex(count, "count") requireRange(offset, count, size, "fill") if (count.toULong() > size_t.MAX_VALUE.toULong()) { throw IllegalArgumentException("count is too big: it shouldn't exceed size_t.MAX_VALUE") } memset(pointer + offset, value.toInt(), count.convert()) } /** * Fill memory range starting at the specified [offset] with [value] repeated [count] times. */ @OptIn(UnsafeNumber::class) public actual fun Memory.fill(offset: Int, count: Int, value: Byte) { requirePositiveIndex(offset, "offset") requirePositiveIndex(count, "count") requireRange(offset.toLong(), count.toLong(), size, "fill") if (count.toULong() > size_t.MAX_VALUE.toULong()) { throw IllegalArgumentException("count is too big: it shouldn't exceed size_t.MAX_VALUE") } memset(pointer + offset, value.toInt(), count.convert()) } /** * Copy content bytes to the memory addressed by the [destination] pointer with * the specified [destinationOffset] in bytes. */ public fun Memory.copyTo( destination: CPointer<ByteVar>, offset: Int, length: Int, destinationOffset: Int ) { copyTo(destination, offset.toLong(), length.toLong(), destinationOffset.toLong()) } /** * Copy content bytes to the memory addressed by the [destination] pointer with * the specified [destinationOffset] in bytes. */ @OptIn(UnsafeNumber::class) public fun Memory.copyTo( destination: CPointer<ByteVar>, offset: Long, length: Long, destinationOffset: Long ) { requirePositiveIndex(offset, "offset") requirePositiveIndex(length, "length") requirePositiveIndex(destinationOffset, "destinationOffset") requireRange(offset, length, size, "source memory") memcpy(destination + destinationOffset, pointer + offset, length.convert()) } /** * Copy [length] bytes to the [destination] at the specified [destinationOffset] * from the memory addressed by this pointer with [offset] in bytes. */ public fun CPointer<ByteVar>.copyTo(destination: Memory, offset: Int, length: Int, destinationOffset: Int) { copyTo(destination, offset.toLong(), length.toLong(), destinationOffset.toLong()) } /** * Copy [length] bytes to the [destination] at the specified [destinationOffset] * from the memory addressed by this pointer with [offset] in bytes. */ @OptIn(UnsafeNumber::class) public fun CPointer<ByteVar>.copyTo(destination: Memory, offset: Long, length: Long, destinationOffset: Long) { requirePositiveIndex(offset, "offset") requirePositiveIndex(length, "length") requirePositiveIndex(destinationOffset, "destinationOffset") requireRange(destinationOffset, length, destination.size, "source memory") memcpy(destination.pointer + destinationOffset, this + offset, length.convert()) }
ktor-io/posix/src/io/ktor/utils/io/bits/MemoryNative.kt
22000909
package org.ethtrader.ticker import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.PropertyNamingStrategy import com.fasterxml.jackson.module.kotlin.KotlinModule import com.fasterxml.jackson.module.kotlin.readValue import org.glassfish.jersey.media.multipart.FormDataMultiPart import org.glassfish.jersey.media.multipart.MultiPart import org.glassfish.jersey.media.multipart.file.StreamDataBodyPart import java.io.InputStream import javax.ws.rs.client.Entity import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response data class JsonError(val error: Int) internal fun List<String>?.csv(): String? = this?.joinToString(",") fun Array<out Pair<String, Any?>>.multipart(): Entity<MultiPart> = Entity.entity(fold(FormDataMultiPart()) { multiPart, pair -> when (pair.second) { is InputStream -> multiPart.bodyPart(StreamDataBodyPart(pair.first, pair.second as InputStream)) as FormDataMultiPart else -> multiPart.field (pair.first, pair.second.toString()) } }, MediaType.MULTIPART_FORM_DATA) private val objectMapper = ObjectMapper() .registerModule(KotlinModule()) .setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE) .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) private fun Response.getResponse(): ResponseWrapper { val string = readEntity(String::class.java) println(string) try { return objectMapper.readValue(string) } catch (e: Throwable) { val error: JsonError = objectMapper.readValue(string) throw RuntimeException("Error Json Object returned, error code: ${error.error}", e) } } data class ResponseWrapper(val kind: String?, val errors: List<String>?, val data: Map<String, Any?>?) // Generated API start. /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L57> * # <https://www.reddit.com/dev/api#GET_api_v1_me>GET /api/v1/meidentity * <https://github.com/reddit/reddit/wiki/OAuth2> * - Returns the identity of the user currently authenticated via OAuth. **/ fun OAuthClient.getV1Me() = retry(3) { requestApi("/api/v1/me").get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L106> * # <https://www.reddit.com/dev/api#GET_api_v1_me_karma>GET /api/v1/me/karma * mysubreddits <https://github.com/reddit/reddit/wiki/OAuth2> * - Return a breakdown of subreddit karma. **/ fun OAuthClient.getV1MeKarma() = retry(3) { requestApi("/api/v1/me/karma").get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L67> * # <https://www.reddit.com/dev/api#GET_api_v1_me_prefs>GET /api/v1/me/prefs * identity <https://github.com/reddit/reddit/wiki/OAuth2> * - Return the preference settings of the logged in user * - fieldsA comma-separated list of items from this set: * - threaded_messages * hide_downs * email_messages * show_link_flair * creddit_autorenew * show_trending * private_feeds * monitor_mentions * research * ignore_suggested_sort * media * clickgadget * use_global_defaults * label_nsfw * domain_details * show_stylesheets * highlight_controversial * no_profanity * default_theme_sr * lang * hide_ups * hide_from_robots * compress * store_visits * threaded_modmail * beta * other_theme * show_gold_expiration * over_18 * enable_default_themes * show_promote * min_comment_score * public_votes * organic * collapse_read_messages * show_flair * mark_messages_read * hide_ads * min_link_score * newwindow * numsites * legacy_search * num_comments * highlight_new_comments * default_comment_sort * hide_locationbar **/ fun OAuthClient.getV1MePrefs(fields: List<String>?) = retry(3) { requestApi("/api/v1/me/prefs", "fields" to fields.csv()).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L123> * # <https://www.reddit.com/dev/api#PATCH_api_v1_me_prefs>PATCH /api/v1/me/prefs * account <https://github.com/reddit/reddit/wiki/OAuth2> * - This endpoint expects JSON data of this format{ "beta": boolean value, * "clickgadget": boolean value, "collapse_read_messages": boolean value, * "compress": boolean value, "creddit_autorenew": boolean value, * "default_comment_sort": one of (`confidence`, `old`, `top`, `qa`, * `controversial`, `new`), "domain_details": boolean value, "email_messages": * boolean value, "enable_default_themes": boolean value, "hide_ads": boolean * value, "hide_downs": boolean value, "hide_from_robots": boolean value, * "hide_locationbar": boolean value, "hide_ups": boolean value, * "highlight_controversial": boolean value, "highlight_new_comments": boolean * value, "ignore_suggested_sort": boolean value, "label_nsfw": boolean value, * "lang": a valid IETF language tag (underscore separated), "legacy_search": * boolean value, "mark_messages_read": boolean value, "media": one of (`on`, * `off`, `subreddit`), "min_comment_score": an integer between -100 and 100, * "min_link_score": an integer between -100 and 100, "monitor_mentions": boolean * value, "newwindow": boolean value, "no_profanity": boolean value, * "num_comments": an integer between 1 and 500, "numsites": an integer between 1 * and 100, "organic": boolean value, "other_theme": subreddit name, "over_18": * boolean value, "private_feeds": boolean value, "public_votes": boolean value, * "research": boolean value, "show_flair": boolean value, "show_gold_expiration": * boolean value, "show_link_flair": boolean value, "show_promote": boolean value, * "show_stylesheets": boolean value, "show_trending": boolean value, * "store_visits": boolean value, "theme_selector": subreddit name, * "threaded_messages": boolean value, "threaded_modmail": boolean value, * "use_global_defaults": boolean value, } **/ fun OAuthClient.patchV1MePrefs(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/v1/me/prefs").method("patch").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L94> * # <https://www.reddit.com/dev/api#GET_api_v1_me_trophies>GET /api/v1/me/trophies * identity <https://github.com/reddit/reddit/wiki/OAuth2> * - Return a list of trophies for the current user. **/ fun OAuthClient.getV1MeTrophies() = retry(3) { requestApi("/api/v1/me/trophies").get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818> * # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /prefs/friends * * → /prefs/blocked * * → /api/v1/me/friends * * → /api/v1/me/blockedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getPrefsWhere(where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/prefs/$where", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818> * # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /prefs/friends * * → /prefs/blocked * * → /api/v1/me/friends * * → /api/v1/me/blockedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getPrefsFriends(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/prefs/friends", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818> * # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /prefs/friends * * → /prefs/blocked * * → /api/v1/me/friends * * → /api/v1/me/blockedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getPrefsBlocked(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/prefs/blocked", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818> * # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /prefs/friends * * → /prefs/blocked * * → /api/v1/me/friends * * → /api/v1/me/blockedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getV1MeFriends(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/api/v1/me/friends", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1818> * # <https://www.reddit.com/dev/api#GET_prefs_{where}>GET /prefs/whereread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /prefs/friends * * → /prefs/blocked * * → /api/v1/me/friends * * → /api/v1/me/blockedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getV1MeBlocked(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/api/v1/me/blocked", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L335># * <https://www.reddit.com/dev/api#GET_api_needs_captcha>GET /api/needs_captchaany * <https://github.com/reddit/reddit/wiki/OAuth2> * - Check whether CAPTCHAs are needed for API methods that define the "captcha" * and "iden" parameters. **/ fun OAuthClient.getNeeds_captcha() = retry(3) { requestApi("/api/needs_captcha").get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L145># * <https://www.reddit.com/dev/api#POST_api_new_captcha>POST /api/new_captchaany * <https://github.com/reddit/reddit/wiki/OAuth2> * - Responds with an iden of a new CAPTCHA. * - Use this endpoint if a user cannot read a given CAPTCHA, and wishes to * receive a new CAPTCHA. * - To request the CAPTCHA image for an iden, use /captcha/iden * <https://www.reddit.com/dev/api#GET_captcha_%7Biden%7D>. * - api_typethe string json **/ fun OAuthClient.postNew_captcha(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/new_captcha").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/captcha.py#L32># * <https://www.reddit.com/dev/api#GET_captcha_{iden}>GET /captcha/idenany * <https://github.com/reddit/reddit/wiki/OAuth2> * - Request a CAPTCHA image given an iden. * - An iden is given as the captcha field with a BAD_CAPTCHA error, you should * use this endpoint if you get aBAD_CAPTCHA error response. * - Responds with a 120x50 image/png which should be displayed to the user. * - The user's response to the CAPTCHA should be sent as captcha along with your * request. * - To request a new CAPTCHA, use /api/new_captcha * <https://www.reddit.com/dev/api#POST_api_new_captcha>. **/ fun OAuthClient.getCaptchaIden(iden: String) = retry(3) { requestApi("/captcha/$iden").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4280># * <https://www.reddit.com/dev/api#POST_api_clearflairtemplates>POST [/r/subreddit * ]/api/clearflairtemplatesmodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - flair_typeone of (USER_FLAIR, LINK_FLAIR) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditClearflairtemplates(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/clearflairtemplates").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4022># * <https://www.reddit.com/dev/api#POST_api_deleteflair>POST [/r/subreddit * ]/api/deleteflairmodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - namea user by name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditDeleteflair(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/deleteflair").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4261># * <https://www.reddit.com/dev/api#POST_api_deleteflairtemplate>POST [/r/subreddit * ]/api/deleteflairtemplatemodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - flair_template_iduh / X-Modhash headera modhash * <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditDeleteflairtemplate(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/deleteflairtemplate").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3968># * <https://www.reddit.com/dev/api#POST_api_flair>POST [/r/subreddit]/api/flair * modflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - css_classa valid subreddit image name * - linka fullname <https://www.reddit.com/dev/api#fullname> of a link * - namea user by name * - texta string no longer than 64 characters * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditFlair(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/flair").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4127># * <https://www.reddit.com/dev/api#POST_api_flairconfig>POST [/r/subreddit * ]/api/flairconfigmodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - flair_enabledboolean value * - flair_positionone of (left, right) * - flair_self_assign_enabledboolean value * - link_flair_positionone of (`,left,right`) * - link_flair_self_assign_enabledboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditFlairconfig(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/flairconfig").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4042># * <https://www.reddit.com/dev/api#POST_api_flaircsv>POST [/r/subreddit * ]/api/flaircsvmodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - Change the flair of multiple users in the same subreddit with a single API * call. * - Requires a string 'flair_csv' which has up to 100 lines of the form 'user, * flairtext,cssclass' (Lines beyond the 100th are ignored). * - If both cssclass and flairtext are the empty string for a given user, instead * clears that user's flair. * - Returns an array of objects indicating if each flair setting was applied, or * a reason for the failure. * - flair_csvcomma-seperated flair information * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditFlaircsv(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/flaircsv").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4169># * <https://www.reddit.com/dev/api#GET_api_flairlist>GET [/r/subreddit * ]/api/flairlistmodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 1000) * - namea user by name * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditFlairlist(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, name: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/api/flairlist", "after" to after, "before" to before, "count" to count, "limit" to limit, "name" to name, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4295># * <https://www.reddit.com/dev/api#POST_api_flairselector>POST [/r/subreddit * ]/api/flairselectorflair <https://github.com/reddit/reddit/wiki/OAuth2> * - Return information about a users's flair options. * - If link is given, return link flair options. Otherwise, return user flair * options for this subreddit. * - The logged in user's flair is also returned. Subreddit moderators may give a * user byname to instead retrieve that user's flair. * - linka fullname <https://www.reddit.com/dev/api#fullname> of a link * - namea user by name **/ fun OAuthClient.postRSubredditFlairselector(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/flairselector").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4187># * <https://www.reddit.com/dev/api#POST_api_flairtemplate>POST [/r/subreddit * ]/api/flairtemplatemodflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - css_classa valid subreddit image name * - flair_template_idflair_typeone of (USER_FLAIR, LINK_FLAIR) * - texta string no longer than 64 characters * - text_editableboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditFlairtemplate(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/flairtemplate").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4341># * <https://www.reddit.com/dev/api#POST_api_selectflair>POST [/r/subreddit * ]/api/selectflairflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - flair_template_idlinka fullname <https://www.reddit.com/dev/api#fullname> of * a link * - namea user by name * - texta string no longer than 64 characters * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditSelectflair(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/selectflair").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4117># * <https://www.reddit.com/dev/api#POST_api_setflairenabled>POST [/r/subreddit * ]/api/setflairenabledflair <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - flair_enabledboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditSetflairenabled(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/setflairenabled").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/gold.py#L77> * # <https://www.reddit.com/dev/api#POST_api_v1_gold_gild_{fullname}>POST  * /api/v1/gold/gild/fullnamecreddits * <https://github.com/reddit/reddit/wiki/OAuth2> * - fullnamefullname <https://www.reddit.com/dev/api#fullnames> of a thing **/ fun OAuthClient.postV1GoldGildFullname(fullname: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/v1/gold/gild/$fullname").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/gold.py#L102> * # <https://www.reddit.com/dev/api#POST_api_v1_gold_give_{username}>POST  * /api/v1/gold/give/usernamecreddits * <https://github.com/reddit/reddit/wiki/OAuth2> * - monthsan integer between 1 and 36 * - usernameA valid, existing reddit username **/ fun OAuthClient.postV1GoldGiveUsername(username: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/v1/gold/give/$username").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2060># * <https://www.reddit.com/dev/api#POST_api_comment>POST /api/commentany * <https://github.com/reddit/reddit/wiki/OAuth2> * - Submit a new comment or reply to a message. * - parent is the fullname of the thing being replied to. Its value changes the * kind of object created by this request: * * the fullname of a Link: a top-level comment in that Link's thread. (requires * submit scope) * * the fullname of a Comment: a comment reply to that comment. (requires submit * scope) * * the fullname of a Message: a message reply to that message. (requires * privatemessages scope) text should be the raw markdown body of the comment or * message. * - To start a new message thread, use /api/compose * <https://www.reddit.com/dev/api#POST_api_compose>. * - api_typethe string json * - textraw markdown text * - thing_idfullname <https://www.reddit.com/dev/api#fullnames> of parent thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postComment(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/comment").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1491># * <https://www.reddit.com/dev/api#POST_api_del>POST /api/deledit * <https://github.com/reddit/reddit/wiki/OAuth2> * - Delete a Link or Comment. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing created by * the user * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postDel(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/del").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1975># * <https://www.reddit.com/dev/api#POST_api_editusertext>POST /api/editusertextedit * <https://github.com/reddit/reddit/wiki/OAuth2> * - Edit the body text of a comment or self-post. * - api_typethe string json * - textraw markdown text * - thing_idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * created by the user * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postEditusertext(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/editusertext").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3472># * <https://www.reddit.com/dev/api#POST_api_hide>POST /api/hidereport * <https://github.com/reddit/reddit/wiki/OAuth2> * - Hide a link. * - This removes it from the user's default view of subreddit listings. * - See also: /api/unhide <https://www.reddit.com/dev/api#POST_api_unhide>. * - idA comma-separated list of link fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postHide(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/hide").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L173># * <https://www.reddit.com/dev/api#GET_api_info>GET [/r/subreddit]/api/inforead * <https://github.com/reddit/reddit/wiki/OAuth2> * - Return a listing of things specified by their fullnames. * - Only Links, Comments, and Subreddits are allowed. * - idA comma-separated list of thing fullnames * <https://www.reddit.com/dev/api#fullnames> * - urla valid URL **/ fun OAuthClient.getRSubredditInfo(subreddit: String, id: List<String>?, url: String?) = retry(3) { requestApi("/r/$subreddit/api/info", "id" to id.csv(), "url" to url).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1522># * <https://www.reddit.com/dev/api#POST_api_lock>POST /api/lockmodposts * <https://github.com/reddit/reddit/wiki/OAuth2> * - Lock a link. * - Prevents a post from receiving new comments. * - See also: /api/unlock <https://www.reddit.com/dev/api#POST_api_unlock>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a link * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLock(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/lock").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1568># * <https://www.reddit.com/dev/api#POST_api_marknsfw>POST /api/marknsfwmodposts * <https://github.com/reddit/reddit/wiki/OAuth2> * - Mark a link NSFW. * - See also: /api/unmarknsfw <https://www.reddit.com/dev/api#POST_api_unmarknsfw> * . * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postMarknsfw(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/marknsfw").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3535># * <https://www.reddit.com/dev/api#GET_api_morechildren>GET /api/morechildrenread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve additional comments omitted from a base comment tree. * - When a comment tree is rendered, the most relevant comments are selected for * display first. Remaining comments are stubbed out with "MoreComments" links. * This API call is used to retrieve the additional comments represented by those * stubs, up to 20 at a time. * - The two core parameters required are link and children. link is the fullname * of the link whose comments are being fetched.children is a comma-delimited list * of comment ID36s that need to be fetched. * - If id is passed, it should be the ID of the MoreComments object this call is * replacing. This is needed only for the HTML UI's purposes and is optional * otherwise. * - NOTE: you may only make one request at a time to this API endpoint. Higher * concurrency will result in an error being returned. * - api_typethe string json * - childrena comma-delimited list of comment ID36s * - id(optional) id of the associated MoreChildren object * - link_idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - sortone of (confidence, top, new, controversial, old, random, qa) **/ fun OAuthClient.getMorechildren(apiType: String?, children: List<String>?, id: String?, linkId: String?, sort: String?) = retry(3) { requestApi("/api/morechildren", "api_type" to apiType, "children" to children.csv(), "id" to id, "link_id" to linkId, "sort" to sort).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1749># * <https://www.reddit.com/dev/api#POST_api_report>POST /api/reportreport * <https://github.com/reddit/reddit/wiki/OAuth2> * - Report a link, comment or message. * - Reporting a thing brings it to the attention of the subreddit's moderators. * Reporting a message sends it to a system for admin review. * - For links and comments, the thing is implicitly hidden as well (see /api/hide * <https://www.reddit.com/dev/api#POST_api_hide> for details). * - api_typethe string json * - other_reasona string no longer than 100 characters * - reasona string no longer than 100 characters * - site_reasona string no longer than 100 characters * - thing_idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postReport(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/report").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3340># * <https://www.reddit.com/dev/api#POST_api_save>POST /api/savesave * <https://github.com/reddit/reddit/wiki/OAuth2> * - Save a link or comment. * - Saved things are kept in the user's saved listing for later perusal. * - See also: /api/unsave <https://www.reddit.com/dev/api#POST_api_unsave>. * - categorya category name * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postSave(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/save").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3323># * <https://www.reddit.com/dev/api#GET_api_saved_categories>GET  * /api/saved_categoriessave <https://github.com/reddit/reddit/wiki/OAuth2> * - Get a list of categories in which things are currently saved. * - See also: /api/save <https://www.reddit.com/dev/api#POST_api_save>. **/ fun OAuthClient.getSaved_categories() = retry(3) { requestApi("/api/saved_categories").get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1619># * <https://www.reddit.com/dev/api#POST_api_sendreplies>POST /api/sendrepliesedit * <https://github.com/reddit/reddit/wiki/OAuth2> * - Enable or disable inbox replies for a link or comment. * - state is a boolean that indicates whether you are enabling or disabling inbox * replies - true to enable, false to disable. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing created by * the user * - stateboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postSendreplies(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/sendreplies").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1680># * <https://www.reddit.com/dev/api#POST_api_set_contest_mode>POST  * /api/set_contest_modemodposts <https://github.com/reddit/reddit/wiki/OAuth2> * - Set or unset "contest mode" for a link's comments. * - state is a boolean that indicates whether you are enabling or disabling * contest mode - true to enable, false to disable. * - api_typethe string json * - idstateboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postSet_contest_mode(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/set_contest_mode").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1706># * <https://www.reddit.com/dev/api#POST_api_set_subreddit_sticky>POST  * /api/set_subreddit_stickymodposts <https://github.com/reddit/reddit/wiki/OAuth2> * - Set or unset a Link as the sticky in its subreddit. * - state is a boolean that indicates whether to sticky or unsticky this post - * true to sticky, false to unsticky. * - The num argument is optional, and only used when stickying a post. It allows * specifying a particular "slot" to sticky the post into, and if there is already * a post stickied in that slot it will be replaced. If there is no post in the * specified slot to replace, ornum is None, the bottom-most slot will be used. * - api_typethe string json * - idnuman integer between 1 and 2 * - stateboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postSet_subreddit_sticky(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/set_subreddit_sticky").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1654># * <https://www.reddit.com/dev/api#POST_api_set_suggested_sort>POST  * /api/set_suggested_sortmodposts <https://github.com/reddit/reddit/wiki/OAuth2> * - Set a suggested sort for a link. * - Suggested sorts are useful to display comments in a certain preferred way for * posts. For example, casual conversation may be better sorted by new by default, * or AMAs may be sorted by Q&A. A sort of an empty string clears the default sort. * - api_typethe string json * - idsortone of (confidence, top, new, controversial, old, random, qa, blank) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postSet_suggested_sort(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/set_suggested_sort").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L5090># * <https://www.reddit.com/dev/api#POST_api_store_visits>POST /api/store_visitssave * <https://github.com/reddit/reddit/wiki/OAuth2> * - Requires a subscription to reddit gold <https://www.reddit.com/gold/about> * - linksA comma-separated list of link fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postStore_visits(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/store_visits").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L438># * <https://www.reddit.com/dev/api#POST_api_submit>POST /api/submitsubmit * <https://github.com/reddit/reddit/wiki/OAuth2> * - Submit a link to a subreddit. * - Submit will create a link or self-post in the subreddit sr with the title * title. If kind is "link", then url is expected to be a valid URL to link to. * Otherwise,text, if present, will be the body of the self-post. * - If a link with the same URL has already been submitted to the specified * subreddit an error will be returned unlessresubmit is true. extension is used * for determining which view-type (e.g.json, compact etc.) to use for the * redirect that is generated if theresubmit error occurs. * - api_typethe string json * - captchathe user's response to the CAPTCHA challenge * - extensionextension used for redirects * - identhe identifier of the CAPTCHA challenge * - kindone of (link, self) * - resubmitboolean value * - sendrepliesboolean value * - srname of a subreddit * - textraw markdown text * - titletitle of the submission. up to 300 characters long * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - urla valid URL **/ fun OAuthClient.postSubmit(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/submit").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3490># * <https://www.reddit.com/dev/api#POST_api_unhide>POST /api/unhidereport * <https://github.com/reddit/reddit/wiki/OAuth2> * - Unhide a link. * - See also: /api/hide <https://www.reddit.com/dev/api#POST_api_hide>. * - idA comma-separated list of link fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnhide(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unhide").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1545># * <https://www.reddit.com/dev/api#POST_api_unlock>POST /api/unlockmodposts * <https://github.com/reddit/reddit/wiki/OAuth2> * - Unlock a link. * - Allow a post to receive new comments. * - See also: /api/lock <https://www.reddit.com/dev/api#POST_api_lock>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a link * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnlock(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unlock").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1589># * <https://www.reddit.com/dev/api#POST_api_unmarknsfw>POST /api/unmarknsfwmodposts * <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove the NSFW marking from a link. * - See also: /api/marknsfw <https://www.reddit.com/dev/api#POST_api_marknsfw>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnmarknsfw(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unmarknsfw").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3367># * <https://www.reddit.com/dev/api#POST_api_unsave>POST /api/unsavesave * <https://github.com/reddit/reddit/wiki/OAuth2> * - Unsave a link or comment. * - This removes the thing from the user's saved listings as well. * - See also: /api/save <https://www.reddit.com/dev/api#POST_api_save>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnsave(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unsave").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2308># * <https://www.reddit.com/dev/api#POST_api_vote>POST /api/votevote * <https://github.com/reddit/reddit/wiki/OAuth2> * - Cast a vote on a thing. * - id should be the fullname of the Link or Comment to vote on. * - dir indicates the direction of the vote. Voting 1 is an upvote, -1 is a * downvote, and0 is equivalent to "un-voting" by clicking again on a highlighted * arrow. * - Note: votes must be cast by humans. That is, API clients proxying a human's * action one-for-one are OK, but bots deciding how to vote on content or * amplifying a human's vote are not. Seethe reddit rules * <https://www.reddit.com/rules> for more details on what constitutes vote * cheating. * - dirvote direction. one of (1, 0, -1) * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - rankan integer greater than 1 * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postVote(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/vote").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L715> * # <https://www.reddit.com/dev/api#GET_by_id_{names}>GET /by_id/namesread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Get a listing of links by fullname. * - names is a list of fullnames for links separated by commas or spaces. * - namesA comma-separated list of link fullnames * <https://www.reddit.com/dev/api#fullnames> **/ fun OAuthClient.getBy_idNames(names: List<String>) = retry(3) { requestApi("/by_id/$names", "names" to names.csv()).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L214># * <https://www.reddit.com/dev/api#GET_comments_{article}>GET [/r/subreddit * ]/comments/articleread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Get the comment tree for a given Link article. * - If supplied, comment is the ID36 of a comment in the comment tree for article * . This comment will be the (highlighted) focal point of the returned view and * context will be the number of parents shown. * - depth is the maximum depth of subtrees in the thread. * - limit is the maximum number of comments to return. * - See also: /api/morechildren * <https://www.reddit.com/dev/api#GET_api_morechildren> and /api/comment * <https://www.reddit.com/dev/api#POST_api_comment>. * - articleID36 of a link * - comment(optional) ID36 of a comment * - contextan integer between 0 and 8 * - depth(optional) an integer * - limit(optional) an integer * - showeditsboolean value * - showmoreboolean value * - sortone of (confidence, top, new, controversial, old, random, qa) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditCommentsArticle(subreddit: String, article: String, comment: String?, context: String?, depth: String?, limit: String?, showedits: String?, showmore: String?, sort: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/comments/$article", "article" to article, "comment" to comment, "context" to context, "depth" to depth, "limit" to limit, "showedits" to showedits, "showmore" to showmore, "sort" to sort, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L1004># * <https://www.reddit.com/dev/api#GET_duplicates_{article}>GET /duplicates/ * articleread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Return a list of other submissions of the same URL * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - articleThe base 36 ID of a Link * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getDuplicatesArticle(article: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/duplicates/$article", "after" to after, "article" to article, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L543> * # <https://www.reddit.com/dev/api#GET_hot>GET [/r/subreddit]/hotread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditHot(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/hot", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L572> * # <https://www.reddit.com/dev/api#GET_new>GET [/r/subreddit]/newread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditNew(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/new", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L128># * <https://www.reddit.com/dev/api#GET_random>GET [/r/subreddit]/randomread * <https://github.com/reddit/reddit/wiki/OAuth2> * - The Serendipity button **/ fun OAuthClient.getRSubredditRandom(subreddit: String) = retry(3) { requestApi("/r/$subreddit/random").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L625> * # <https://www.reddit.com/dev/api#GET_{sort}>GET [/r/subreddit]/sortread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/top * * → [/r/subreddit]/controversialThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - tone of (hour, day, week, month, year, all) * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditSort(subreddit: String, sort: String, t: String?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/$sort", "t" to t, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L625> * # <https://www.reddit.com/dev/api#GET_{sort}>GET [/r/subreddit]/sortread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/top * * → [/r/subreddit]/controversialThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - tone of (hour, day, week, month, year, all) * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditTop(subreddit: String, t: String?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/top", "t" to t, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L625> * # <https://www.reddit.com/dev/api#GET_{sort}>GET [/r/subreddit]/sortread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/top * * → [/r/subreddit]/controversialThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - tone of (hour, day, week, month, year, all) * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditControversial(subreddit: String, t: String?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/controversial", "t" to t, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * Real-time updates on reddit. * - In addition to the standard reddit API, WebSockets play a huge role in reddit * live. Receiving push notification of changes to the thread via websockets is * much better than polling the thread repeatedly. * - To connect to the websocket server, fetch /live/thread/about.json * <https://www.reddit.com/dev/api#GET_live_%7Bthread%7D_about.json> and get the * websocket_url field. The websocket URL expires after a period of time; if it * does, fetch a new one from that endpoint. * - Once connected to the socket, a variety of messages can come in. All messages * will be in text frames containing a JSON object with two keys:type and payload. * Live threads can send messages with manytypes: * * update - a new update has been posted in the thread. the payload contains * the JSON representation of the update. * * activity - periodic update of the viewer counts for the thread. * * settings - the thread's settings have changed. the payload is an object * with each key being a property of the thread (as inabout.json) and its new * value. * * delete - an update has been deleted (removed from the thread). the payload * is the ID of the deleted update. * * strike - an update has been stricken (marked incorrect and crossed out). the * payload is the ID of the stricken update. * * embeds_ready - a previously posted update has been parsed and embedded * media is available for it now. thepayload contains a liveupdate_id and list of * embeds to add to it. * * complete - the thread has been marked complete. no further updates will be * sent. See /r/live <https://www.reddit.com/r/live> for more information. **/ fun OAuthClient.get() = retry(3) { requestApi("").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L1015> * # <https://www.reddit.com/dev/api#POST_api_live_create>POST /api/live/create * submit <https://github.com/reddit/reddit/wiki/OAuth2> * - Create a new live thread. * - Once created, the initial settings can be modified with /api/live/thread/edit * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_edit> and new * updates can be posted with/api/live/thread/update * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>. * - api_typethe string json * - descriptionraw markdown text * - nsfwboolean value * - resourcesraw markdown text * - titlea string no longer than 120 characters * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveCreate(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/create").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L620> * # * <https://www.reddit.com/dev/api#POST_api_live_{thread}_accept_contributor_invite> * POST /api/live/thread/accept_contributor_invitelivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Accept a pending invitation to contribute to the thread. * - See also: /api/live/thread/leave_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_leave_contributor>. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadAccept_contributor_invite(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/accept_contributor_invite").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L828> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_close_thread>POST  * /api/live/thread/close_threadlivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Permanently close the thread, disallowing future updates. * - Requires the close permission for this thread. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadClose_thread(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/close_thread").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L770> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_delete_update>POST  * /api/live/thread/delete_updateedit * <https://github.com/reddit/reddit/wiki/OAuth2> * - Delete an update from the thread. * - Requires that specified update must have been authored by the user or that * you have theedit permission for this thread. * - See also: /api/live/thread/update * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>. * - api_typethe string json * - idthe ID of a single update. e.g. * LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603 * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadDelete_update(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/delete_update").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L427> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_edit>POST /api/live/ * thread/editlivemanage <https://github.com/reddit/reddit/wiki/OAuth2> * - Configure the thread. * - Requires the settings permission for this thread. * - See also: /live/thread/about.json * <https://www.reddit.com/dev/api#GET_live_%7Bthread%7D_about.json>. * - api_typethe string json * - descriptionraw markdown text * - nsfwboolean value * - resourcesraw markdown text * - titlea string no longer than 120 characters * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadEdit(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/edit").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L517> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_invite_contributor> * POST /api/live/thread/invite_contributorlivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Invite another user to contribute to the thread. * - Requires the manage permission for this thread. If the recipient accepts the * invite, they will be granted the permissions specified. * - See also: /api/live/thread/accept_contributor_invite * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_accept_contributor_invite> * , and/api/live/thread/rm_contributor_invite * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_rm_contributor_invite> * . * - api_typethe string json * - namethe name of an existing user * - permissionspermission description e.g. +update,+edit,-manage * - typeone of (liveupdate_contributor_invite, liveupdate_contributor) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadInvite_contributor(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/invite_contributor").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L580> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_leave_contributor>POST  * /api/live/thread/leave_contributorlivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Abdicate contributorship of the thread. * - See also: /api/live/thread/accept_contributor_invite * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_accept_contributor_invite> * , and/api/live/thread/invite_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadLeave_contributor(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/leave_contributor").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L851> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_report>POST /api/live/ * thread/reportreport <https://github.com/reddit/reddit/wiki/OAuth2> * - Report the thread for violating the rules of reddit. * - api_typethe string json * - typeone of (spam, vote-manipulation, personal-information, sexualizing-minors, * site-breaking) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadReport(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/report").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L702> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_rm_contributor>POST  * /api/live/thread/rm_contributorlivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Revoke another user's contributorship. * - Requires the manage permission for this thread. * - See also: /api/live/thread/invite_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>. * - api_typethe string json * - idfullname <https://www.reddit.com/dev/api#fullnames> of a account * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadRm_contributor(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/rm_contributor").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L599> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_rm_contributor_invite> * POST /api/live/thread/rm_contributor_invitelivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Revoke an outstanding contributor invite. * - Requires the manage permission for this thread. * - See also: /api/live/thread/invite_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>. * - api_typethe string json * - idfullname <https://www.reddit.com/dev/api#fullnames> of a account * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadRm_contributor_invite(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/rm_contributor_invite").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L649> * # * <https://www.reddit.com/dev/api#POST_api_live_{thread}_set_contributor_permissions> * POST /api/live/thread/set_contributor_permissionslivemanage * <https://github.com/reddit/reddit/wiki/OAuth2> * - Change a contributor or contributor invite's permissions. * - Requires the manage permission for this thread. * - See also: /api/live/thread/invite_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor> * and/api/live/thread/rm_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_rm_contributor>. * - api_typethe string json * - namethe name of an existing user * - permissionspermission description e.g. +update,+edit,-manage * - typeone of (liveupdate_contributor_invite, liveupdate_contributor) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadSet_contributor_permissions(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/set_contributor_permissions").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L799> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_strike_update>POST  * /api/live/thread/strike_updateedit * <https://github.com/reddit/reddit/wiki/OAuth2> * - Strike (mark incorrect and cross out) the content of an update. * - Requires that specified update must have been authored by the user or that * you have theedit permission for this thread. * - See also: /api/live/thread/update * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>. * - api_typethe string json * - idthe ID of a single update. e.g. * LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603 * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadStrike_update(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/strike_update").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L722> * # <https://www.reddit.com/dev/api#POST_api_live_{thread}_update>POST /api/live/ * thread/updatesubmit <https://github.com/reddit/reddit/wiki/OAuth2> * - Post an update to the thread. * - Requires the update permission for this thread. * - See also: /api/live/thread/strike_update * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_strike_update>, and * /api/live/thread/delete_update * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_delete_update>. * - api_typethe string json * - bodyraw markdown text * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLiveThreadUpdate(thread: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/live/$thread/update").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L259> * # <https://www.reddit.com/dev/api#GET_live_{thread}>GET /live/threadread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Get a list of updates posted in this thread. * - See also: /api/live/thread/update * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_update>. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterthe ID of a single update. e.g. * LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603 * - beforethe ID of a single update. e.g. * LiveUpdate_ff87068e-a126-11e3-9f93-12313b0b3603 * - counta positive integer (default: 0) * - is_embed(internal use only) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - stylesrsubreddit name **/ fun OAuthClient.getLiveThread(thread: String, after: String?, before: String?, count: Int?, isEmbed: String?, limit: Int?, stylesr: String?) = retry(3) { requestApi("/live/$thread", "after" to after, "before" to before, "count" to count, "is_embed" to isEmbed, "limit" to limit, "stylesr" to stylesr).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L382> * # <https://www.reddit.com/dev/api#GET_live_{thread}_about>GET /live/thread/about * read <https://github.com/reddit/reddit/wiki/OAuth2> * - Get some basic information about the live thread. * - See also: /api/live/thread/edit * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_edit>. **/ fun OAuthClient.getLiveThreadAbout(thread: String) = retry(3) { requestApi("/live/$thread/about").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L472> * # <https://www.reddit.com/dev/api#GET_live_{thread}_contributors>GET /live/ * thread/contributorsread <https://github.com/reddit/reddit/wiki/OAuth2> * - Get a list of users that contribute to this thread. * - See also: /api/live/thread/invite_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_invite_contributor>, * and/api/live/thread/rm_contributor * <https://www.reddit.com/dev/api#POST_api_live_%7Bthread%7D_rm_contributor>. **/ fun OAuthClient.getLiveThreadContributors(thread: String) = retry(3) { requestApi("/live/$thread/contributors").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit-plugin-liveupdate/blob/master/reddit_liveupdate/controllers.py#L398> * # <https://www.reddit.com/dev/api#GET_live_{thread}_discussions>GET /live/thread * /discussionsread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Get a list of reddit submissions linking to this thread. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getLiveThreadDiscussions(thread: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/live/$thread/discussions", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1842># * <https://www.reddit.com/dev/api#POST_api_block>POST /api/blockprivatemessages * <https://github.com/reddit/reddit/wiki/OAuth2> * - For blocking via inbox. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postBlock(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/block").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3403># * <https://www.reddit.com/dev/api#POST_api_collapse_message>POST  * /api/collapse_message * - Collapse a message * - See also: /api/uncollapse_message * <https://www.reddit.com/dev/api#POST_uncollapse_message> * - idA comma-separated list of thing fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postCollapse_message(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/collapse_message").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L345># * <https://www.reddit.com/dev/api#POST_api_compose>POST /api/compose * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2> * - Handles message composition under /message/compose. * - api_typethe string json * - captchathe user's response to the CAPTCHA challenge * - from_srsubreddit name * - identhe identifier of the CAPTCHA challenge * - subjecta string no longer than 100 characters * - textraw markdown text * - tothe name of an existing user * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postCompose(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/compose").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3455># * <https://www.reddit.com/dev/api#POST_api_read_all_messages>POST  * /api/read_all_messagesprivatemessages * <https://github.com/reddit/reddit/wiki/OAuth2> * - Queue up marking all messages for a user as read. * - This may take some time, and returns 202 to acknowledge acceptance of the * request. * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRead_all_messages(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/read_all_messages").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3441># * <https://www.reddit.com/dev/api#POST_api_read_message>POST /api/read_message * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2> * - idA comma-separated list of thing fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRead_message(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/read_message").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1881># * <https://www.reddit.com/dev/api#POST_api_unblock_subreddit>POST  * /api/unblock_subredditprivatemessages * <https://github.com/reddit/reddit/wiki/OAuth2> * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnblock_subreddit(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unblock_subreddit").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3415># * <https://www.reddit.com/dev/api#POST_api_uncollapse_message>POST  * /api/uncollapse_message * - Uncollapse a message * - See also: /api/collapse_message * <https://www.reddit.com/dev/api#POST_collapse_message> * - idA comma-separated list of thing fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUncollapse_message(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/uncollapse_message").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3427># * <https://www.reddit.com/dev/api#POST_api_unread_message>POST /api/unread_message * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2> * - idA comma-separated list of thing fullnames * <https://www.reddit.com/dev/api#fullnames> * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnread_message(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unread_message").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299> * # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /message/inbox * * → /message/unread * * → /message/sentThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - markone of (true, false) * - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getMessageWhere(where: String, mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/message/$where", "mark" to mark, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299> * # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /message/inbox * * → /message/unread * * → /message/sentThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - markone of (true, false) * - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getMessageInbox(mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/message/inbox", "mark" to mark, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299> * # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /message/inbox * * → /message/unread * * → /message/sentThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - markone of (true, false) * - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getMessageUnread(mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/message/unread", "mark" to mark, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1299> * # <https://www.reddit.com/dev/api#GET_message_{where}>GET /message/where * privatemessages <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /message/inbox * * → /message/unread * * → /message/sentThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - markone of (true, false) * - midafterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getMessageSent(mark: Boolean?, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/message/sent", "mark" to mark, "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/scopes.py#L34> * # <https://www.reddit.com/dev/api#GET_api_v1_scopes>GET /api/v1/scopesany * <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve descriptions of reddit's OAuth2 scopes. * - If no scopes are given, information on all scopes are returned. * - Invalid scope(s) will result in a 400 error with body that indicates the * invalid scope(s). * - scopes(optional) An OAuth2 scope string **/ fun OAuthClient.getV1Scopes(scopes: String?) = retry(3) { requestApi("/api/v1/scopes", "scopes" to scopes).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L593># * <https://www.reddit.com/dev/api#GET_about_log>GET [/r/subreddit]/about/logmodlog * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Get a list of recent moderation actions. * - Moderator actions taken within a subreddit are logged. This listing is a view * of that log with various filters to aid in analyzing the information. * - The optional mod parameter can be a comma-delimited list of moderator names * to restrict the results to, or the stringa to restrict the results to admin * actions taken within the subreddit. * - The type parameter is optional and if sent limits the log entries returned to * only those of the type specified. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 500) * - mod(optional) a moderator filter * - show(optional) the string all * - sr_detail(optional) expand subreddits * - typeone of (banuser, unbanuser, removelink, approvelink, removecomment, * approvecomment, addmoderator, invitemoderator, uninvitemoderator, * acceptmoderatorinvite, removemoderator, addcontributor, removecontributor, * editsettings, editflair, distinguish, marknsfw, wikibanned, wikicontributor, * wikiunbanned, wikipagelisted, removewikicontributor, wikirevise, wikipermlevel, * ignorereports, unignorereports, setpermissions, setsuggestedsort, sticky, * unsticky, setcontestmode, unsetcontestmode, lock, unlock, muteuser, unmuteuser, * createrule, editrule, deleterule) **/ fun OAuthClient.getRSubredditAboutLog(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, mod: String?, show: String?, srDetail: Boolean?, type: String?) = retry(3) { requestApi("/r/$subreddit/about/log", "after" to after, "before" to before, "count" to count, "limit" to limit, "mod" to mod, "show" to show, "sr_detail" to srDetail, "type" to type).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818># * <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/ * locationread <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/about/reports * * → [/r/subreddit]/about/spam * * → [/r/subreddit]/about/modqueue * * → [/r/subreddit]/about/unmoderated * * → [/r/subreddit]/about/editedReturn a listing of posts relevant to * moderators. * * reports: Things that have been reported. * * spam: Things that have been marked as spam or otherwise removed. * * modqueue: Things requiring moderator review, such as reported things and * items caught by the spam filter. * * unmoderated: Things that have yet to be approved/removed by a mod. * * edited: Things that have been edited recently. Requires the "posts" * moderator permission for the subreddit. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - locationonlyone of (links, comments) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditAboutLocation(subreddit: String, location: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/$location", "after" to after, "before" to before, "count" to count, "limit" to limit, "only" to only, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818># * <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/ * locationread <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/about/reports * * → [/r/subreddit]/about/spam * * → [/r/subreddit]/about/modqueue * * → [/r/subreddit]/about/unmoderated * * → [/r/subreddit]/about/editedReturn a listing of posts relevant to * moderators. * * reports: Things that have been reported. * * spam: Things that have been marked as spam or otherwise removed. * * modqueue: Things requiring moderator review, such as reported things and * items caught by the spam filter. * * unmoderated: Things that have yet to be approved/removed by a mod. * * edited: Things that have been edited recently. Requires the "posts" * moderator permission for the subreddit. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - locationonlyone of (links, comments) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditAboutReports(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/reports", "after" to after, "before" to before, "count" to count, "limit" to limit, "only" to only, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818># * <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/ * locationread <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/about/reports * * → [/r/subreddit]/about/spam * * → [/r/subreddit]/about/modqueue * * → [/r/subreddit]/about/unmoderated * * → [/r/subreddit]/about/editedReturn a listing of posts relevant to * moderators. * * reports: Things that have been reported. * * spam: Things that have been marked as spam or otherwise removed. * * modqueue: Things requiring moderator review, such as reported things and * items caught by the spam filter. * * unmoderated: Things that have yet to be approved/removed by a mod. * * edited: Things that have been edited recently. Requires the "posts" * moderator permission for the subreddit. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - locationonlyone of (links, comments) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditAboutSpam(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/spam", "after" to after, "before" to before, "count" to count, "limit" to limit, "only" to only, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818># * <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/ * locationread <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/about/reports * * → [/r/subreddit]/about/spam * * → [/r/subreddit]/about/modqueue * * → [/r/subreddit]/about/unmoderated * * → [/r/subreddit]/about/editedReturn a listing of posts relevant to * moderators. * * reports: Things that have been reported. * * spam: Things that have been marked as spam or otherwise removed. * * modqueue: Things requiring moderator review, such as reported things and * items caught by the spam filter. * * unmoderated: Things that have yet to be approved/removed by a mod. * * edited: Things that have been edited recently. Requires the "posts" * moderator permission for the subreddit. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - locationonlyone of (links, comments) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditAboutModqueue(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/modqueue", "after" to after, "before" to before, "count" to count, "limit" to limit, "only" to only, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818># * <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/ * locationread <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/about/reports * * → [/r/subreddit]/about/spam * * → [/r/subreddit]/about/modqueue * * → [/r/subreddit]/about/unmoderated * * → [/r/subreddit]/about/editedReturn a listing of posts relevant to * moderators. * * reports: Things that have been reported. * * spam: Things that have been marked as spam or otherwise removed. * * modqueue: Things requiring moderator review, such as reported things and * items caught by the spam filter. * * unmoderated: Things that have yet to be approved/removed by a mod. * * edited: Things that have been edited recently. Requires the "posts" * moderator permission for the subreddit. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - locationonlyone of (links, comments) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditAboutUnmoderated(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/unmoderated", "after" to after, "before" to before, "count" to count, "limit" to limit, "only" to only, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L818># * <https://www.reddit.com/dev/api#GET_about_{location}>GET [/r/subreddit]/about/ * locationread <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/about/reports * * → [/r/subreddit]/about/spam * * → [/r/subreddit]/about/modqueue * * → [/r/subreddit]/about/unmoderated * * → [/r/subreddit]/about/editedReturn a listing of posts relevant to * moderators. * * reports: Things that have been reported. * * spam: Things that have been marked as spam or otherwise removed. * * modqueue: Things requiring moderator review, such as reported things and * items caught by the spam filter. * * unmoderated: Things that have yet to be approved/removed by a mod. * * edited: Things that have been edited recently. Requires the "posts" * moderator permission for the subreddit. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - locationonlyone of (links, comments) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditAboutEdited(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, only: String?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/edited", "after" to after, "before" to before, "count" to count, "limit" to limit, "only" to only, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1317># * <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>POST [/r/ * subreddit]/api/accept_moderator_invitemodself * <https://github.com/reddit/reddit/wiki/OAuth2> * - Accept an invite to moderate the specified subreddit. * - The authenticated user must have been invited to moderate the subreddit by * one of its current moderators. * - See also: /api/friend <https://www.reddit.com/dev/api#POST_api_friend> and * /subreddits/mine * <https://www.reddit.com/dev/api#GET_subreddits_mine_%7Bwhere%7D>. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditAccept_moderator_invite(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/accept_moderator_invite").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3096># * <https://www.reddit.com/dev/api#POST_api_approve>POST /api/approvemodposts * <https://github.com/reddit/reddit/wiki/OAuth2> * - Approve a link or comment. * - If the thing was removed, it will be re-inserted into appropriate listings. * Any reports on the approved thing will be discarded. * - See also: /api/remove <https://www.reddit.com/dev/api#POST_api_remove>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postApprove(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/approve").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3192># * <https://www.reddit.com/dev/api#POST_api_distinguish>POST /api/distinguish * modposts <https://github.com/reddit/reddit/wiki/OAuth2> * - Distinguish a thing's author with a sigil. * - This can be useful to draw attention to and confirm the identity of the user * in the context of a link or comment of theirs. The options for distinguish are * as follows: * * yes - add a moderator distinguish ([M]). only if the user is a moderator of * the subreddit the thing is in. * * no - remove any distinguishes. * * admin - add an admin distinguish ([A]). admin accounts only. * * special - add a user-specific distinguish. depends on user. The first time * a top-level comment is moderator distinguished, the author of the link the * comment is in reply to will get a notification in their inbox. * - api_typethe string json * - howone of (yes, no, admin, special) * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postDistinguish(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/distinguish").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3140># * <https://www.reddit.com/dev/api#POST_api_ignore_reports>POST /api/ignore_reports * modposts <https://github.com/reddit/reddit/wiki/OAuth2> * - Prevent future reports on a thing from causing notifications. * - Any reports made about a thing after this flag is set on it will not cause * notifications or make the thing show up in the various moderation listings. * - See also: /api/unignore_reports * <https://www.reddit.com/dev/api#POST_api_unignore_reports>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postIgnore_reports(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/ignore_reports").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L812># * <https://www.reddit.com/dev/api#POST_api_leavecontributor>POST  * /api/leavecontributormodself <https://github.com/reddit/reddit/wiki/OAuth2> * - Abdicate approved submitter status in a subreddit. * - See also: /api/friend <https://www.reddit.com/dev/api#POST_api_friend>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLeavecontributor(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/leavecontributor").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L796># * <https://www.reddit.com/dev/api#POST_api_leavemoderator>POST /api/leavemoderator * modself <https://github.com/reddit/reddit/wiki/OAuth2> * - Abdicate moderator status in a subreddit. * - See also: /api/friend <https://www.reddit.com/dev/api#POST_api_friend>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postLeavemoderator(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/leavemoderator").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1901># * <https://www.reddit.com/dev/api#POST_api_mute_message_author>POST  * /api/mute_message_authormodcontributors * <https://github.com/reddit/reddit/wiki/OAuth2> * - For muting user via modmail. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postMute_message_author(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/mute_message_author").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3034># * <https://www.reddit.com/dev/api#POST_api_remove>POST /api/removemodposts * <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove a link, comment, or modmail message. * - If the thing is a link, it will be removed from all subreddit listings. If * the thing is a comment, it will be redacted and removed from all subreddit * comment listings. * - See also: /api/approve <https://www.reddit.com/dev/api#POST_api_approve>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - spamboolean value * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRemove(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/remove").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3168># * <https://www.reddit.com/dev/api#POST_api_unignore_reports>POST  * /api/unignore_reportsmodposts <https://github.com/reddit/reddit/wiki/OAuth2> * - Allow future reports on a thing to cause notifications. * - See also: /api/ignore_reports * <https://www.reddit.com/dev/api#POST_api_ignore_reports>. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnignore_reports(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unignore_reports").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1945># * <https://www.reddit.com/dev/api#POST_api_unmute_message_author>POST  * /api/unmute_message_authormodcontributors * <https://github.com/reddit/reddit/wiki/OAuth2> * - For unmuting user via modmail. * - idfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postUnmute_message_author(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/unmute_message_author").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L556># * <https://www.reddit.com/dev/api#GET_stylesheet>GET [/r/subreddit]/stylesheet * modconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Redirect to the subreddit's stylesheet if one exists. * - See also: /api/subreddit_stylesheet * <https://www.reddit.com/dev/api#POST_api_subreddit_stylesheet>. **/ fun OAuthClient.getRSubredditStylesheet(subreddit: String) = retry(3) { requestApi("/r/$subreddit/stylesheet").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L285># * <https://www.reddit.com/dev/api#POST_api_multi_copy>POST /api/multi/copy * subscribe <https://github.com/reddit/reddit/wiki/OAuth2> * - Copy a multi. * - Responds with 409 Conflict if the target already exists. * - A "copied from ..." line will automatically be appended to the description. * - display_namea string no longer than 50 characters * - frommultireddit url path * - todestination multireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postMultiCopy(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/copy").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L115># * <https://www.reddit.com/dev/api#GET_api_multi_mine>GET /api/multi/mineread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Fetch a list of multis belonging to the current user. * - expand_srsboolean value **/ fun OAuthClient.getMultiMine(expandSrs: String?) = retry(3) { requestApi("/api/multi/mine", "expand_srs" to expandSrs).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L334># * <https://www.reddit.com/dev/api#POST_api_multi_rename>POST /api/multi/rename * subscribe <https://github.com/reddit/reddit/wiki/OAuth2> * - Rename a multi. * - display_namea string no longer than 50 characters * - frommultireddit url path * - todestination multireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postMultiRename(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/rename").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L104># * <https://www.reddit.com/dev/api#GET_api_multi_user_{username}>GET  * /api/multi/user/usernameread <https://github.com/reddit/reddit/wiki/OAuth2> * - Fetch a list of public multis belonging to username * - expand_srsboolean value * - usernameA valid, existing reddit username **/ fun OAuthClient.getMultiUserUsername(username: String, expandSrs: String?) = retry(3) { requestApi("/api/multi/user/$username", "expand_srs" to expandSrs, "username" to username).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L255># * <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}>DELETE /api/multi/ * multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathDelete a multi. * - multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - expand_srsboolean value **/ fun OAuthClient.deleteMultiMultipath(multipath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/$multipath").method("delete").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L255># * <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}>DELETE /api/multi/ * multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathDelete a multi. * - multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - expand_srsboolean value **/ fun OAuthClient.deleteFilterFilterpath(filterpath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/filter/$filterpath").method("delete").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L127># * <https://www.reddit.com/dev/api#GET_api_multi_{multipath}>GET /api/multi/ * multipathread <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathFetch a multi's data and subreddit list by name. * - expand_srsboolean value * - multipathmultireddit url path **/ fun OAuthClient.getMultiMultipath(multipath: String, expandSrs: String?) = retry(3) { requestApi("/api/multi/$multipath", "expand_srs" to expandSrs, "multipath" to multipath).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L127># * <https://www.reddit.com/dev/api#GET_api_multi_{multipath}>GET /api/multi/ * multipathread <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathFetch a multi's data and subreddit list by name. * - expand_srsboolean value * - multipathmultireddit url path **/ fun OAuthClient.getFilterFilterpath(filterpath: String, expandSrs: String?, multipath: String?) = retry(3) { requestApi("/api/filter/$filterpath", "expand_srs" to expandSrs, "multipath" to multipath).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L199># * <https://www.reddit.com/dev/api#POST_api_multi_{multipath}>POST /api/multi/ * multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathCreate a multi. Responds with 409 Conflict if it * already exists. * - modeljson data: * - { "description_md": raw markdown text, "display_name": a string no longer * than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`, * `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and * drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`, * `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`, * `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`, * ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`, * "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of * (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`, * `fresh`), } multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - expand_srsboolean value **/ fun OAuthClient.postMultiMultipath(multipath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/$multipath").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L199># * <https://www.reddit.com/dev/api#POST_api_multi_{multipath}>POST /api/multi/ * multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathCreate a multi. Responds with 409 Conflict if it * already exists. * - modeljson data: * - { "description_md": raw markdown text, "display_name": a string no longer * than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`, * `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and * drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`, * `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`, * `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`, * ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`, * "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of * (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`, * `fresh`), } multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - expand_srsboolean value **/ fun OAuthClient.postFilterFilterpath(filterpath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/filter/$filterpath").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L233># * <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}>PUT /api/multi/ * multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathCreate or update a multi. * - modeljson data: * - { "description_md": raw markdown text, "display_name": a string no longer * than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`, * `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and * drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`, * `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`, * `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`, * ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`, * "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of * (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`, * `fresh`), } multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - expand_srsboolean value **/ fun OAuthClient.putMultiMultipath(multipath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/$multipath").method("put").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L233># * <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}>PUT /api/multi/ * multipathsubscribe <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpathCreate or update a multi. * - modeljson data: * - { "description_md": raw markdown text, "display_name": a string no longer * than 50 characters, "icon_name": one of (`art and design`, `ask`, `books`, * `business`, `cars`, `comics`, `cute animals`, `diy`, `entertainment`, `food and * drink`, `funny`, `games`, `grooming`, `health`, `life advice`, `military`, * `models pinup`, `music`, `news`, `philosophy`, `pictures and gifs`, `science`, * `shopping`, `sports`, `style`, `tech`, `travel`, `unusual stories`, `video`, * ``, `None`), "key_color": a 6-digit rgb hex color, e.g. `#AABBCC`, * "subreddits": [ { "name": subreddit name, }, ... ], "visibility": one of * (`private`, `public`, `hidden`), "weighting_scheme": one of (`classic`, * `fresh`), } multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - expand_srsboolean value **/ fun OAuthClient.putFilterFilterpath(filterpath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/filter/$filterpath").method("put").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L427># * <https://www.reddit.com/dev/api#GET_api_multi_{multipath}_description>GET  * /api/multi/multipath/descriptionread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Get a multi's description. * - multipathmultireddit url path **/ fun OAuthClient.getMultiMultipathDescription(multipath: String) = retry(3) { requestApi("/api/multi/$multipath/description", "multipath" to multipath).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L440># * <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}_description>PUT  * /api/multi/multipath/descriptionread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Change a multi's markdown description. * - modeljson data: * - { "body_md": raw markdown text, } multipathmultireddit url path * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.putMultiMultipathDescription(multipath: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/$multipath/description").method("put").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L410># * <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}_r_{srname}>DELETE  * /api/multi/multipath/r/srnamesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpath/r/srnameRemove a subreddit from a multi. * - multipathmultireddit url path * - srnamesubreddit name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.deleteMultiMultipathRSrname(multipath: String, srname: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/$multipath/r/$srname").method("delete").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L410># * <https://www.reddit.com/dev/api#DELETE_api_multi_{multipath}_r_{srname}>DELETE  * /api/multi/multipath/r/srnamesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpath/r/srnameRemove a subreddit from a multi. * - multipathmultireddit url path * - srnamesubreddit name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.deleteFilterFilterpathRSrname(filterpath: String, srname: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/filter/$filterpath/r/$srname").method("delete").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L371># * <https://www.reddit.com/dev/api#GET_api_multi_{multipath}_r_{srname}>GET  * /api/multi/multipath/r/srnameread <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpath/r/srnameGet data about a subreddit in a multi. * - multipathmultireddit url path * - srnamesubreddit name **/ fun OAuthClient.getMultiMultipathRSrname(multipath: String, srname: String) = retry(3) { requestApi("/api/multi/$multipath/r/$srname", "multipath" to multipath, "srname" to srname).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L371># * <https://www.reddit.com/dev/api#GET_api_multi_{multipath}_r_{srname}>GET  * /api/multi/multipath/r/srnameread <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpath/r/srnameGet data about a subreddit in a multi. * - multipathmultireddit url path * - srnamesubreddit name **/ fun OAuthClient.getFilterFilterpathRSrname(filterpath: String, srname: String, multipath: String?) = retry(3) { requestApi("/api/filter/$filterpath/r/$srname", "multipath" to multipath, "srname" to srname).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L386># * <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}_r_{srname}>PUT  * /api/multi/multipath/r/srnamesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpath/r/srnameAdd a subreddit to a multi. * - modeljson data: * - { "name": subreddit name, } multipathmultireddit url path * - srnamesubreddit name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.putMultiMultipathRSrname(multipath: String, srname: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/multi/$multipath/r/$srname").method("put").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/multi.py#L386># * <https://www.reddit.com/dev/api#PUT_api_multi_{multipath}_r_{srname}>PUT  * /api/multi/multipath/r/srnamesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * * → /api/filter/filterpath/r/srnameAdd a subreddit to a multi. * - modeljson data: * - { "name": subreddit name, } multipathmultireddit url path * - srnamesubreddit name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.putFilterFilterpathRSrname(filterpath: String, srname: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/filter/$filterpath/r/$srname").method("put").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L1092># * <https://www.reddit.com/dev/api#GET_search>GET [/r/subreddit]/searchread * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Search links page. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - include_facetsboolean value * - limitthe maximum number of items desired (default: 25, maximum: 100) * - qa string no longer than 512 characters * - restrict_srboolean value * - show(optional) the string all * - sortone of (relevance, hot, top, new, comments) * - sr_detail(optional) expand subreddits * - syntaxone of (cloudsearch, lucene, plain) * - tone of (hour, day, week, month, year, all) * - type(optional) comma-delimited list of result types (sr, link) **/ fun OAuthClient.getRSubredditSearch(subreddit: String, after: String?, before: String?, count: Int?, includeFacets: String?, limit: Int?, q: String?, restrictSr: String?, show: String?, sort: String?, srDetail: Boolean?, syntax: String?, t: String?, type: List<String>?) = retry(3) { requestApi("/r/$subreddit/search", "after" to after, "before" to before, "count" to count, "include_facets" to includeFacets, "limit" to limit, "q" to q, "restrict_sr" to restrictSr, "show" to show, "sort" to sort, "sr_detail" to srDetail, "syntax" to syntax, "t" to t, "type" to type.csv()).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutWhere(subreddit: String, where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/$where", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutBanned(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/banned", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutMuted(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/muted", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutWikibanned(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/wikibanned", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutContributors(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/contributors", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutWikicontributors(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/wikicontributors", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1855> * # <https://www.reddit.com/dev/api#GET_about_{where}>GET [/r/subreddit]/about/ * whereread <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → [/r/subreddit]/about/banned * * → [/r/subreddit]/about/muted * * → [/r/subreddit]/about/wikibanned * * → [/r/subreddit]/about/contributors * * → [/r/subreddit]/about/wikicontributors * * → [/r/subreddit]/about/moderatorsThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits * - userA valid, existing reddit username **/ fun OAuthClient.getRSubredditAboutModerators(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?, user: String?) = retry(3) { requestApi("/r/$subreddit/about/moderators", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail, "user" to user).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2539># * <https://www.reddit.com/dev/api#POST_api_delete_sr_banner>POST [/r/subreddit * ]/api/delete_sr_bannermodconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove the subreddit's custom mobile banner. * - See also: /api/upload_sr_img * <https://www.reddit.com/dev/api#POST_api_upload_sr_img>. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditDelete_sr_banner(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/delete_sr_banner").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2479># * <https://www.reddit.com/dev/api#POST_api_delete_sr_header>POST [/r/subreddit * ]/api/delete_sr_headermodconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove the subreddit's custom header image. * - The sitewide-default header image will be shown again after this call. * - See also: /api/upload_sr_img * <https://www.reddit.com/dev/api#POST_api_upload_sr_img>. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditDelete_sr_header(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/delete_sr_header").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2512># * <https://www.reddit.com/dev/api#POST_api_delete_sr_icon>POST [/r/subreddit * ]/api/delete_sr_iconmodconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove the subreddit's custom mobile icon. * - See also: /api/upload_sr_img * <https://www.reddit.com/dev/api#POST_api_upload_sr_img>. * - api_typethe string json * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditDelete_sr_icon(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/delete_sr_icon").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2447># * <https://www.reddit.com/dev/api#POST_api_delete_sr_img>POST [/r/subreddit * ]/api/delete_sr_imgmodconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove an image from the subreddit's custom image set. * - The image will no longer count against the subreddit's image limit. However, * the actual image data may still be accessible for an unspecified amount of * time. If the image is currently referenced by the subreddit's stylesheet, that * stylesheet will no longer validate and won't be editable until the image * reference is removed. * - See also: /api/upload_sr_img * <https://www.reddit.com/dev/api#POST_api_upload_sr_img>. * - api_typethe string json * - img_namea valid subreddit image name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditDelete_sr_img(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/delete_sr_img").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L5046># * <https://www.reddit.com/dev/api#GET_api_recommend_sr_{srnames}>GET  * /api/recommend/sr/srnamesread <https://github.com/reddit/reddit/wiki/OAuth2> * - Return subreddits recommended for the given subreddit(s). * - Gets a list of subreddits recommended for srnames, filtering out any that * appear in the optionalomit param. * - omitcomma-delimited list of subreddit names * - srnamescomma-delimited list of subreddit names **/ fun OAuthClient.getRecommendSrSrnames(srnames: List<String>, omit: List<String>?) = retry(3) { requestApi("/api/recommend/sr/$srnames", "omit" to omit.csv(), "srnames" to srnames.csv()).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4592># * <https://www.reddit.com/dev/api#POST_api_search_reddit_names>POST  * /api/search_reddit_namesread <https://github.com/reddit/reddit/wiki/OAuth2> * - List subreddit names that begin with a query string. * - Subreddits whose names begin with query will be returned. If include_over_18 * is false, subreddits with over-18 content restrictions will be filtered from * the results. * - If exact is true, only an exact match will be returned. * - exactboolean value * - include_over_18boolean value * - querya string up to 50 characters long, consisting of printable characters. **/ fun OAuthClient.postSearch_reddit_names(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/search_reddit_names").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2710># * <https://www.reddit.com/dev/api#POST_api_site_admin>POST /api/site_admin * modconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Create or configure a subreddit. * - If sr is specified, the request will attempt to modify the specified * subreddit. If not, a subreddit with namename will be created. * - This endpoint expects all values to be supplied on every request. If * modifying a subset of options, it may be useful to get the current settings from * /about/edit.json * <https://www.reddit.com/dev/api#GET_r_%7Bsubreddit%7D_about_edit.json> first. * - For backwards compatibility, description is the sidebar text and * public_description is the publicly visible subreddit description. * - Most of the parameters for this endpoint are identical to options visible in * the user interface and their meanings are best explained there. * - See also: /about/edit.json * <https://www.reddit.com/dev/api#GET_r_%7Bsubreddit%7D_about_edit.json>. * - allow_topboolean value * - api_typethe string json * - captchathe user's response to the CAPTCHA challenge * - collapse_deleted_commentsboolean value * - comment_score_hide_minsan integer between 0 and 1440 (default: 0) * - descriptionraw markdown text * - exclude_banned_modqueueboolean value * - header-titlea string no longer than 500 characters * - hide_adsboolean value * - identhe identifier of the CAPTCHA challenge * - langa valid IETF language tag (underscore separated) * - link_typeone of (any, link, self) * - namesubreddit name * - over_18boolean value * - public_descriptionraw markdown text * - public_trafficboolean value * - show_mediaboolean value * - spam_commentsone of (low, high, all) * - spam_linksone of (low, high, all) * - spam_selfpostsone of (low, high, all) * - srfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - submit_link_labela string no longer than 60 characters * - submit_textraw markdown text * - submit_text_labela string no longer than 60 characters * - suggested_comment_sortone of (confidence, top, new, controversial, old, random * ,qa) * - titlea string no longer than 100 characters * - typeone of (gold_restricted, archived, restricted, gold_only, employees_only, * private, public) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - wiki_edit_agean integer greater than 0 (default: 0) * - wiki_edit_karmaan integer greater than 0 (default: 0) * - wikimodeone of (disabled, modonly, anyone) **/ fun OAuthClient.postSite_admin(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/site_admin").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L417># * <https://www.reddit.com/dev/api#GET_api_submit_text>GET [/r/subreddit * ]/api/submit_textsubmit <https://github.com/reddit/reddit/wiki/OAuth2> * - Get the submission text for the subreddit. * - This text is set by the subreddit moderators and intended to be displayed on * the submission form. * - See also: /api/site_admin <https://www.reddit.com/dev/api#POST_api_site_admin> * . **/ fun OAuthClient.getRSubredditSubmit_text(subreddit: String) = retry(3) { requestApi("/r/$subreddit/api/submit_text").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2364># * <https://www.reddit.com/dev/api#POST_api_subreddit_stylesheet>POST [/r/subreddit * ]/api/subreddit_stylesheetmodconfig * <https://github.com/reddit/reddit/wiki/OAuth2> * - Update a subreddit's stylesheet. * - op should be save to update the contents of the stylesheet. * - api_typethe string json * - opone of (save, preview) * - reasona string up to 256 characters long, consisting of printable characters. * - stylesheet_contentsthe new stylesheet content * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditSubreddit_stylesheet(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/subreddit_stylesheet").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L4738># * <https://www.reddit.com/dev/api#GET_api_subreddits_by_topic>GET  * /api/subreddits_by_topicread <https://github.com/reddit/reddit/wiki/OAuth2> * - Return a list of subreddits that are relevant to a search query. * - querya string no longer than 50 characters **/ fun OAuthClient.getSubreddits_by_topic(query: String?) = retry(3) { requestApi("/api/subreddits_by_topic", "query" to query).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L3774># * <https://www.reddit.com/dev/api#POST_api_subscribe>POST /api/subscribesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * - Subscribe to or unsubscribe from a subreddit. * - To subscribe, action should be sub. To unsubscribe, action should be unsub. * The user must have access to the subreddit to be able to subscribe to it. * - See also: /subreddits/mine/ * <https://www.reddit.com/dev/api#GET_subreddits_mine_%7Bwhere%7D>. * - actionone of (sub, unsub) * - srthe name of a subreddit * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postSubscribe(vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/subscribe").post(urlParams.multipart()).getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L2577># * <https://www.reddit.com/dev/api#POST_api_upload_sr_img>POST [/r/subreddit * ]/api/upload_sr_imgmodconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Add or replace a subreddit image, custom header logo, custom mobile icon, or * custom mobile banner. * * If the upload_type value is img, an image for use in the subreddit * stylesheet is uploaded with the name specified inname. * * If the upload_type value is header then the image uploaded will be the * subreddit's new logo andname will be ignored. * * If the upload_type value is icon then the image uploaded will be the * subreddit's new mobile icon andname will be ignored. * * If the upload_type value is banner then the image uploaded will be the * subreddit's new mobile banner andname will be ignored. For backwards * compatibility, ifupload_type is not specified, the header field will be used * instead: * * If the header field has value 0, then upload_type is img. * * If the header field has value 1, then upload_type is header. The img_type * field specifies whether to store the uploaded image as a PNG or JPEG. * - Subreddits have a limited number of images that can be in use at any given * time. If no image with the specified name already exists, one of the slots will * be consumed. * - If an image with the specified name already exists, it will be replaced. This * does not affect the stylesheet immediately, but will take effect the next time * the stylesheet is saved. * - See also: /api/delete_sr_img * <https://www.reddit.com/dev/api#POST_api_delete_sr_img>, /api/delete_sr_header * <https://www.reddit.com/dev/api#POST_api_delete_sr_header>, /api/delete_sr_icon * <https://www.reddit.com/dev/api#POST_api_delete_sr_icon>, and * /api/delete_sr_banner <https://www.reddit.com/dev/api#POST_api_delete_sr_banner> * . * - filefile upload with maximum size of 500 KiB * - formid(optional) can be ignored * - headeran integer between 0 and 1 * - img_typeone of png or jpg (default: png) * - namea valid subreddit image name * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - upload_typeone of (img, header, icon, banner) **/ fun OAuthClient.postRSubredditUpload_sr_img(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/upload_sr_img").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L919># * <https://www.reddit.com/dev/api#GET_r_{subreddit}_about>GET /r/subreddit/about * read <https://github.com/reddit/reddit/wiki/OAuth2> * - Return information about the subreddit. * - Data includes the subscriber count, description, and header image. **/ fun OAuthClient.getRSubredditAbout(subreddit: String) = retry(3) { requestApi("/r/$subreddit/about").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L897># * <https://www.reddit.com/dev/api#GET_r_{subreddit}_about_edit>GET /r/subreddit * /about/editmodconfig <https://github.com/reddit/reddit/wiki/OAuth2> * - Get the current settings of a subreddit. * - In the API, this returns the current settings of the subreddit as used by * /api/site_admin <https://www.reddit.com/dev/api#POST_api_site_admin>. On the * HTML site, it will display a form for editing the subreddit. * - createdone of (true, false) * - location **/ fun OAuthClient.getRSubredditAboutEdit(subreddit: String, created: Boolean?) = retry(3) { requestApi("/r/$subreddit/about/edit", "created" to created).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L938># * <https://www.reddit.com/dev/api#GET_rules>GET [/r/subreddit]/rulesread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Get the rules for the current subreddit **/ fun OAuthClient.getRSubredditRules(subreddit: String) = retry(3) { requestApi("/r/$subreddit/rules").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L931># * <https://www.reddit.com/dev/api#GET_sidebar>GET [/r/subreddit]/sidebarread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Get the sidebar for the current subreddit **/ fun OAuthClient.getRSubredditSidebar(subreddit: String) = retry(3) { requestApi("/r/$subreddit/sidebar").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#GET_sticky>GET [/r/subreddit]/stickyread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Redirect to one of the posts stickied in the current subreddit * - The "num" argument can be used to select a specific sticky, and will default * to 1 (the top sticky) if not specified. Will 404 if there is not currently a * sticky post in this subreddit. * - numan integer between 1 and 2 (default: 1) **/ fun OAuthClient.getRSubredditSticky(subreddit: String, num: String?) = retry(3) { requestApi("/r/$subreddit/sticky", "num" to num).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626> * # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET  * /subreddits/mine/wheremysubreddits * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/mine/subscriber * * → /subreddits/mine/contributor * * → /subreddits/mine/moderatorGet subreddits the user has a relationship with. * - The where parameter chooses which subreddits are returned as follows: * * subscriber - subreddits the user is subscribed to * * contributor - subreddits the user is an approved submitter in * * moderator - subreddits the user is a moderator of See also: /api/subscribe * <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend * <https://www.reddit.com/dev/api#POST_api_friend>, and * /api/accept_moderator_invite * <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsMineWhere(where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/mine/$where", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626> * # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET  * /subreddits/mine/wheremysubreddits * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/mine/subscriber * * → /subreddits/mine/contributor * * → /subreddits/mine/moderatorGet subreddits the user has a relationship with. * - The where parameter chooses which subreddits are returned as follows: * * subscriber - subreddits the user is subscribed to * * contributor - subreddits the user is an approved submitter in * * moderator - subreddits the user is a moderator of See also: /api/subscribe * <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend * <https://www.reddit.com/dev/api#POST_api_friend>, and * /api/accept_moderator_invite * <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsMineSubscriber(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/mine/subscriber", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626> * # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET  * /subreddits/mine/wheremysubreddits * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/mine/subscriber * * → /subreddits/mine/contributor * * → /subreddits/mine/moderatorGet subreddits the user has a relationship with. * - The where parameter chooses which subreddits are returned as follows: * * subscriber - subreddits the user is subscribed to * * contributor - subreddits the user is an approved submitter in * * moderator - subreddits the user is a moderator of See also: /api/subscribe * <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend * <https://www.reddit.com/dev/api#POST_api_friend>, and * /api/accept_moderator_invite * <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsMineContributor(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/mine/contributor", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1626> * # <https://www.reddit.com/dev/api#GET_subreddits_mine_{where}>GET  * /subreddits/mine/wheremysubreddits * <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/mine/subscriber * * → /subreddits/mine/contributor * * → /subreddits/mine/moderatorGet subreddits the user has a relationship with. * - The where parameter chooses which subreddits are returned as follows: * * subscriber - subreddits the user is subscribed to * * contributor - subreddits the user is an approved submitter in * * moderator - subreddits the user is a moderator of See also: /api/subscribe * <https://www.reddit.com/dev/api#POST_api_subscribe>, /api/friend * <https://www.reddit.com/dev/api#POST_api_friend>, and * /api/accept_moderator_invite * <https://www.reddit.com/dev/api#POST_api_accept_moderator_invite>. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsMineModerator(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/mine/moderator", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/front.py#L1034># * <https://www.reddit.com/dev/api#GET_subreddits_search>GET /subreddits/search * read <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * - Search subreddits by title and description. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - qa search query * - show(optional) the string all * - sortone of (relevance, activity) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsSearch(after: String?, before: String?, count: Int?, limit: Int?, q: String?, show: String?, sort: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/search", "after" to after, "before" to before, "count" to count, "limit" to limit, "q" to q, "show" to show, "sort" to sort, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507> * # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where * read <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/popular * * → /subreddits/new * * → /subreddits/gold * * → /subreddits/defaultGet all subreddits. * - The where parameter chooses the order in which the subreddits are displayed. * popular sorts on the activity of the subreddit and the position of the * subreddits can shift around.new sorts the subreddits based on their creation * date, newest first. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsWhere(where: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/$where", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507> * # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where * read <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/popular * * → /subreddits/new * * → /subreddits/gold * * → /subreddits/defaultGet all subreddits. * - The where parameter chooses the order in which the subreddits are displayed. * popular sorts on the activity of the subreddit and the position of the * subreddits can shift around.new sorts the subreddits based on their creation * date, newest first. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsPopular(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/popular", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507> * # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where * read <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/popular * * → /subreddits/new * * → /subreddits/gold * * → /subreddits/defaultGet all subreddits. * - The where parameter chooses the order in which the subreddits are displayed. * popular sorts on the activity of the subreddit and the position of the * subreddits can shift around.new sorts the subreddits based on their creation * date, newest first. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsNew(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/new", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507> * # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where * read <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/popular * * → /subreddits/new * * → /subreddits/gold * * → /subreddits/defaultGet all subreddits. * - The where parameter chooses the order in which the subreddits are displayed. * popular sorts on the activity of the subreddit and the position of the * subreddits can shift around.new sorts the subreddits based on their creation * date, newest first. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsGold(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/gold", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1507> * # <https://www.reddit.com/dev/api#GET_subreddits_{where}>GET /subreddits/where * read <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /subreddits/popular * * → /subreddits/new * * → /subreddits/gold * * → /subreddits/defaultGet all subreddits. * - The where parameter chooses the order in which the subreddits are displayed. * popular sorts on the activity of the subreddit and the position of the * subreddits can shift around.new sorts the subreddits based on their creation * date, newest first. * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getSubredditsDefault(after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/subreddits/default", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L1020># * <https://www.reddit.com/dev/api#POST_api_friend>POST [/r/subreddit]/api/friend * any <https://github.com/reddit/reddit/wiki/OAuth2> * - Create a relationship between a user and another user or subreddit * - OAuth2 use requires appropriate scope based on the 'type' of the relationship: * * moderator: Use "moderator_invite" * * moderator_invite: modothers * * contributor: modcontributors * * banned: modcontributors * * muted: modcontributors * * wikibanned: modcontributors and modwiki * * wikicontributor: modcontributors and modwiki * * friend: Use /api/v1/me/friends/{username} * <https://www.reddit.com/dev/api#PUT_api_v1_me_friends_%7Busername%7D> * * enemy: Use /api/block <https://www.reddit.com/dev/api#POST_api_block> * Complement toPOST_unfriend <https://www.reddit.com/dev/api#POST_api_unfriend> * - api_typethe string json * - ban_messageraw markdown text * - ban_reasona string no longer than 100 characters * - containerdurationan integer between 1 and 999 * - namethe name of an existing user * - notea string no longer than 300 characters * - permissionstypeone of (friend, moderator, moderator_invite, contributor, * banned, muted, wikibanned, wikicontributor) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditFriend(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/friend").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L974># * <https://www.reddit.com/dev/api#POST_api_setpermissions>POST [/r/subreddit * ]/api/setpermissionsmodothers <https://github.com/reddit/reddit/wiki/OAuth2> * - api_typethe string json * - namethe name of an existing user * - permissionstypeuh / X-Modhash headera modhash * <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditSetpermissions(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/setpermissions").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L868># * <https://www.reddit.com/dev/api#POST_api_unfriend>POST [/r/subreddit * ]/api/unfriendany <https://github.com/reddit/reddit/wiki/OAuth2> * - Remove a relationship between a user and another user or subreddit * - The user can either be passed in by name (nuser) or by fullname * <https://www.reddit.com/dev/api#fullnames> (iuser). If type is friend or enemy, * 'container' MUST be the current user's fullname; for other types, the subreddit * must be set via URL (e.g.,/r/funny/api/unfriend * <https://www.reddit.com/r/funny/api/unfriend>) * - OAuth2 use requires appropriate scope based on the 'type' of the relationship: * * moderator: modothers * * moderator_invite: modothers * * contributor: modcontributors * * banned: modcontributors * * muted: modcontributors * * wikibanned: modcontributors and modwiki * * wikicontributor: modcontributors and modwiki * * friend: Use /api/v1/me/friends/{username} * <https://www.reddit.com/dev/api#DELETE_api_v1_me_friends_%7Busername%7D> * * enemy: privatemessages Complement to POST_friend * <https://www.reddit.com/dev/api#POST_api_friend> * - containeridfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - namethe name of an existing user * - typeone of (friend, enemy, moderator, moderator_invite, contributor, banned, * muted, wikibanned, wikicontributor) * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditUnfriend(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/unfriend").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/api.py#L238># * <https://www.reddit.com/dev/api#GET_api_username_available>GET  * /api/username_available * - Check whether a username is available for registration. * - usera valid, unused, username **/ fun OAuthClient.getUsername_available(user: String?) = retry(3) { requestApi("/api/username_available", "user" to user).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L202> * # <https://www.reddit.com/dev/api#DELETE_api_v1_me_friends_{username}>DELETE  * /api/v1/me/friends/usernamesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * - Stop being friends with a user. * - idA valid, existing reddit username **/ fun OAuthClient.deleteV1MeFriendsUsername(username: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/v1/me/friends/$username").method("delete").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L191> * # <https://www.reddit.com/dev/api#GET_api_v1_me_friends_{username}>GET  * /api/v1/me/friends/usernamemysubreddits * <https://github.com/reddit/reddit/wiki/OAuth2> * - Get information about a specific 'friend', such as notes. * - idA valid, existing reddit username **/ fun OAuthClient.getV1MeFriendsUsername(username: String, id: String?) = retry(3) { requestApi("/api/v1/me/friends/$username", "id" to id).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L146> * # <https://www.reddit.com/dev/api#PUT_api_v1_me_friends_{username}>PUT  * /api/v1/me/friends/usernamesubscribe * <https://github.com/reddit/reddit/wiki/OAuth2> * - Create or update a "friend" relationship. * - This operation is idempotent. It can be used to add a new friend, or update * an existing friend (e.g., add/change the note on that friend) * - This endpoint expects JSON data of this format{ "name": A valid, existing * reddit username, "note": a string no longer than 300 characters, } **/ fun OAuthClient.putV1MeFriendsUsername(username: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/api/v1/me/friends/$username").method("put").getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/apiv1/user.py#L82> * # <https://www.reddit.com/dev/api#GET_api_v1_user_{username}_trophies>GET  * /api/v1/user/username/trophiesread * <https://github.com/reddit/reddit/wiki/OAuth2> * - Return a list of trophies for the a given user. * - idA valid, existing reddit username **/ fun OAuthClient.getV1UserUsernameTrophies(username: String, id: String?) = retry(3) { requestApi("/api/v1/user/$username/trophies", "id" to id).get().getResponse() } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L1015> * # <https://www.reddit.com/dev/api#GET_user_{username}_about>GET /user/username * /aboutread <https://github.com/reddit/reddit/wiki/OAuth2> * - Return information about the user, including karma and gold status. * - usernamethe name of an existing user **/ fun OAuthClient.getUserUsernameAbout(username: String) = retry(3) { requestApi("/user/$username/about", "username" to username).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameWhere(username: String, where: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/$where", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameOverview(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/overview", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameSubmitted(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/submitted", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameComments(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/comments", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameUpvoted(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/upvoted", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameDownvoted(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/downvoted", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameHidden(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/hidden", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameSaved(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/saved", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/listingcontroller.py#L890> * # <https://www.reddit.com/dev/api#GET_user_{username}_{where}>GET /user/username * /wherehistory <https://github.com/reddit/reddit/wiki/OAuth2>rss support * <https://www.reddit.com/wiki/rss> * * → /user/username/overview * * → /user/username/submitted * * → /user/username/comments * * → /user/username/upvoted * * → /user/username/downvoted * * → /user/username/hidden * * → /user/username/saved * * → /user/username/gildedThis endpoint is a listing * <https://www.reddit.com/dev/api#listings>. * - showone of (given) * - sortone of (hot, new, top, controversial) * - tone of (hour, day, week, month, year, all) * - usernamethe name of an existing user * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getUserUsernameGilded(username: String, show: String?, sort: String?, t: String?, after: String?, before: String?, count: Int?, limit: Int?, srDetail: Boolean?) = retry(3) { requestApi("/user/$username/gilded", "show" to show, "sort" to sort, "t" to t, "username" to username, "after" to after, "before" to before, "count" to count, "limit" to limit, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L452># * <https://www.reddit.com/dev/api#POST_api_wiki_alloweditor_{act}>POST [/r/ * subreddit]/api/wiki/alloweditor/actmodwiki * <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/api/wiki/alloweditor/del * * → [/r/subreddit]/api/wiki/alloweditor/addAllow/deny username to edit this * wikipage * - actone of (del, add) * - pagethe name of an existing wiki page * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - usernamethe name of an existing user **/ fun OAuthClient.postRSubredditWikiAlloweditorAct(subreddit: String, act: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/wiki/alloweditor/$act").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L452># * <https://www.reddit.com/dev/api#POST_api_wiki_alloweditor_{act}>POST [/r/ * subreddit]/api/wiki/alloweditor/actmodwiki * <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/api/wiki/alloweditor/del * * → [/r/subreddit]/api/wiki/alloweditor/addAllow/deny username to edit this * wikipage * - actone of (del, add) * - pagethe name of an existing wiki page * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - usernamethe name of an existing user **/ fun OAuthClient.postRSubredditWikiAlloweditorDel(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/wiki/alloweditor/del").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L452># * <https://www.reddit.com/dev/api#POST_api_wiki_alloweditor_{act}>POST [/r/ * subreddit]/api/wiki/alloweditor/actmodwiki * <https://github.com/reddit/reddit/wiki/OAuth2> * * → [/r/subreddit]/api/wiki/alloweditor/del * * → [/r/subreddit]/api/wiki/alloweditor/addAllow/deny username to edit this * wikipage * - actone of (del, add) * - pagethe name of an existing wiki page * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> * - usernamethe name of an existing user **/ fun OAuthClient.postRSubredditWikiAlloweditorAdd(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/wiki/alloweditor/add").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L376># * <https://www.reddit.com/dev/api#POST_api_wiki_edit>POST [/r/subreddit * ]/api/wiki/editwikiedit <https://github.com/reddit/reddit/wiki/OAuth2> * - Edit a wiki page * - contentpagethe name of an existing page or a new page to create * - previousthe starting point revision for this edit * - reasona string up to 256 characters long, consisting of printable characters. * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditWikiEdit(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/wiki/edit").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L493># * <https://www.reddit.com/dev/api#POST_api_wiki_hide>POST [/r/subreddit * ]/api/wiki/hidemodwiki <https://github.com/reddit/reddit/wiki/OAuth2> * - Toggle the public visibility of a wiki page revision * - pagethe name of an existing wiki page * - revisiona wiki revision ID * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditWikiHide(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/wiki/hide").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L508># * <https://www.reddit.com/dev/api#POST_api_wiki_revert>POST [/r/subreddit * ]/api/wiki/revertmodwiki <https://github.com/reddit/reddit/wiki/OAuth2> * - Revert a wiki page to revision * - pagethe name of an existing wiki page * - revisiona wiki revision ID * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditWikiRevert(subreddit: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/api/wiki/revert").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#GET_wiki_discussions_{page}>GET [/r/subreddit * ]/wiki/discussions/pagewikiread <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve a list of discussions about this wiki page * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - pagethe name of an existing wiki page * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditWikiDiscussionsPage(subreddit: String, page: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/wiki/discussions/$page", "after" to after, "before" to before, "count" to count, "limit" to limit, "page" to page, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/controllers/wiki.py#L258># * <https://www.reddit.com/dev/api#GET_wiki_pages>GET [/r/subreddit]/wiki/pages * wikiread <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve a list of wiki pages in this subreddit **/ fun OAuthClient.getRSubredditWikiPages(subreddit: String) = retry(3) { requestApi("/r/$subreddit/wiki/pages").get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#GET_wiki_revisions>GET [/r/subreddit * ]/wiki/revisionswikiread <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve a list of recently changed wiki pages in this subreddit * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditWikiRevisions(subreddit: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/wiki/revisions", "after" to after, "before" to before, "count" to count, "limit" to limit, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#GET_wiki_revisions_{page}>GET [/r/subreddit * ]/wiki/revisions/pagewikiread <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve a list of revisions of this wiki page * - This endpoint is a listing <https://www.reddit.com/dev/api#listings>. * - afterfullname <https://www.reddit.com/dev/api#fullnames> of a thing * - beforefullname <https://www.reddit.com/dev/api#fullnames> of a thing * - counta positive integer (default: 0) * - limitthe maximum number of items desired (default: 25, maximum: 100) * - pagethe name of an existing wiki page * - show(optional) the string all * - sr_detail(optional) expand subreddits **/ fun OAuthClient.getRSubredditWikiRevisionsPage(subreddit: String, page: String, after: String?, before: String?, count: Int?, limit: Int?, show: String?, srDetail: Boolean?) = retry(3) { requestApi("/r/$subreddit/wiki/revisions/$page", "after" to after, "before" to before, "count" to count, "limit" to limit, "page" to page, "show" to show, "sr_detail" to srDetail).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#GET_wiki_settings_{page}>GET [/r/subreddit * ]/wiki/settings/pagemodwiki <https://github.com/reddit/reddit/wiki/OAuth2> * - Retrieve the current permission settings for page * - pagethe name of an existing wiki page **/ fun OAuthClient.getRSubredditWikiSettingsPage(subreddit: String, page: String) = retry(3) { requestApi("/r/$subreddit/wiki/settings/$page", "page" to page).get().readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#POST_wiki_settings_{page}>POST [/r/subreddit * ]/wiki/settings/pagemodwiki <https://github.com/reddit/reddit/wiki/OAuth2> * - Update the permissions and visibility of wiki page * - listedboolean value * - pagethe name of an existing wiki page * - permlevelan integer * - uh / X-Modhash headera modhash <https://www.reddit.com/dev/api#modhashes> **/ fun OAuthClient.postRSubredditWikiSettingsPage(subreddit: String, page: String, vararg urlParams: Pair<String, Any?>) = retry(3) { requestApi("/r/$subreddit/wiki/settings/$page").post(urlParams.multipart()).readEntity(String::class.java) } /* * view code * <https://github.com/reddit/reddit/blob/master/r2/r2/lib/validator/validator.py#L200> * # <https://www.reddit.com/dev/api#GET_wiki_{page}>GET [/r/subreddit]/wiki/page * wikiread <https://github.com/reddit/reddit/wiki/OAuth2> * - Return the content of a wiki page * - If v is given, show the wiki page as it was at that version If both v and v2 * are given, show a diff of the two * - pagethe name of an existing wiki page * - va wiki revision ID * - v2a wiki revision ID **/ fun OAuthClient.getRSubredditWikiPage(subreddit: String, page: String, v: String?, v2: String?) = retry(3) { requestApi("/r/$subreddit/wiki/$page", "page" to page, "v" to v, "v2" to v2).get().readEntity(String::class.java) } // Generated API end.
src/main/java/org/ethtrader/ticker/Api.kt
364841917
package github.jk1.smtpidea.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import github.jk1.smtpidea.Icons import github.jk1.smtpidea.ui.NewMailDialog /** * Opens dialog window to compose new e-mail to be placed on our toy server */ object CreateMailAction : AnAction("Create new message", "Create new e-mail in our imaginary POP3 mailbox", Icons.ADD){ override fun actionPerformed(p0: AnActionEvent?) { val project = p0?.getProject() if (project != null){ NewMailDialog(project).show() } } }
src/main/kotlin/github/jk1/smtpidea/actions/CreateMailAction.kt
3262487426
package ru.bozaro.gitlfs.client.exceptions import org.apache.http.HttpResponse import org.apache.http.client.methods.HttpUriRequest import java.io.IOException /** * Simple HTTP exception. * * @author Artem V. Navrotskiy */ open class RequestException(private val request: HttpUriRequest, private val response: HttpResponse) : IOException() { val statusCode: Int get() = response.statusLine.statusCode override val message: String get() { val statusLine = response.statusLine return request.uri.toString() + " - " + statusLine.statusCode + " (" + statusLine.reasonPhrase + ")" } }
gitlfs-client/src/main/kotlin/ru/bozaro/gitlfs/client/exceptions/RequestException.kt
3427345368
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.generator import org.lwjgl.generator.GenerationMode.* import java.io.* /* **** The code below implements the more complex parts of LWJGL's code generation. Please only modify if you fully understand what's going on. **** The basic generation is relatively straightforward. It's an almost 1-to-1 mapping of the native function signature to the proper Java -> JNI -> native function code. We then try to generate additional Java methods that make the user's life easier. We use the TemplateModifiers on the function signature parameters and return values to figure out what kind of Transforms we should apply. Depending on the modifiers, we may generate one or more additional methods. */ // Global definitions internal const val ADDRESS = "address()" const val RESULT = "__result" internal const val ANONYMOUS = "*" // invalid character in Java identifiers internal const val POINTER_POSTFIX = "Address" internal const val MAP_OLD = "old_buffer" internal const val MAP_LENGTH = "length" const val FUNCTION_ADDRESS = "__functionAddress" internal const val JNIENV = "__env" /** Special parameter that generates an explicit function address parameter. */ val EXPLICIT_FUNCTION_ADDRESS = Parameter(opaque_p, FUNCTION_ADDRESS, "the function address") /** Special parameter that will accept the JNI function's JNIEnv* parameter. Hidden in Java code. */ val JNI_ENV = Parameter("JNIEnv".opaque.p, JNIENV, "the JNI environment struct") private val TRY_FINALLY_RESULT_REFERENCE = """(?<=^|\W)$RESULT(?=\W|$)""".toRegex() private val TRY_FINALLY_ALIGN = "^(\\s+)".toRegex(RegexOption.MULTILINE) enum class GenerationMode { NORMAL, ALTERNATIVE } // --- [ Native class functions ] --- class Func( val returns: ReturnValue, val simpleName: String, val name: String, val documentation: ((Parameter) -> Boolean) -> String, val nativeClass: NativeClass, vararg val parameters: Parameter ) : ModifierTarget<FunctionModifier>() { private val paramMap = HashMap<String, Parameter>() init { for (param in parameters) paramMap[param.name] = param validate() } private val hasNativeParams = getNativeParams().any() fun getParam(paramName: String) = paramMap[paramName] ?: throw IllegalArgumentException("Referenced parameter does not exist: $simpleName.$paramName") inline fun getParams(crossinline predicate: (Parameter) -> Boolean) = parameters.asSequence().filter { predicate(it) } private inline fun getParam(crossinline predicate: (Parameter) -> Boolean) = getParams(predicate).single() internal inline fun hasParam(crossinline predicate: (Parameter) -> Boolean) = getParams(predicate).any() private fun getNativeParams( withExplicitFunctionAddress: Boolean = true, withJNIEnv: Boolean = false, withAutoSizeResultParams: Boolean = true ) = parameters.asSequence() .let { p -> if (withExplicitFunctionAddress) p else p.filter { it !== EXPLICIT_FUNCTION_ADDRESS } } .let { p -> if (withJNIEnv) p else p.filter { it !== JNI_ENV } } .let { p -> if (withAutoSizeResultParams) p.filter { !it.has<Virtual>() } else p.filter { !((it.has<Virtual>() && !it.has<AutoSizeResultParam>()) || (it.isAutoSizeResultOut && hideAutoSizeResultParam)) } } /** Returns a parameter that has the specified ReferenceModifier with the specified reference. Returns null if no such parameter exists. */ internal inline fun <reified T> getReferenceParam(reference: String) where T : ParameterModifier, T : ReferenceModifier = parameters.asSequence().firstOrNull { it.has<T>(reference) } // Assumes at most 1 parameter will be found that references the specified parameter override fun validate(modifier: FunctionModifier) = modifier.validate(this) internal fun copyModifiers(other: Func): Func { if (other.hasModifiers()) this._modifiers = HashMap(other.modifiers) return this } val functionAddress get() = if (has<NativeName>()) get<NativeName>().name else "\"${this.name}\"" val nativeName get() = if (has<NativeName> { !nativeName.contains(' ') }) get<NativeName>().nativeName else this.name private val accessModifier get() = (if (has<AccessModifier>()) get<AccessModifier>().access else nativeClass.access).modifier private fun stripPostfix(functionName: String = name): String { if (!hasNativeParams) return functionName val param = parameters[parameters.lastIndex] if (!param.isBufferPointer) return functionName var name = functionName var postfix = (if (has<DependsOn>()) get<DependsOn>().postfix else null) ?: nativeClass.postfix if (name.endsWith(postfix)) name = name.substring(0, name.length - postfix.length) else postfix = "" return (if (name.endsWith("v")) name.substring(0, name.length - (if (name.endsWith("_v")) 2 else 1)) else name) + postfix } val javaDocLink get() = "#${this.simpleName}()" private val hasFunctionAddressParam: Boolean by lazy(LazyThreadSafetyMode.NONE) { nativeClass.binding != null && (nativeClass.binding.apiCapabilities !== APICapabilities.JNI_CAPABILITIES || hasParam { it.nativeType is ArrayType<*> }) } internal val hasExplicitFunctionAddress get() = this.parameters.isNotEmpty() && this.parameters.last() === EXPLICIT_FUNCTION_ADDRESS private val hasNativeCode get() = (has<Code> { nativeBeforeCall != null || nativeCall != null || nativeAfterCall != null }) || this.parameters.contains(JNI_ENV) internal val hasCustomJNIWithIgnoreAddress get() = (this.returns.isStructValue || hasNativeCode) && (!has<Macro> { expression != null }) internal val hasCustomJNI: Boolean by lazy(LazyThreadSafetyMode.NONE) { (!hasFunctionAddressParam || hasNativeCode || ((nativeClass.module.library != null || nativeClass.module.key.startsWith("core.")) && (returns.isStructValue || hasParam { it.nativeType is StructType }))) && !has<Macro> { expression != null } } private val isNativeOnly: Boolean by lazy(LazyThreadSafetyMode.NONE) { (nativeClass.binding == null || nativeClass.binding.apiCapabilities === APICapabilities.JNI_CAPABILITIES) && !( modifiers.any { it.value.isSpecial } || this.returns.isSpecial || hasParam { it.isSpecial } || has<NativeName>() || (has<Macro> { expression != null }) ) } private val hasUnsafeMethod by lazy(LazyThreadSafetyMode.NONE) { hasFunctionAddressParam && !(hasExplicitFunctionAddress && hasNativeCode) && (this.returns.hasUnsafe || hasParam { it.hasUnsafe || it has MapToInt }) && !has<Address>() && !hasParam { it.nativeType is ArrayType<*> } && (!has<Macro> { expression != null }) } internal val hasArrayOverloads get() = !has<OffHeapOnly>() && this.parameters .count { it.isAutoSizeResultOut } .let { autoSizeResultOutParams -> this.parameters.asSequence().any { it.has<MultiType>() || it.isArrayParameter(autoSizeResultOutParams) } } private val ReturnValue.javaMethodType get() = this.nativeType.let { if (it is PointerType<*>) { if (it.elementType is StructType && hasParam { param -> param.has<AutoSizeResultParam>() }) "${it.javaMethodType}.Buffer" else if (it is FunctionType) it.className else it.javaMethodType } else it.javaMethodType } private val ReturnValue.nativeMethodType get() = if (this.isStructValue) "void" else this.nativeType.nativeMethodType private val ReturnValue.jniFunctionType get() = if (this.isStructValue) "void" else this.nativeType.jniFunctionType internal val returnsNull get() = !(has(Nonnull) || has(Address) || has<Macro> { !function }) private inline fun <reified T> hasReference(reference: Parameter): (Parameter) -> Boolean where T : ParameterModifier, T : ReferenceModifier = { it.has<T> { hasReference(reference.name) } } private inline fun <reified T> hasReferenceFor(reference: Parameter) where T : ParameterModifier, T : ReferenceModifier = hasParam(hasReference<T>(reference)) internal fun hasAutoSizeFor(reference: Parameter) = hasReferenceFor<AutoSize>(reference) internal val hideAutoSizeResultParam = returns.nativeType is PointerType<*> && getParams { it.isAutoSizeResultOut }.count() == 1 private fun Parameter.error(msg: String) { throw IllegalArgumentException("$msg [${nativeClass.className}.${[email protected]}, parameter: ${this.name}]") } private fun Parameter.asJavaMethodParam(annotate: Boolean) = ( if (nativeType is PointerType<*> && nativeType.elementType is StructType && (has<Check>() || has<Unsafe>() || getReferenceParam<AutoSize>(name) != null)) "$javaMethodType.Buffer" else if (nativeType is ArrayType<*>) "${nativeType.mapping.primitive}[]" else if (has<MapToInt>()) "int" else javaMethodType ).let { if (annotate) { nativeType.annotate(it).let { annotatedType -> if (nativeType.isReference && has(nullable)) { "@Nullable $annotatedType" } else { annotatedType } } } else { it } }.let { "$it $name" } private fun Parameter.asNativeMethodParam(nativeOnly: Boolean) = (if (nativeType is ArrayType<*>) "${nativeType.mapping.primitive}[]" else nativeType.nativeMethodType ).let { if (nativeOnly) { "${nativeType.annotate(it)} $name" } else { "$it $name" } } private fun Parameter.asNativeMethodArgument(mode: GenerationMode) = when { nativeType.dereference is StructType || nativeType is WrappedPointerType -> if (has(nullable)) "memAddressSafe($name)" else if (nativeType is WrappedPointerType && hasUnsafeMethod && nativeClass.binding!!.apiCapabilities === APICapabilities.PARAM_CAPABILITIES) name else "$name.$ADDRESS" nativeType.isPointerData -> if (nativeType is ArrayType<*>) name else if (!isAutoSizeResultOut && (has(nullable) || (has(optional) && mode === NORMAL))) "memAddressSafe($name)" else "memAddress($name)" nativeType.mapping === PrimitiveMapping.BOOLEAN4 -> "$name ? 1 : 0" has<MapToInt>() -> if (nativeType.mapping === PrimitiveMapping.BYTE) "(byte)$name" else "(short)$name" else -> name } private val Parameter.isFunctionProvider get() = nativeType is WrappedPointerType && nativeClass.binding != null && nativeClass.binding.apiCapabilities === APICapabilities.PARAM_CAPABILITIES && !has(nullable) /** Validates parameters with modifiers that reference other parameters. */ private fun validate() { returns.nativeType.let { if (it is StructType) it.definition.setUsageOutput() else if (it is PointerType<*> && it.elementType is StructType) it.elementType.definition.setUsageResultPointer() } var returnCount = 0 val autoSizeReferences = HashSet<String>() parameters.forEachIndexed { i, it -> it.nativeType.dereference.let { type -> if (type is StructType) { if (it.isInput) type.definition.setUsageInput() else type.definition.setUsageOutput() } } if (it === EXPLICIT_FUNCTION_ADDRESS && i != parameters.lastIndex) it.error("The explicit function address parameter must be the last parameter.") if (it.has<Check>()) { val checkReference = paramMap[it.get<Check>().expression] if (checkReference != null) { if (checkReference.nativeType !is IntegerType) { it.error("The Check expression refers to an invalid parameter: ${checkReference.name}") } } } if (it.has<AutoSize>()) { val autoSize = it.get<AutoSize>() val nullableReference = paramMap[autoSize.reference]?.has(nullable) ?: false (sequenceOf(autoSize.reference) + autoSize.dependent.asSequence()).forEach { reference -> if (autoSizeReferences.contains(reference)) it.error("An AutoSize reference already exists for: $reference") autoSizeReferences.add(reference) val bufferParam = paramMap[reference] if (bufferParam == null) it.error("Buffer reference does not exist: AutoSize($reference)") else { when { !bufferParam.nativeType.isPointerData -> it.error("Buffer reference must be a data pointer: AutoSize($reference)") nullableReference && !bufferParam.has(nullable) -> it.error("If reference is nullable, dependent parameters must also be nullable: AutoSize($reference)") } if (bufferParam.nativeType is CharSequenceType && bufferParam.nativeType.charMapping == CharMapping.UTF16) it.replaceModifier(nativeClass.AutoSize(2, autoSize.reference, *autoSize.dependent)) } } } if (it.has<AutoSizeResultParam>()) { if (!returns.nativeType.isPointerData) it.error("Return type is not an array: AutoSizeResult") } if (it.isBufferPointer && it.nativeType !is CharSequenceType && !it.has<Check>() && !it.has<Unsafe>() && !hasAutoSizeFor(it) && !it.has<AutoSizeResultParam>() && !it.has<Terminated>() ) { it.error("Data pointer not validated with Check/AutoSize/Terminated. If validation is not possible, use the Unsafe modifier.") } if (it.has<AutoType>()) { val bufferParamName = it.get<AutoType>().reference val bufferParam = paramMap[bufferParamName] if (bufferParam == null) it.error("Buffer reference does not exist: AutoType($bufferParamName)") else when { bufferParam.nativeType !is PointerType<*> -> it.error("Buffer reference must be a pointer type: AutoType($bufferParamName)") bufferParam.nativeType.elementType !is VoidType -> it.error("Pointer reference must point to a void type: AutoType($bufferParamName)") } } if (it.has<Return>()) { returnCount++ if (1 < returnCount) it.error("More than one return value found.") val returnMod = it.get<Return>() if (returnMod === ReturnParam) { if (returns.isStructValue) { if (returns.nativeType != it.nativeType) it.error("The ReturnParam modifier can only be used on a struct value parameter if the function returns the same type.") } else if (!returns.isVoid) it.error("The ReturnParam modifier can only be used in functions with void return type.") } else { if (returnMod.lengthParam.startsWith(RESULT)) { if (!returns.nativeType.mapping.let { it === PrimitiveMapping.INT || it === PrimitiveMapping.POINTER }) it.error("The Return modifier was used in a function with an unsupported return type") if (!it.has<Check>()) { if (!hasAutoSizeFor(it)) it.error("A Check or AutoSize for ReturnParam parameter does not exist") else if (it.nativeType !is CharSequenceType) it.error("Return parameters with AutoSize must have a CharSequence type") } else if (it.get<Check>().expression != "1" || it.nativeType is CharSequenceType) it.error("Return parameters with Check must be pointers to a single primitive value") } else { if (!returns.isVoid) it.error("The Return modifier was used in a function with an unsupported return type") if (!hasAutoSizeFor(it)) it.error("An AutoSize for Return parameter does not exist") val lengthParam = paramMap[returnMod.lengthParam] if (lengthParam == null) it.error("The length parameter does not exist: Return(${returnMod.lengthParam})") else if (!lengthParam.nativeType.isPointerSize) it.error("The length parameter must be an integer pointer type: Return(${returnMod.lengthParam})") } } } if (it.has<PointerArray>()) { if (!hasAutoSizeFor(it)) it.error("An AutoSize for PointerArray parameter does not exist") val lengthsParamName = it.get<PointerArray>().lengthsParam val lengthsParam = paramMap[lengthsParamName] if (lengthsParam != null && !lengthsParam.nativeType.isPointerSize) it.error("Lengths reference must be an integer pointer type: PointerArray($lengthsParamName)") } if (it.nativeType === va_list && i != parameters.lastIndex) it.error("The va_list type can only be used on the last parameter of a function") } } private fun PrintWriter.generateChecks(mode: GenerationMode, transforms: Map<QualifiedType, Transform>? = null) { val checks = ArrayList<String>() // Validate function address if (hasFunctionAddressParam && (has<DependsOn>() || has<IgnoreMissing>() || (nativeClass.binding?.shouldCheckFunctionAddress(this@Func) == true)) && !hasUnsafeMethod) checks.add("check($FUNCTION_ADDRESS);") // We convert multi-byte-per-element buffers to ByteBuffer for NORMAL generation. // So we need to scale the length check by the number of bytes per element. fun bufferShift(expression: String, param: String, shift: String, transform: Transform?): String { val nativeType = paramMap[param]!!.nativeType val mapping = if (transform != null && transform is AutoTypeTargetTransform) { transform.autoType } else nativeType.mapping as PointerMapping if (!mapping.isMultiByte) return expression val builder = StringBuilder(expression.length + 8) if (expression.indexOf(' ') != -1) { builder .append('(') .append(expression) .append(')') } else builder.append(expression) return builder .append(' ') .append(shift) .append(' ') .append(mapping.byteShift) .toString() } // First pass getNativeParams().forEach { if (it.nativeType.mapping === PointerMapping.OPAQUE_POINTER) { if (!it.has(nullable) && !hasUnsafeMethod && it.nativeType !is WrappedPointerType && transforms?.get(it) !is SkipCheckFunctionTransform) checks.add("check(${it.name});") return@forEach } var Safe = if (it.has<Nullable>()) "Safe" else "" if (it.nativeType is CharSequenceType && !it.has<Check>() && !it.has<Unsafe>() && !hasAutoSizeFor(it) && transforms?.get(it) == null) checks.add("checkNT${it.nativeType.charMapping.bytes}$Safe(${it.name});") if (it.has<Terminated>()) { val postfix = if ((it.nativeType.mapping as PointerMapping).isMultiByte) "" else "1" checks.add("checkNT$postfix$Safe(${it.name}${it.get<Terminated>().let { terminated -> if (terminated === NullTerminated) "" else ", ${terminated.value}" }});") } if (it.has<Check>() && (!it.has<AutoSizeResultParam>() || !hideAutoSizeResultParam)) { val check = it.get<Check>() val transform = transforms?.get(it) if (transform !is SkipCheckFunctionTransform) { checks.add(when { it.has<MultiType>() -> "check$Safe(${it.name}, ${bufferShift(check.expression, it.name, ">>", transform)});" it.nativeType is StructType -> "check$Safe(${it.name}, ${bufferShift(check.expression, it.name, "<<", transform)});" else -> "check$Safe(${it.name}, ${check.expression});" }.let { code -> if (check.debug) "if (DEBUG) {\n$t$t$t$t$code\n$t$t$t}" else code}) } } if (it.has<AutoSize>()) { val autoSize = it.get<AutoSize>() if (mode === NORMAL || !it.isInput) { var expression = it.name if (!it.isInput) { expression += if (it.nativeType is ArrayType<*>) "[0]" else ".get($expression.position())" } else if (autoSize.factor != null) expression = autoSize.factor.scaleInv(expression) sequenceOf(autoSize.reference, *autoSize.dependent) .map { reference -> val bufferParam = paramMap[reference]!! Safe = if (bufferParam.has<Nullable>()) "Safe" else "" "check$Safe($reference, $expression);" } .let { expressions -> if (it.has<Nullable>()) { checks.add("if (${it.name} != null) { ${expressions.joinToString(" ")} }") } else { checks.addAll(expressions) } } } if (mode !== NORMAL) { val reference = paramMap[autoSize.reference]!! val referenceTransform = transforms!![reference] val expression = if (referenceTransform is SingleValueTransform || referenceTransform === PointerArrayTransformSingle) { "1" } else if (referenceTransform is PointerArrayTransform || reference.nativeType is ArrayType<*>) { if (reference has nullable) "lengthSafe(${autoSize.reference})" else "${autoSize.reference}.length" } else { if (reference has nullable) "remainingSafe(${autoSize.reference})" else "${autoSize.reference}.remaining()" } autoSize.dependent.forEach { dependency -> val param = paramMap[dependency]!! val transform = transforms[param] if (transform !is SkipCheckFunctionTransform) { Safe = if (param.has<Nullable>() && transform !is PointerArrayTransform) "Safe" else "" checks.add(if (transform === PointerArrayTransformArray) "check$Safe($dependency, $expression);" else "check$Safe($dependency, $expression);") } } } } } // Second pass getNativeParams() .filter { it.isInput && it.nativeType.hasStructValidation && !hasUnsafeMethod } .forEach { // Do this after the AutoSize check checks.add( sequenceOf( if (it.has<Check>()) it.get<Check>().expression else null, getReferenceParam<AutoSize>(it.name).let { autoSize -> if (autoSize == null) null else transforms?.get(autoSize).let { transform -> if (transform == null) autoSize.name else @Suppress("UNCHECKED_CAST") (transform as FunctionTransform<Parameter>).transformCall(autoSize, autoSize.name) }.let { name -> if (autoSize.nativeType.mapping === PrimitiveMapping.INT || name.endsWith(".remaining()")) name else "(int)$name" } } ) .firstOrNull { size -> size != null } .let { size -> if (size == null) "${it.nativeType.javaMethodType}.validate(${it.name}.address());" else "Struct.validate(${it.name}.address(), $size, ${it.nativeType.javaMethodType}.SIZEOF, ${it.nativeType.javaMethodType}::validate);" } .let { validation -> if (it.has<Nullable>()) "if (${it.name} != null) { $validation }" else validation } ) } // Third pass getNativeParams().forEach { // Special checks last nativeClass.binding?.addParameterChecks(checks, mode, it) { transform -> transforms?.get(this) === transform } } if (checks.isEmpty()) return println("$t${t}if (CHECKS) {") checks.forEach { print("$t$t$t") println(it) } println("$t$t}") } /** This is where we start generating java code. */ internal fun generateMethods(writer: PrintWriter) { val hasReuse = has<Reuse>() val nativeOnly = isNativeOnly val constantMacro = has<Macro> { constant } if (hasCustomJNI && !(hasReuse && nativeOnly)) writer.generateNativeMethod(constantMacro, nativeOnly, hasReuse) if (!nativeOnly || hasReuse) { if (hasUnsafeMethod) writer.generateUnsafeMethod(constantMacro, hasReuse) if ((returns.nativeType !is CharSequenceType || has<Address>() || has<MustBeDisposed>()) && parameters.none { (it.has<AutoSize>() && it.isInput) || it.has<Expression> { skipNormal } }) writer.generateJavaMethod(constantMacro, hasReuse) writer.generateAlternativeMethods() } if (constantMacro && !has(private)) { writer.println() writer.printDocumentation { true } writer.println("$t${accessModifier}static final ${if (returns.nativeType is CharSequenceType) "String" else returns.javaMethodType} $name = $name(${ if (returns.nativeType !is StructType) "" else "${returns.nativeType.javaMethodType}.create()" });") } } // --[ JAVA METHODS ]-- private fun <T> PrintWriter.printList(items: Sequence<T>, itemPrint: (item: T) -> String?) = print(items.map(itemPrint).filterNotNull().joinToString(", ")) private fun PrintWriter.printUnsafeJavadoc(private: Boolean, verbose: Boolean = false) { if (private) return val javadoc = documentation { it !== JNI_ENV } if (javadoc.isEmpty()) { if (verbose) nativeClass.binding?.printCustomJavadoc(this, this@Func, javadoc) return } if (verbose) { if (nativeClass.binding?.printCustomJavadoc(this, this@Func, javadoc) != true) println(javadoc) } else if (hasParam { it.nativeType is ArrayType<*> } && !has<OffHeapOnly>()) { println(nativeClass.processDocumentation("Array version of: ${nativeClass.className}#n$name()").toJavaDoc()) } else { getNativeParams().filter { it.documentation != null && ( it.has<AutoSize>() || it.has<AutoType>() || (it.isAutoSizeResultOut && hideAutoSizeResultParam) // TODO: more? ) }.let { hiddenParameters -> val documentation = nativeClass.processDocumentation("Unsafe version of: $javaDocLink") println(if (hiddenParameters.any()) nativeClass.toJavaDoc(documentation, hiddenParameters, returns.nativeType, "", null, "") else documentation.toJavaDoc() ) } } } private fun PrintWriter.generateNativeMethod(constantMacro: Boolean, nativeOnly: Boolean, hasReuse: Boolean) { println() printUnsafeJavadoc(constantMacro, nativeOnly) if (returns.nativeType is JObjectType && returnsNull) { println("$t@Nullable") } val retType = returns.nativeMethodType if (nativeOnly) { val retTypeAnnotation = returns.nativeType.annotation(retType) if (retTypeAnnotation != null) println("$t$retTypeAnnotation") } print("$t${if (constantMacro) "private " else accessModifier}static${if (hasReuse) "" else " native"} $retType ") if (!nativeOnly) print('n') print(name) print("(") val nativeParams = getNativeParams() printList(nativeParams) { it.asNativeMethodParam(nativeOnly) } if (hasFunctionAddressParam && !hasExplicitFunctionAddress) { if (nativeParams.any()) print(", ") print("long $FUNCTION_ADDRESS") } if (returns.isStructValue && !hasParam { it has ReturnParam }) { if (nativeClass.binding != null || nativeParams.any()) print(", ") print("long $RESULT") } if (hasReuse) { print(") {\n$t$t") if (retType != "void") print("return ") print("${get<Reuse>().source.className}.n$name(") printList(nativeParams) { it.name } if (hasFunctionAddressParam && !hasExplicitFunctionAddress) { if (nativeParams.any()) print(", ") print(FUNCTION_ADDRESS) } println(");\n$t}") } else { println(");") } } private fun PrintWriter.generateUnsafeMethod(constantMacro: Boolean, hasReuse: Boolean) { val customJNI = hasCustomJNI val useLibFFI = !customJNI && (returns.isStructValue || hasParam { it.nativeType is StructType }) if (useLibFFI) { println(""" private static final FFICIF ${name}CIF = apiCreateCIF( ${if (nativeClass.module.callingConvention == CallingConvention.DEFAULT) "FFI_DEFAULT_ABI" else "apiStdcall()"}, ${returns.nativeType.libffiType}, ${parameters.joinToString(", ") { it.nativeType.libffiType }} );""") } println() printUnsafeJavadoc(constantMacro) if (returns.nativeType is JObjectType && returnsNull) { println("$t@Nullable") } print("$t${if (constantMacro) "private " else accessModifier}static ${returns.nativeMethodType} n$name(") printList(getNativeParams()) { if (it.isFunctionProvider) it.asJavaMethodParam(false) else it.asNativeMethodParam(false) } if (returns.isStructValue && !hasParam { it has ReturnParam }) { if ([email protected]) print(", ") print("long $RESULT") } println(") {") if (hasReuse) { print("$t$t") if (returns.nativeMethodType != "void") { print("return ") } print("${get<Reuse>().source.className}.n$name(") printList(getNativeParams()) { it.name } println(");\n$t}") return } val binding = nativeClass.binding!! // Get function address if (!hasExplicitFunctionAddress && !constantMacro) binding.generateFunctionAddress(this, this@Func) if (Module.CHECKS) { // Basic checks val checks = ArrayList<String>(4) if (has<DependsOn>() || has<IgnoreMissing>() || binding.shouldCheckFunctionAddress(this@Func)) checks.add("check($FUNCTION_ADDRESS);") getNativeParams().forEach { if (it.nativeType.mapping === PointerMapping.OPAQUE_POINTER && !it.has(nullable) && it.nativeType !is WrappedPointerType) checks.add("check(${it.name});") else if (it.isInput && it.nativeType.hasStructValidation) checks.add( sequenceOf( if (it.has<Check>()) it.get<Check>().expression else null, getReferenceParam<AutoSize>(it.name).let { autoSize -> autoSize?.name?.let { name -> if (autoSize.nativeType.mapping === PrimitiveMapping.INT) name else "(int)$name" } } ) .firstOrNull { size -> size != null } .let { size -> if (size == null) "${it.nativeType.javaMethodType}.validate(${it.name});" else "Struct.validate(${it.name}, $size, ${it.nativeType.javaMethodType}.SIZEOF, ${it.nativeType.javaMethodType}::validate);" } .let { validation -> if (it.has<Nullable>()) "if (${it.name} != NULL) { $validation }" else validation } ) } if (checks.isNotEmpty()) { println("$t${t}if (CHECKS) {") checks.forEach { print("$t$t$t") println(it) } println("$t$t}") } } val hasReturnStatement = !(returns.isVoid || returns.isStructValue) // Native method call if (useLibFFI) { // TODO: This implementation takes advantage of MemoryStack's automatic alignment. Could be precomputed + hardcoded for more efficiency. // TODO: This implementation has not been tested with too many different signatures and probably contains bugs. println("""$t${t}MemoryStack stack = stackGet(); int stackPointer = stack.getPointer(); try { ${if (hasReturnStatement) { """long __result = stack.n${when { returns.nativeType.mapping == PrimitiveMapping.BOOLEAN -> "byte" returns.nativeType is PointerType<*> -> "pointer" else -> returns.nativeType.nativeMethodType }}(0); """ } else ""}long arguments = stack.nmalloc(POINTER_SIZE, POINTER_SIZE * ${parameters.size}); ${parameters.asSequence() .withIndex() .joinToString("\n$t$t$t") { (i, it) -> "memPutAddress(arguments${when (i) { 0 -> "" 1 -> " + POINTER_SIZE" else -> " + $i * POINTER_SIZE" }}, ${ if (it.nativeType is StructType) { it.name } else { "stack.n${when { it.nativeType.mapping == PrimitiveMapping.BOOLEAN -> "byte" it.nativeType is PointerType<*> -> "pointer" else -> it.nativeType.nativeMethodType }}(${it.name})" } });" } } nffi_call(${name}CIF.address(), $FUNCTION_ADDRESS, ${if (returns.isVoid) "NULL" else "__result"}, arguments);${if (hasReturnStatement) { """ return memGet${when { returns.nativeType.mapping == PrimitiveMapping.BOOLEAN -> "Byte" returns.nativeType is PointerType<*> -> "Address" else -> returns.nativeType.nativeMethodType.upperCaseFirst }}(__result);""" } else ""} } finally { stack.setPointer(stackPointer); }""") } else { print("$t$t") if (hasReturnStatement) print("return ") print(if (customJNI) "n$name(" else "${nativeClass.callingConvention.method}${getNativeParams(withExplicitFunctionAddress = false).map { it.nativeType.jniSignatureJava }.joinToString("")}${returns.nativeType.jniSignature}(" ) printList(getNativeParams()) { if (it.isFunctionProvider) "${it.name}.$ADDRESS" else it.name } if (!hasExplicitFunctionAddress) { if (hasNativeParams) print(", ") print(FUNCTION_ADDRESS) } if (returns.isStructValue && !hasParam { it has ReturnParam }) { print(", ") print(RESULT) } println(");") } println("$t}") } private fun PrintWriter.printDocumentation(parameterFilter: (Parameter) -> Boolean) { val doc = documentation(parameterFilter) val custom = nativeClass.binding?.printCustomJavadoc(this, this@Func, doc) ?: false if (!custom && doc.isNotEmpty()) println(doc) } private fun PrintWriter.generateJavaMethod(constantMacro: Boolean, hasReuse: Boolean) { println() // JavaDoc if (!constantMacro) { val hideAutoSizeResult = parameters.count { it.isAutoSizeResultOut } == 1 printDocumentation { !(hideAutoSizeResult && it.isAutoSizeResultOut) } } // Method signature if (returns.nativeType.isReference && returnsNull) { println("$t@Nullable") } val retType = returns.javaMethodType val retTypeAnnotation = returns.nativeType.annotation(retType) if (retTypeAnnotation != null) { println("$t$retTypeAnnotation") } print("$t${if (constantMacro) "private " else accessModifier}static ${if (has<MapPointer>() && returns.nativeType.dereference is StructType) "$retType.Buffer" else retType} $name(") printList(getNativeParams(withAutoSizeResultParams = false)) { it.asJavaMethodParam(true) } if (returns.isStructValue && !hasParam { it has ReturnParam }) { if (parameters.isNotEmpty()) print(", ") print("${returns.nativeType.annotate(retType)} $RESULT") } println(") {") if (hasReuse) { print("$t$t") if (retType != "void") { print("return ") } print("${get<Reuse>().source.className}.$name(") printList(getNativeParams()) { if (it.isAutoSizeResultOut && hideAutoSizeResultParam) null else it.name } println(");\n$t}") return } val hasArrays = hasParam { it.nativeType is ArrayType<*> } val code = if (has<Code>()) get() else Code.NO_CODE // Get function address if (hasFunctionAddressParam && !hasUnsafeMethod && !hasExplicitFunctionAddress && !has<Macro>()) nativeClass.binding!!.generateFunctionAddress(this, this@Func) // Generate checks printCode(code.javaInit, false, hasArrays) if (Module.CHECKS && !has<Macro>()) generateChecks(NORMAL) // Prepare stack parameters val hasStack = hideAutoSizeResultParam if (hasStack) { println("$t${t}MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();") val autoSizeParam = getParam { it.has<AutoSizeResultParam>() } val autoSizeType = (autoSizeParam.nativeType.mapping as PointerMapping).mallocType println("$t$t${autoSizeType}Buffer ${autoSizeParam.name} = stack.calloc$autoSizeType(1);") } val hasFinally = hasStack || code.hasStatements(code.javaFinally, false, hasArrays) // Call the native method generateCodeBeforeNative(code, false, hasArrays, hasFinally) if (hasCustomJNI || !has<Address>()) { generateNativeMethodCall( code, code.hasStatements(code.javaAfterNative, false, hasArrays), hasStack || code.hasStatements(code.javaFinally, false, hasArrays) ) { printList(getNativeParams()) { it.asNativeMethodArgument(NORMAL) } } } generateCodeAfterNative(code, false, hasArrays, hasFinally) if (returns.isStructValue) { println("${if (hasFinally) "$t$t$t" else "$t$t"}return ${getParams { it has ReturnParam }.map { it.name }.singleOrNull() ?: RESULT};") } else if (!returns.isVoid) { if (returns.nativeType is PointerType<*> && returns.nativeType.mapping !== PointerMapping.OPAQUE_POINTER) { if (hasFinally) print(t) print("$t${t}return ") val isNullTerminated = returns.nativeType is CharSequenceType print( if (returns.nativeType.dereference is StructType) { "${returns.nativeType.javaMethodType}.create" } else { "mem${if (isNullTerminated || returns.nativeType.elementType is VoidType) "ByteBuffer" else returns.nativeType.mapping.javaMethodName}" } ) if (isNullTerminated) { print("NT${(returns.nativeType as CharSequenceType).charMapping.bytes}") } if (returnsNull) { print("Safe") } print("($RESULT") if (has<MapPointer>()) get<MapPointer>().sizeExpression.let { expression -> val castToInt = paramMap[expression].run { this != null && nativeType.mapping !== PrimitiveMapping.INT } || expression.indexOf('(').run { if (this == -1) false else expression.substring(0, this).run { nativeClass.functions .singleOrNull { it.nativeName == this }?.let { it.returns.nativeType.mapping !== PrimitiveMapping.INT } ?: false } } print(", ${if (castToInt) "(int)" else ""}$expression") } else { val hasAutoSizeResult = hasParam { it.has<AutoSizeResultParam>() } if (!isNullTerminated || hasAutoSizeResult) { if (hasAutoSizeResult) { val params = getParams { it.has<AutoSizeResultParam>() } val single = params.count() == 1 print(", ${params.map { getAutoSizeResultExpression(single, it) }.joinToString(" * ")}") } else if (returns.nativeType.dereference !is StructType) { if (has<Address>()) { print(", 1") } else { throw IllegalStateException("No AutoSizeResult parameter could be found.") } } } } println(");") } else if (code.hasStatements(code.javaAfterNative, false, hasArrays)) { if (hasFinally) print(t) println("$t${t}return $RESULT;") } } generateCodeFinally(code, false, hasArrays, hasStack) println("$t}") } private fun PrintWriter.printCode(statements: List<Code.Statement>, alternative: Boolean, arrays: Boolean, indent: String = "") { if (statements.isEmpty()) return statements .filter { it.applyTo.filter(alternative, arrays) } .forEach { print(indent) println(it.code) } } private fun getAutoSizeResultExpression(single: Boolean, param: Parameter) = if (param.isInput) param.name.let { val custom = param.get<AutoSizeResultParam>().expression custom?.replace("\$original", it) ?: it.let { expression -> if (param.nativeType.mapping === PrimitiveMapping.INT) expression else "(int)$expression" } } else when { single -> "${param.name}.get(0)" param.nativeType is ArrayType<*> -> "${param.name}[0]" else -> "${param.name}.get(${param.name}.position())" }.let { val custom = param.get<AutoSizeResultParam>().expression custom?.replace("\$original", it) ?: it.let { expression -> if (param.nativeType.mapping === PointerMapping.DATA_INT) expression else "(int)$expression" } } private fun PrintWriter.generateCodeBeforeNative(code: Code, alternative: Boolean, arrays: Boolean, hasFinally: Boolean) { printCode(code.javaBeforeNative, alternative, arrays , "") if (hasFinally) { if (code.javaFinally.any { TRY_FINALLY_RESULT_REFERENCE.containsMatchIn(it.code) }) { val returnsObject = returns.nativeType is WrappedPointerType val returnType = if (returnsObject) (returns.nativeType as WrappedPointerType).className else returns.nativeMethodType println("$t${t}$returnType $RESULT = ${if (returnsObject) "null" else "NULL"};") // TODO: support more types if necessary } println("$t${t}try {") } } private fun PrintWriter.generateCodeAfterNative(code: Code, alternative: Boolean, arrays: Boolean, hasFinally: Boolean) { printCode(code.javaAfterNative, alternative, arrays, if (hasFinally) t else "") } private fun PrintWriter.generateCodeFinally(code: Code, alternative: Boolean, arrays: Boolean, hasStack: Boolean) { val finally = code.getStatements(code.javaFinally, alternative, arrays) if (hasStack || finally.isNotEmpty()) { println("$t$t} finally {") finally.forEach { println(it.code) } if (hasStack) println("$t$t${t}stack.setPointer(stackPointer);") println("$t$t}") } } private fun PrintWriter.generateNativeMethodCall( code: Code, returnLater: Boolean, hasFinally: Boolean, printParams: PrintWriter.() -> Unit ) { val returnsObject = returns.nativeType is WrappedPointerType val returnType = if (returnsObject) (returns.nativeType as WrappedPointerType).className else returns.nativeMethodType if (hasFinally) print(t) print("$t$t") if (!(returns.isVoid || returns.isStructValue)) { if (returnLater || returns.nativeType.isPointerData) { if (!hasFinally || code.javaFinally.none { TRY_FINALLY_RESULT_REFERENCE.containsMatchIn(it.code) }) { print("$returnType ") } print("$RESULT = ") if (returnsObject) print("$returnType.createSafe(") } else { print("return ") if (returnsObject) print("$returnType.createSafe(") } } val macroExpression = if (has<Macro>()) get<Macro>().expression else null if (hasUnsafeMethod) { print("n$name(") } else { if (hasCustomJNI) { if (!isNativeOnly) { print('n') } print("$name(") } else { print(macroExpression ?: "${nativeClass.callingConvention.method}${getNativeParams(withExplicitFunctionAddress = false) .map { it.nativeType.jniSignatureJava } .joinToString("") }${returns.nativeType.jniSignature}(") } } if (macroExpression == null) { printParams() if (!hasUnsafeMethod && hasFunctionAddressParam && !hasExplicitFunctionAddress && !has<Macro>()) { if (hasNativeParams) print(", ") print(FUNCTION_ADDRESS) } if (returns.isStructValue && !hasParam { it has ReturnParam }) { if (hasNativeParams) print(", ") print("$RESULT.$ADDRESS") } print(")") } if (returnsObject) { if (has<Construct>()) { val construct = get<Construct>() print(", ${construct.firstArg}") for (arg in construct.otherArgs) print(", $arg") } print(")") } if (returns.nativeType.mapping == PrimitiveMapping.BOOLEAN4) print(" != 0") println(";") } /** Alternative methods are generated by applying one or more transformations. */ private fun PrintWriter.generateAlternativeMethods() { val transforms = LinkedHashMap<QualifiedType, Transform>() nativeClass.binding?.generateAlternativeMethods(this, this@Func, transforms) // Apply RawPointer transformations. parameters.filter { it.has<RawPointer>() && it.nativeType !is ArrayType<*> }.let { params -> if (params.isEmpty()) return@let params.forEach { transforms[it] = RawPointerTransform } generateAlternativeMethod(name, transforms) params.forEach { transforms.remove(it) } } if (returns.nativeType is CharSequenceType && !has<Address>() && !has<MustBeDisposed>()) transforms[returns] = StringReturnTransform(returnsNull) else if (has<MapPointer>()) { val mapPointer = get<MapPointer>() if (mapPointer.oldBufferOverloads) { transforms[returns] = if (paramMap.containsKey(mapPointer.sizeExpression)) MapPointerExplicitTransform(mapPointer.sizeExpression, useOldBuffer = true, addParam = false) else MapPointerTransform(mapPointer.sizeExpression, useOldBuffer = true) } } // Apply basic transformations parameters.forEach { if (it.has<AutoSize>() && it.isInput) { val autoSize = it.get<AutoSize>() val param = paramMap[autoSize.reference]!! // TODO: Check dependent too? // Check if there's also an optional on the referenced parameter. Skip if so. if (!(param has optional)) transforms[it] = AutoSizeTransform(param, hasCustomJNI || hasUnsafeMethod) } else if (it has optional) { transforms[it] = ExpressionTransform("NULL") } else if (it.has<Expression>()) { // We do this here in case another transform applies too. // We overwrite the value with the expression but use the type of the other transform. val expression = it.get<Expression>() transforms[it] = ExpressionTransform(expression.value, expression.keepParam, @Suppress("UNCHECKED_CAST") (transforms[it] as FunctionTransform<Parameter>?)) } } // Check if we have any basic transformations to apply if (transforms.isNotEmpty()) generateAlternativeMethod(name, transforms) // Generate more complex alternatives if necessary // The size expression may be an existing parameter, in which case we don't need an explicit size alternative. if (has<MapPointer> { !paramMap.containsKey(sizeExpression) }) { transforms[returns] = MapPointerExplicitTransform("length", get<MapPointer>().oldBufferOverloads) generateAlternativeMethod(name, transforms) } // Apply any CharSequenceTransforms. These can be combined with any of the other transformations. @Suppress("ReplaceSizeCheckWithIsNotEmpty") if (parameters.count { if (!it.isInput || it.nativeType !is CharSequenceType) false else { val hasAutoSize = hasAutoSizeFor(it) it.apply { if (hasAutoSize) getParams(hasReference<AutoSize>(this)).forEach { param -> transforms[param] = AutoSizeCharSequenceTransform(this) } } transforms[it] = CharSequenceTransform(!hasAutoSize) true } } != 0) generateAlternativeMethod(name, transforms) fun applyReturnValueTransforms(param: Parameter) { // Transform void to the proper type transforms[returns] = PrimitiveValueReturnTransform(param.nativeType as PointerType<*>, param.name) // Transform the AutoSize parameter, if there is one getParams(hasReference<AutoSize>(param)).forEach { transforms[it] = Expression1Transform } // Transform the returnValue parameter transforms[param] = PrimitiveValueTransform } // Apply any complex transformations. parameters.forEach { if (it.has<Return>() && !hasParam { param -> param.has<PointerArray>() }) { val returnMod = it.get<Return>() if (returnMod === ReturnParam && returns.isVoid && it.nativeType !is CharSequenceType) { if (!hasParam { param -> param.has<SingleValue>() || param.has<PointerArray>() }) { // Skip, we inject the Return alternative in these transforms applyReturnValueTransforms(it) generateAlternativeMethod(stripPostfix(), transforms) } } else if (it.nativeType is CharSequenceType) { // Remove any transform from the maxLength parameter val maxLengthParam = getParam(hasReference<AutoSize>(it)) transforms.remove(maxLengthParam) // Hide length parameter and use the stack val lengthParam = returnMod.lengthParam if (lengthParam.isNotEmpty() && lengthParam !== RESULT) transforms[paramMap[lengthParam]!!] = BufferLengthTransform // Hide target parameter and decode internally val bufferAutoSizeTransform: FunctionTransform<Parameter> = if (returnMod.heapAllocate) StringAutoSizeTransform(maxLengthParam) else StringAutoSizeStackTransform(maxLengthParam) transforms[it] = bufferAutoSizeTransform // Transform void to the buffer type transforms[returns] = if (lengthParam.isNotEmpty()) BufferReturnTransform(it, lengthParam, it.nativeType.charMapping, returnMod.includesNT) else BufferReturnNTTransform( it, if (4 < (maxLengthParam.nativeType.mapping as PrimitiveMapping).bytes) "(int)${maxLengthParam.name}" else maxLengthParam.name ) generateAlternativeMethod(name, transforms) if (returnMod.maxLengthExpression != null) { // Transform maxLength parameter and generate an additional alternative transforms[maxLengthParam] = ExpressionTransform(returnMod.maxLengthExpression) generateAlternativeMethodDelegate(name, transforms) } } else if (returnMod.lengthParam.startsWith(RESULT)) { transforms[returns] = BufferAutoSizeReturnTransform(it, returnMod.lengthParam) transforms[it] = BufferReplaceReturnTransform generateAlternativeMethod(name, transforms) } else { check(!returns.isVoid) } } else if (it.has<AutoType>()) { // Generate AutoType alternatives val autoTypes = it.get<AutoType>() val bufferParam = paramMap[autoTypes.reference]!! // Disable AutoSize factor val autoSizeParam = getReferenceParam<AutoSize>(bufferParam.name) if (autoSizeParam != null) transforms[autoSizeParam] = AutoSizeTransform(bufferParam, hasCustomJNI || hasUnsafeMethod, applyFactor = false) for (autoType in autoTypes.types) { transforms[it] = AutoTypeParamTransform("${autoType.className}.${autoType.name}") transforms[bufferParam] = AutoTypeTargetTransform(autoType.mapping) generateAlternativeMethod(name, transforms) } transforms.remove(bufferParam) transforms.remove(it) } } // Apply any MultiType transformations. parameters.filter { it.has<MultiType>() }.let { params -> if (params.isEmpty()) return@let check(params.groupBy { it.get<MultiType>().types.contentHashCode() }.size == 1) { "All MultiType modifiers in a function must have the same structure." } // Add the AutoSize transformation if we skipped it above getParams { it.has<AutoSize>() }.forEach { val autoSize = it.get<AutoSize>() transforms[it] = AutoSizeTransform(paramMap[autoSize.reference]!!, hasCustomJNI || hasUnsafeMethod) } var multiTypes = params.first().get<MultiType>().types.asSequence() if (params.any { it has optional }) multiTypes = sequenceOf(PointerMapping.DATA_BYTE) + multiTypes for (autoType in multiTypes) { params.forEach { // Transform the AutoSize parameter, if there is one getReferenceParam<AutoSize>(it.name).let { autoSizeParam -> if (autoSizeParam != null) transforms[autoSizeParam] = AutoSizeTransform(it, hasCustomJNI || hasUnsafeMethod, autoType.byteShift) } transforms[it] = AutoTypeTargetTransform(autoType) } generateAlternativeMethod(name, transforms) } val singleValueParams = params.filter { it.has<SingleValue>() } if (singleValueParams.any()) { // Generate a SingleValue alternative for each type for (autoType in multiTypes) { val primitiveType = autoType.box.lowercase() // Generate type1, type2, type4 versions // TODO: Make customizable? New modifier? for (i in 1..4) { if (i == 3) { continue } singleValueParams.forEach { // Transform the AutoSize parameter val autoSizeParam = getParam(hasReference<AutoSize>(it)) // required transforms[autoSizeParam] = ExpressionTransform("(1 << ${autoType.byteShift}) * $i") val singleValue = it.get<SingleValue>() transforms[it] = VectorValueTransform(autoType, primitiveType, singleValue.newName, i) } generateAlternativeMethod("$name$i${primitiveType[0]}", transforms) } } singleValueParams.forEach { transforms.remove(getParam(hasReference<AutoSize>(it))) } } params.forEach { getReferenceParam<AutoSize>(it.name).let { param -> if (param != null) transforms.remove(param) } transforms.remove(it) } } // Apply any PointerArray transformations. parameters.filter { it.has<PointerArray>() }.let { params -> if (params.isEmpty()) return@let fun Parameter.getAutoSizeReference(): Parameter? = getParams { it.has<AutoSize> { reference == [email protected] } }.firstOrNull() // Array version params.forEach { val pointerArray = it.get<PointerArray>() val lengthsParam = paramMap[pointerArray.lengthsParam] if (lengthsParam != null) transforms[lengthsParam] = PointerArrayLengthsTransform(it, true) val countParam = it.getAutoSizeReference() if (countParam != null) transforms[countParam] = ExpressionTransform("${it.name}.length") transforms[it] = if (it === parameters.last { param -> param !== lengthsParam && param !== countParam // these will be hidden, ignore }) PointerArrayTransformVararg else PointerArrayTransformArray } generateAlternativeMethod(name, transforms) // Combine PointerArrayTransformSingle with BufferValueReturnTransform getParams { it has ReturnParam }.forEach(::applyReturnValueTransforms) // Single value version params.forEach { val pointerArray = it.get<PointerArray>() val lengthsParam = paramMap[pointerArray.lengthsParam] if (lengthsParam != null) transforms[lengthsParam] = PointerArrayLengthsTransform(it, false) val countParam = it.getAutoSizeReference() if (countParam != null) transforms[countParam] = ExpressionTransform("1") transforms[it] = PointerArrayTransformSingle } generateAlternativeMethod(name, transforms) // Cleanup params.forEach { val countParam = it.getAutoSizeReference() if (countParam != null) transforms.remove(countParam) transforms.remove(it) } } // Apply any SingleValue transformations. @Suppress("ReplaceSizeCheckWithIsNotEmpty") if (parameters.count { if (!it.has<SingleValue>() || it.has<MultiType>()) { false } else { // Compine SingleValueTransform with BufferValueReturnTransform getParams { param -> param has ReturnParam }.forEach(::applyReturnValueTransforms) // Transform the AutoSize parameter, if there is one getParams(hasReference<AutoSize>(it)).forEach { param -> transforms[param] = Expression1Transform } val singleValue = it.get<SingleValue>() val pointerType = it.nativeType as PointerType<*> if (pointerType.elementType is StructType) { transforms[it] = SingleValueStructTransform(singleValue.newName) } else { transforms[it] = SingleValueTransform( when (pointerType.elementType) { is CharSequenceType -> "CharSequence" is WrappedPointerType -> pointerType.elementType.className is StructType -> it.javaMethodType is PointerType<*> -> "long" else -> pointerType.elementType.javaMethodType }, pointerType.mapping.box.lowercase(), singleValue.newName ) } true } } != 0) generateAlternativeMethod(stripPostfix(), transforms) } private fun <T : QualifiedType> T.transformDeclarationOrElse(transforms: Map<QualifiedType, Transform>, original: String, annotate: Boolean): String? { val transform = transforms[this] return ( if (transform == null) original else @Suppress("UNCHECKED_CAST") (transform as FunctionTransform<T>).transformDeclaration(this, original) ).let { if (!annotate || it == null) it else { val space = it.lastIndexOf(' ') "${nativeType.annotate(it.substring(0, space))} ${it.substring(space + 1)}" } } } private fun <T : QualifiedType> T.transformCallOrElse(transforms: Map<QualifiedType, Transform>, original: String): String { val transform = transforms[this] if (transform == null || this is Parameter && this.has(UseVariable)) return original else @Suppress("UNCHECKED_CAST") return (transform as FunctionTransform<T>).transformCall(this, original) } private fun PrintWriter.generateAlternativeMethodSignature( name: String, transforms: Map<QualifiedType, Transform>, description: String? = null, constantMacro: Boolean ): String { // JavaDoc if (!constantMacro) { if (description != null) { val doc = nativeClass.processDocumentation("$description $javaDocLink").toJavaDoc() val custom = nativeClass.binding?.printCustomJavadoc(this, this@Func, doc) ?: false if (!custom && doc.isNotEmpty()) println(doc) } else { val hideAutoSizeResult = parameters.count { it.isAutoSizeResultOut } == 1 printDocumentation { param -> !(hideAutoSizeResult && param.isAutoSizeResultOut) && transforms[param].let { @Suppress("UNCHECKED_CAST") (it == null || (it as FunctionTransform<Parameter>).transformDeclaration(param, param.name) .let { declaration -> declaration != null && declaration.endsWith(param.name) }) } } } } // Method signature val retType = returns.transformDeclarationOrElse(transforms, returns.javaMethodType, false)!! if ((returns.nativeType.isReference && returnsNull) || (transforms[returns].let { it is FunctionTransform<*> && it.forceNullable }) ) { println("$t@Nullable") } val retTypeAnnotation = returns.nativeType.annotation(retType) if (retTypeAnnotation != null) { println("$t$retTypeAnnotation") } print("$t${if (constantMacro) "private " else accessModifier}static $retType $name(") printList(getNativeParams(withAutoSizeResultParams = false)) { param -> param.transformDeclarationOrElse(transforms, param.asJavaMethodParam(false), true).let { if ( it != null && param.nativeType.isReference && param.has(nullable) && transforms[param] !is SingleValueTransform && transforms[param] !is SingleValueStructTransform ) { "@Nullable $it" } else { it } } } // Update Reuse delegation if the code below changes when (val returnTransform = transforms[returns]) { is MapPointerTransform -> { if (returnTransform.useOldBuffer) { if (parameters.isNotEmpty()) print(", ") print("@Nullable ByteBuffer $MAP_OLD") } } is MapPointerExplicitTransform -> { var hasParams = parameters.isNotEmpty() if (returnTransform.addParam) { if (hasParams) print(", ") else hasParams = true print("long ${returnTransform.lengthParam}") } if (returnTransform.useOldBuffer) { if (hasParams) print(", ") print("@Nullable ByteBuffer $MAP_OLD") } } } if (returns.isStructValue) { if (parameters.isNotEmpty()) print(", ") print("${returns.nativeType.annotate(retType)} $RESULT") } println(") {") return retType } private fun PrintWriter.generateAlternativeMethod( name: String, transforms: Map<QualifiedType, Transform>, description: String? = null ) { println() val macro = has<Macro>() val retType = generateAlternativeMethodSignature(name, transforms, description, macro && get<Macro>().constant) if (has<Reuse>()) { print("$t$t") if (retType != "void") { print("return ") } print("${get<Reuse>().source.className}.$name(") printList(getNativeParams(withAutoSizeResultParams = false)) { it.transformDeclarationOrElse(transforms, it.name, false).let { name -> name?.substring(name.lastIndexOf(' ') + 1) } } when (val returnTransform = transforms[returns]) { is MapPointerTransform -> { if (returnTransform.useOldBuffer) { if (parameters.isNotEmpty()) print(", ") print(MAP_OLD) } } is MapPointerExplicitTransform -> { var hasParams = parameters.isNotEmpty() if (returnTransform.addParam) { if (hasParams) print(", ") else hasParams = true print(returnTransform.lengthParam) } if (returnTransform.useOldBuffer) { if (hasParams) print(", ") print(MAP_OLD) } } } if (returns.isStructValue) { if (parameters.isNotEmpty()) print(", ") print(RESULT) } println(");\n$t}") return } // Append CodeFunctionTransform statements to Code val hasArrays = hasParam { it.nativeType is ArrayType<*> } val code = transforms .asSequence() .filter { it.value is CodeFunctionTransform<*> } .fold(if (has<Code>()) get() else Code.NO_CODE) { code, (qtype, transform) -> @Suppress("UNCHECKED_CAST") (transform as CodeFunctionTransform<QualifiedType>).generate(qtype, code) } // Get function address if (hasFunctionAddressParam && !hasUnsafeMethod && !has<Macro>()) nativeClass.binding!!.generateFunctionAddress(this, this@Func) // Generate checks transforms .asSequence() .filter { it.key.let { qt -> qt is Parameter && qt.has<UseVariable>() } } .forEach { val param = it.key as Parameter @Suppress("UNCHECKED_CAST") val transform = it.value as FunctionTransform<Parameter> println("$t$t${param.asJavaMethodParam(false)} = ${transform.transformCall(param, param.name)};") } printCode(code.javaInit, true, hasArrays) if (Module.CHECKS && !macro) generateChecks(ALTERNATIVE, transforms) // Prepare stack parameters val stackTransforms = if (macro) emptySequence() else transforms.asSequence().filter { it.value is StackFunctionTransform<*> } val hideAutoSizeResultParam = [email protected] val hasStack = (hideAutoSizeResultParam || stackTransforms.any()) && !macro if (hasStack) println("$t${t}MemoryStack stack = stackGet(); int stackPointer = stack.getPointer();") val hasFinally = hasStack || code.hasStatements(code.javaFinally, true, hasArrays) // Call the native method generateCodeBeforeNative(code, true, hasArrays, hasFinally) if (hideAutoSizeResultParam) { val autoSizeParam = getParam { it.has<AutoSizeResultParam>() } val autoSizeType = (autoSizeParam.nativeType.mapping as PointerMapping).mallocType println("$t$t$t${autoSizeType}Buffer ${autoSizeParam.name} = stack.calloc$autoSizeType(1);") } for ((qtype, transform) in stackTransforms) { @Suppress("UNCHECKED_CAST") when (qtype) { is Parameter -> (transform as StackFunctionTransform<Parameter>).setupStack(this@Func, qtype, this) is ReturnValue -> (transform as StackFunctionTransform<ReturnValue>).setupStack(this@Func, qtype, this) } } val returnLater = code.hasStatements(code.javaAfterNative, true, hasArrays) || transforms[returns] is ReturnLaterTransform generateNativeMethodCall(code, returnLater, hasFinally) { printList(getNativeParams()) { it.transformCallOrElse(transforms, it.asNativeMethodArgument(ALTERNATIVE)) } } generateCodeAfterNative(code, true, hasArrays, hasFinally) // Return if (returns.isVoid || returns.isStructValue) { // TODO: struct value + custom transform? val result = returns.transformCallOrElse(transforms, "") if (result.isNotEmpty()) { println(if (hasFinally) result.replace(TRY_FINALLY_ALIGN, "$t$1") else result) } else if (returns.isStructValue) println("${if (hasFinally) "$t$t$t" else "$t$t"}return $RESULT;") } else { if (returns.nativeType is PointerType<*> && returns.nativeType.mapping !== PointerMapping.OPAQUE_POINTER) { if (hasFinally) print(t) print("$t$t") val builder = StringBuilder() val isNullTerminated = returns.nativeType is CharSequenceType builder.append( if (returns.nativeType.dereference is StructType) { "${returns.nativeType.javaMethodType}.create" } else { "mem${if (isNullTerminated || returns.nativeType.elementType is VoidType) "ByteBuffer" else returns.nativeType.mapping.javaMethodName}" } ) if (isNullTerminated) { builder.append("NT${(returns.nativeType as CharSequenceType).charMapping.bytes}") } else if (returnsNull) { builder.append("Safe") } builder.append("($RESULT") if (has<MapPointer>()) builder.append(", ${get<MapPointer>().sizeExpression}") else { val hasAutoSizeResult = hasParam { it.has<AutoSizeResultParam>() } if (!isNullTerminated || hasAutoSizeResult) { if (hasAutoSizeResult) { val params = getParams { it.has<AutoSizeResultParam>() } val single = params.count() == 1 builder.append(", ${params.map { getAutoSizeResultExpression(single, it) }.joinToString(" * ")}") } else { check(returns.nativeType.dereference is StructType) { "No AutoSizeResult parameter could be found." } } } } builder.append(")") val returnExpression = returns.transformCallOrElse(transforms, builder.toString()) if (returnExpression.indexOf('\n') == -1) println("return $returnExpression;") else // Multiple statements, assumes the transformation includes the return statement. println(returnExpression) } else if (returnLater) { if (hasFinally) print(t) println(returns.transformCallOrElse(transforms, "$t${t}return $RESULT;")) } } generateCodeFinally(code, true, hasArrays, hasStack) println("$t}") } private fun PrintWriter.generateAlternativeMethodDelegate( name: String, transforms: Map<QualifiedType, Transform>, description: String? = null ) { println() generateAlternativeMethodSignature(name, transforms, description, has<Macro> { constant }) // Call the native method print("$t$t") if (!((returns.isVoid && transforms[returns] == null) || returns.isStructValue)) print("return ") print("$name(") printList(getNativeParams().filter { @Suppress("UNCHECKED_CAST") val t = transforms[it] as FunctionTransform<Parameter>? t == null || t is ExpressionTransform || t.transformDeclaration(it, it.asJavaMethodParam(false)) != null }) { val t = transforms[it] if (t is ExpressionTransform) t.transformCall(it, it.asNativeMethodArgument(ALTERNATIVE)) else it.name } println(");") println("$t}") } // --[ JNI FUNCTIONS ]-- internal fun generateFunctionDefinition(writer: PrintWriter) = writer.generateFunctionDefinitionImpl() private fun PrintWriter.generateFunctionDefinitionImpl() { print("typedef ${returns.toNativeType(nativeClass.binding)} (") if (nativeClass.callingConvention !== CallingConvention.DEFAULT) print("APIENTRY ") print("*${nativeName}PROC) (") val nativeParams = getNativeParams(withExplicitFunctionAddress = false, withJNIEnv = true) if (nativeParams.any()) { printList(nativeParams) { it.toNativeType(nativeClass.binding) } } else print("void") println(");") } internal fun generateFunction(writer: PrintWriter) { val hasArrays = hasParam { it.nativeType is ArrayType<*> } val hasCritical = false && nativeClass.binding?.apiCapabilities != APICapabilities.JNI_CAPABILITIES && !parameters.contains(JNI_ENV) if (hasCritical) { writer.generateFunctionImpl(hasArrays, hasCritical, critical = true) } writer.generateFunctionImpl(hasArrays, hasCritical, critical = false) } private fun PrintWriter.generateFunctionImpl(hasArrays: Boolean, hasCritical: Boolean, critical: Boolean) { val params = ArrayList<String>(4 + parameters.size) if (!critical) params.add("JNIEnv *$JNIENV, jclass clazz") getNativeParams(withExplicitFunctionAddress = false).map { if (it.nativeType is ArrayType<*>) { if (critical) "jint ${it.name}__length, j${it.nativeType.mapping.primitive}* ${it.name}" else "j${it.nativeType.mapping.primitive}Array ${it.name}$POINTER_POSTFIX" } else { "${it.nativeType.jniFunctionType} ${it.name}${if (it.nativeType is PointerType<*> || it.nativeType is StructType) POINTER_POSTFIX else ""}" } }.toCollection(params) if (hasFunctionAddressParam) params.add("jlong $FUNCTION_ADDRESS") if (returns.isStructValue && !hasParam { it has ReturnParam }) params.add("jlong $RESULT") // Function signature print("JNIEXPORT${if (critical && workaroundJDK8167409()) "_CRITICAL" else ""} ${returns.jniFunctionType} JNICALL ${JNI_NAME(hasArrays, critical)}") println("(${if (params.isEmpty()) "void" else params.joinToString(", ")}) {") if (hasCritical && !(critical || hasArrays)) { // Unused parameter macro printUnusedParameters(false) print(t) if (!returns.isVoid && !returns.isStructValue) print("return ") print(JNI_NAME(hasArrays, critical = true, ignoreArrayType = true)) print('(') params.clear() getNativeParams(withExplicitFunctionAddress = true, withJNIEnv = false) .mapTo(params) { "${it.name}${if (it.nativeType is PointerType<*> || it.nativeType is StructType) POINTER_POSTFIX else ""}" } if (hasFunctionAddressParam) params.add(FUNCTION_ADDRESS) if (returns.isStructValue && !hasParam { it has ReturnParam }) params.add(RESULT) print(params.joinToString(", ")) println(");") println("}") return } // Cast function address to pointer if (nativeClass.binding != null) { if (hasFunctionAddressParam) { println("$t${nativeName}PROC $nativeName = (${nativeName}PROC)(uintptr_t)$FUNCTION_ADDRESS;") } else println("$t${nativeName}PROC $nativeName = (${nativeName}PROC)tlsGetFunction(${nativeClass.binding.getFunctionOrdinal(this@Func)});") } // Cast addresses to pointers if (!hasCritical || !hasArrays) { getNativeParams(withExplicitFunctionAddress = false) .filter { it.nativeType.castAddressToPointer } .forEach { val variableType = if (it.nativeType === va_list) "va_list *" else it.toNativeType(nativeClass.binding, pointerMode = true) print(t) if (it.nativeType is FunctionType && variableType.contains("(*)")) { print(variableType.replace("(*)", "(*${it.name})")) } else { print(variableType) if (!variableType.endsWith('*')) { print(' ') } print(it.name) } println( " = ${if (it.nativeType === va_list) { "VA_LIST_CAST" } else { "($variableType)" } }${if (variableType != "uintptr_t") "(uintptr_t)" else ""}${it.name}$POINTER_POSTFIX;" ) } } // Custom code var code = if (has<Code>()) get() else Code.NO_CODE if (hasArrays) { if (!critical) { code = code.append( nativeBeforeCall = getParams { it.nativeType is ArrayType<*> }.map { "j${(it.nativeType.mapping as PointerMapping).primitive} *${it.name} = ${ "(*$JNIENV)->Get${(it.nativeType as PointerType<*>).mapping.box}ArrayElements($JNIENV, ${it.name}$POINTER_POSTFIX, NULL)".let { expression -> if (it.has<Nullable>()) "${it.name}$POINTER_POSTFIX == NULL ? NULL : $expression" else expression }};" }.joinToString("\n$t", prefix = t), nativeAfterCall = getParams { it.nativeType is ArrayType<*> } .withIndex() .sortedByDescending { it.index } .map { it.value } .map { "(*$JNIENV)->Release${(it.nativeType as PointerType<*>).mapping.box}ArrayElements($JNIENV, ${it.name}$POINTER_POSTFIX, ${it.name}, 0);".let { expression -> if (it.has<Nullable>()) "if (${it.name} != NULL) { $expression }" else expression } }.joinToString("\n$t", prefix = t) ) } if (hasCritical) { val callPrefix = if (!returns.isVoid && !returns.isStructValue) { if (critical) "return " else "$RESULT = " } else { "" } code = code.append( nativeCall = "$t$callPrefix${JNI_NAME(hasArrays = true, critical = true, ignoreArrayType = true)}(${getNativeParams() .map { if (it.nativeType is ArrayType<*>) "(uintptr_t)${it.name}" else "${it.name}${if (it.nativeType is PointerType<*> || it.nativeType is StructType) POINTER_POSTFIX else ""}" } .joinToString(", ") }${if (returns.isStructValue) ", $RESULT" else ""});" ) } } if (code.nativeAfterCall != null && !returns.isVoid && !returns.isStructValue) println("$t${returns.jniFunctionType} $RESULT;") code.nativeBeforeCall.let { if (it != null) println(it) } // Unused parameter macro printUnusedParameters(critical) // Call native function code.nativeCall.let { call -> if (call != null) println(call) else { print(t) if (returns.isStructValue) { getParams { it has ReturnParam }.map { it.name }.singleOrNull().let { print(if (it != null) "*$it = " else "*((${returns.nativeType.name}*)(uintptr_t)$RESULT) = " ) } } else if (!returns.isVoid) { print(if (code.nativeAfterCall != null) "$RESULT = " else "return ") if (returns.jniFunctionType != returns.nativeType.name) print("(${returns.jniFunctionType})") if (returns.nativeType is PointerType<*> && nativeClass.binding == null) print("(uintptr_t)") if (has<Address>()) print('&') } if (parameters.isNotEmpty() && parameters[0] === JNI_ENV && nativeClass.className == "JNINativeInterface") print("(*$JNIENV)->") print(nativeName) if (!has<Macro> { !function }) print('(') printList(getNativeParams(withExplicitFunctionAddress = false, withJNIEnv = true)) { param -> param.nativeType.let { if (it is StructType || it === va_list) "*${param.name}" else if (!it.castAddressToPointer) { val nativeType = param.toNativeType(nativeClass.binding) if (nativeType != it.jniFunctionType && "j$nativeType" != it.jniFunctionType) "($nativeType)${param.name}" // Avoid implicit cast warnings else param.name } else param.name } } if (!has<Macro> { !function }) print(')') println(';') } } code.nativeAfterCall.let { if (it == null) return@let println(it) if (!returns.isVoid && !returns.isStructValue) println("${t}return $RESULT;") } println("}") } private fun workaroundJDK8167409(ignoreArrayType: Boolean = false): Boolean = parameters.size.let { 6 <= it || (5 <= it && returns.isStructValue && !hasParam { param -> param has ReturnParam }) } && parameters[0].nativeType.let { type -> (type is PointerType<*> && (ignoreArrayType || type !is ArrayType<*>)) || type.mapping.let { it is PrimitiveMapping && 4 < it.bytes } } private fun JNI_NAME(hasArrays: Boolean, critical: Boolean, ignoreArrayType: Boolean = false): String { return "${nativeClass.nativeFileNameJNI}_${if (isNativeOnly) "" else "n"}${name.asJNIName}${if (nativeClass.module.arrayOverloads && (hasArrays || hasArrayOverloads)) getNativeParams(withExplicitFunctionAddress = false) .map { if (it.nativeType is ArrayType<*> && !(critical && ignoreArrayType)) it.nativeType.jniSignatureArray else it.nativeType.jniSignatureStrict } .joinToString( "", prefix = "__", postfix = "J".repeat((if (returns.isStructValue) 1 else 0) + (if (hasFunctionAddressParam) 1 else 0)) ) else "" }".let { if (critical) { if (workaroundJDK8167409(ignoreArrayType)) "CRITICAL($it)" else "JavaCritical_$it" } else { "Java_$it" } } } private fun PrintWriter.printUnusedParameters(critical: Boolean) { if (!critical) println( if (parameters.contains(JNI_ENV) || (nativeClass.binding != null && !hasFunctionAddressParam)) "${t}UNUSED_PARAM(clazz)" else "${t}UNUSED_PARAMS($JNIENV, clazz)" ) else getParams { it.nativeType is ArrayType<*> }.forEach { println("${t}UNUSED_PARAM(${it.name}__length)") } } }
modules/generator/src/main/kotlin/org/lwjgl/generator/Functions.kt
2406639025
/* * 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.fhir.datacapture import org.hl7.fhir.r4.model.CanonicalType import org.hl7.fhir.r4.model.Expression import org.hl7.fhir.r4.model.Questionnaire /** * The StructureMap url in the * [target structure-map extension](http://build.fhir.org/ig/HL7/sdc/StructureDefinition-sdc-questionnaire-targetStructureMap.html) * s. */ val Questionnaire.targetStructureMap: String? get() { val extensionValue = this.extension.singleOrNull { it.url == TARGET_STRUCTURE_MAP }?.value ?: return null return if (extensionValue is CanonicalType) extensionValue.valueAsString else null } internal val Questionnaire.variableExpressions: List<Expression> get() = this.extension.filter { it.url == EXTENSION_VARIABLE_URL }.map { it.castToExpression(it.value) } /** * Finds the specific variable name [String] at questionnaire [Questionnaire] level * * @param variableName the [String] to match the variable at questionnaire [Questionnaire] level * @return [Expression] the matching expression */ internal fun Questionnaire.findVariableExpression(variableName: String): Expression? = variableExpressions.find { it.name == variableName } /** * See * [Extension: target structure map](http://build.fhir.org/ig/HL7/sdc/StructureDefinition-sdc-questionnaire-targetStructureMap.html) * . */ private const val TARGET_STRUCTURE_MAP: String = "http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-targetStructureMap" val Questionnaire.isPaginated: Boolean get() = item.any { item -> item.displayItemControl == DisplayItemControlType.PAGE } /** * See * [Extension: Entry mode](http://build.fhir.org/ig/HL7/sdc/StructureDefinition-sdc-questionnaire-entryMode.html) * . */ internal const val EXTENSION_ENTRY_MODE_URL: String = "http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-entryMode" val Questionnaire.entryMode: EntryMode? get() { val entryMode = this.extension .firstOrNull { it.url == EXTENSION_ENTRY_MODE_URL } ?.value ?.toString() ?.lowercase() return EntryMode.from(entryMode) } enum class EntryMode(val value: String) { PRIOR_EDIT("prior-edit"), RANDOM("random"), SEQUENTIAL("sequential"); companion object { fun from(type: String?): EntryMode? = values().find { it.value == type } } }
datacapture/src/main/java/com/google/android/fhir/datacapture/MoreQuestionnaires.kt
3872657933
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val AMD_seamless_cubemap_per_texture = "AMDSeamlessCubemapPerTexture".nativeClassGL("AMD_seamless_cubemap_per_texture", postfix = AMD) { documentation = """ Native bindings to the $registryLink extension. In unextended OpenGL, cube maps are treated as sets of six, independent texture images. Once a face is selected from the set, it is treated exactly as any other two-dimensional texture would be. When sampling linearly from the texture, all of the individual texels that would be used to to create the final, bilinear sample values are taken from the same cube face. The normal, two-dimensional texture coordinate wrapping modes are honored. This sometimes causes seams to appear in cube maps. ARB_seamless_cube_map addresses this issue by providing a mechanism whereby an implementation could take each of the taps of a bilinear sample from a different face, spanning face boundaries and providing seamless filtering from cube map textures. However, in ARB_seamless_cube_map, this feature was exposed as a global state, affecting all bound cube map textures. It was not possible to mix seamless and per-face cube map sampling modes during multisampling. Furthermore, if an application included cube maps that were meant to be sampled seamlessly and non-seamlessly, it would have to track this state and enable or disable seamless cube map sampling as needed. This extension addresses this issue and provides an orthogonal method for allowing an implementation to provide a per-texture setting for enabling seamless sampling from cube maps. Requires ${ARB_texture_cube_map.link}. """ IntConstant( "Accepted by the {@code pname} parameter of TexParameterf, TexParameteri, TexParameterfv, TexParameteriv, GetTexParameterfv, and GetTexParameteriv.", "TEXTURE_CUBE_MAP_SEAMLESS"..0x884F ) }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/AMD_seamless_cubemap_per_texture.kt
3311372914
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_imaging = "ARBImaging".nativeClassGL("ARB_imaging") { documentation = "Native bindings to the OpenGL 1.2 optional imaging subset." val IMAGING_INTERNAL_FORMATS = """ #RGB GL11#GL_RGBA #RG8 #RG8_SNORM #R3_G3_B2 #RGB4 #RGB5 #RGB565 #RGB8 #RGB8_SNORM #RGB10 #RGB12 #RGB16 #RGB16_SNORM #RGBA2 #RGBA4 #RGB5_A1 #RGBA8 #RGBA8_SNORM #RGB10_A2 #RGBA12 #RGBA16 #RGBA16_SNORM #SRGB8 #SRGB8_ALPHA8 #RGB16F #RGBA16F #RGB32F #RGBA32F #R11F_G11F_B10F #ALPHA #LUMINANCE #LUMINANCE_ALPHA #INTENSITY #ALPHA4 #ALPHA8 #ALPHA12 #ALPHA16 #LUMINANCE4 #LUMINANCE8 #LUMINANCE12 #LUMINANCE16 #LUMINANCE4_ALPHA4 #LUMINANCE6_ALPHA2 #LUMINANCE8_ALPHA8 #LUMINANCE12_ALPHA4 #LUMINANCE12_ALPHA12 #LUMINANCE16_ALPHA16 #INTENSITY4 #INTENSITY8 #INTENSITY12 #INTENSITY16 #SLUMINANCE #SLUMINANCE8_ALPHA8 """ val PIXEL_DATA_FORMATS = "#RED #GREEN #BLUE #ALPHA #RGB GL11#GL_RGBA #BGR #BGRA #LUMINANCE #LUMINANCE_ALPHA" val PIXEL_DATA_TYPES = """ #UNSIGNED_BYTE #BYTE #UNSIGNED_SHORT #SHORT #UNSIGNED_INT #INT #UNSIGNED_BYTE_3_3_2 #UNSIGNED_BYTE_2_3_3_REV #UNSIGNED_SHORT_5_6_5 #UNSIGNED_SHORT_5_6_5_REV #UNSIGNED_SHORT_4_4_4_4 #UNSIGNED_SHORT_4_4_4_4_REV #UNSIGNED_SHORT_5_5_5_1 #UNSIGNED_SHORT_1_5_5_5_REV #UNSIGNED_INT_8_8_8_8 #UNSIGNED_INT_8_8_8_8_REV #UNSIGNED_INT_10_10_10_2 #UNSIGNED_INT_2_10_10_10_REV """ // SGI_color_table val COLOR_TABLE_TARGETS = IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev, and by the {@code target} parameter of ColorTable, CopyColorTable, ColorTableParameteriv, ColorTableParameterfv, GetColorTable, GetColorTableParameteriv, and GetColorTableParameterfv. """, "COLOR_TABLE"..0x80D0, "POST_CONVOLUTION_COLOR_TABLE"..0x80D1, "POST_COLOR_MATRIX_COLOR_TABLE"..0x80D2 ).javaDocLinks val PROXY_COLOR_TABLE_TARGETS = IntConstant( "Accepted by the {@code target} parameter of ColorTable, GetColorTableParameteriv, and GetColorTableParameterfv.", "PROXY_COLOR_TABLE"..0x80D3, "PROXY_POST_CONVOLUTION_COLOR_TABLE"..0x80D4, "PROXY_POST_COLOR_MATRIX_COLOR_TABLE"..0x80D5 ).javaDocLinks val COLOR_TABLE_PARAMS = IntConstant( """ Accepted by the {@code pname} parameter of ColorTableParameteriv, ColorTableParameterfv, GetColorTableParameteriv, and GetColorTableParameterfv. """, "COLOR_TABLE_SCALE"..0x80D6, "COLOR_TABLE_BIAS"..0x80D7 ).javaDocLinks val COLOR_TABLE_PROPERTIES = IntConstant( "Accepted by the {@code pname} parameter of GetColorTableParameteriv and GetColorTableParameterfv.", "COLOR_TABLE_FORMAT"..0x80D8, "COLOR_TABLE_WIDTH"..0x80D9, "COLOR_TABLE_RED_SIZE"..0x80DA, "COLOR_TABLE_GREEN_SIZE"..0x80DB, "COLOR_TABLE_BLUE_SIZE"..0x80DC, "COLOR_TABLE_ALPHA_SIZE"..0x80DD, "COLOR_TABLE_LUMINANCE_SIZE"..0x80DE, "COLOR_TABLE_INTENSITY_SIZE"..0x80DF ).javaDocLinks IntConstant( "ErrorCode", "TABLE_TOO_LARGE"..0x8031 ) DeprecatedGL..void( "ColorTable", "Specifies a color lookup table.", GLenum("target", "the color table target", "$COLOR_TABLE_TARGETS $PROXY_COLOR_TABLE_TARGETS"), GLenum("internalformat", "the color table internal format", IMAGING_INTERNAL_FORMATS), GLsizei("width", "the color table width"), GLenum("format", "the color data format", PIXEL_DATA_FORMATS), GLenum("type", "the color data type", PIXEL_DATA_TYPES), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..Unsafe..RawPointer..void.const.p("table", "the color table data") ) DeprecatedGL..void( "CopyColorTable", "Defines a color table in exactly the manner of #ColorTable(), except that the image data are taken from the framebuffer rather than from client memory.", GLenum("target", "the color table target", COLOR_TABLE_TARGETS), GLenum("internalformat", "the color table internal format", IMAGING_INTERNAL_FORMATS), GLint("x", "the left framebuffer pixel coordinate"), GLint("y", "the lower framebuffer pixel coordinate"), GLsizei("width", "the color table width") ) DeprecatedGL..void( "ColorTableParameteriv", "Specifies the scale and bias parameters for a color table.", GLenum("target", "the color table target", COLOR_TABLE_TARGETS), GLenum("pname", "the parameter to set", COLOR_TABLE_PARAMS), Check(4)..GLint.const.p("params", "the parameter value") ) DeprecatedGL..void( "ColorTableParameterfv", "Float version of #ColorTableParameteriv().", GLenum("target", "the color table target"), GLenum("pname", "the parameter to set"), Check(4)..GLfloat.const.p("params", "the parameter value") ) DeprecatedGL..void( "GetColorTable", "Returns the current contents of a color table.", GLenum("target", "the color table target", COLOR_TABLE_TARGETS), GLenum("format", "the color data format", PIXEL_DATA_FORMATS), GLenum("type", "the color data type", PIXEL_DATA_TYPES), MultiType( PointerMapping.DATA_SHORT, PointerMapping.DATA_INT, PointerMapping.DATA_FLOAT )..Unsafe..RawPointer..void.p("table", "the color table data") ) DeprecatedGL..void( "GetColorTableParameteriv", "Returns the integer value of the specified color table parameter.", GLenum("target", "the color table target", "$COLOR_TABLE_TARGETS $PROXY_COLOR_TABLE_TARGETS"), GLenum("pname", "the parameter to query", "$COLOR_TABLE_PARAMS $COLOR_TABLE_PROPERTIES"), Check(4)..ReturnParam..GLint.p("params", "a buffer in which to place the returned value") ) DeprecatedGL..void( "GetColorTableParameterfv", "Float version of #GetColorTableParameteriv().", GLenum("target", "the color table target"), GLenum("pname", "the parameter to query"), Check(4)..ReturnParam..GLfloat.p("params", "a buffer in which to place the returned value") ) // EXT_color_subtable DeprecatedGL..void( "ColorSubTable", "Respecifies a portion of an existing color table.", GLenum("target", "the color table target", COLOR_TABLE_TARGETS), GLsizei("start", "the starting index of the subregion to respecify"), GLsizei("count", "the number of colors in the subregion to respecify"), GLenum("format", "the color data format", PIXEL_DATA_FORMATS), GLenum("type", "the color data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.const.p("data", "the color table data") ) DeprecatedGL..void( "CopyColorSubTable", "Respecifies a portion of an existing color table using image taken from the framebuffer.", GLenum("target", "the color table target", COLOR_TABLE_TARGETS), GLsizei("start", "the start index of the subregion to respecify"), GLint("x", "the left framebuffer pixel coordinate"), GLint("y", "the lower framebuffer pixel coordinate"), GLsizei("width", "the number of colors in the subregion to respecify") ) // EXT_convolution IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev, and by the {@code target} parameter of ConvolutionFilter1D, CopyConvolutionFilter1D, GetConvolutionFilter, ConvolutionParameteri, ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv. """, "CONVOLUTION_1D"..0x8010 ) IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev, and by the {@code target} parameter of ConvolutionFilter2D, CopyConvolutionFilter2D, GetConvolutionFilter, ConvolutionParameteri, ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv. """, "CONVOLUTION_2D"..0x8011 ) IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev, and by the {@code target} parameter of SeparableFilter2D, SeparableFilter2D, GetSeparableFilter, ConvolutionParameteri, ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv. """, "SEPARABLE_2D"..0x8012 ) IntConstant( """ Accepted by the {@code pname} parameter of ConvolutionParameteri, ConvolutionParameterf, ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv. """, "CONVOLUTION_BORDER_MODE"..0x8013 ) val CONVOLUTION_FILTER_PARAMS = IntConstant( "Accepted by the {@code pname} parameter of ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.", "CONVOLUTION_FILTER_SCALE"..0x8014, "CONVOLUTION_FILTER_BIAS"..0x8015 ).javaDocLinks IntConstant( """ Accepted by the {@code param} parameter of ConvolutionParameteri, and ConvolutionParameterf, and by the {@code params} parameter of ConvolutionParameteriv and ConvolutionParameterfv, when the {@code pname} parameter is CONVOLUTION_BORDER_MODE. """, "REDUCE"..0x8016 ) val CONVOLUTION_FILTER_PROPERTIES = IntConstant( "Accepted by the {@code pname} parameter of GetConvolutionParameteriv and GetConvolutionParameterfv.", "CONVOLUTION_FORMAT"..0x8017, "CONVOLUTION_WIDTH"..0x8018, "CONVOLUTION_HEIGHT"..0x8019, "MAX_CONVOLUTION_WIDTH"..0x801A, "MAX_CONVOLUTION_HEIGHT"..0x801B ).javaDocLinks IntConstant( """ Accepted by the {@code pname} parameter of PixelTransferi, PixelTransferf, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev. """, "POST_CONVOLUTION_RED_SCALE"..0x801C, "POST_CONVOLUTION_GREEN_SCALE"..0x801D, "POST_CONVOLUTION_BLUE_SCALE"..0x801E, "POST_CONVOLUTION_ALPHA_SCALE"..0x801F, "POST_CONVOLUTION_RED_BIAS"..0x8020, "POST_CONVOLUTION_GREEN_BIAS"..0x8021, "POST_CONVOLUTION_BLUE_BIAS"..0x8022, "POST_CONVOLUTION_ALPHA_BIAS"..0x8023 ) DeprecatedGL..void( "ConvolutionFilter1D", "Defines a one-dimensional convolution filter.", GLenum("target", "the convolution target", "#CONVOLUTION_1D"), GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS), GLsizei("width", "the filter width"), GLenum("format", "the filter data format", PIXEL_DATA_FORMATS), GLenum("type", "the filter data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.const.p("data", "the filter data") ) DeprecatedGL..void( "ConvolutionFilter2D", "Defines a two-dimensional convolution filter.", GLenum("target", "the convolution target", "#CONVOLUTION_2D"), GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS), GLsizei("width", "the filter width"), GLsizei("height", "the filter height"), GLenum("format", "the filter data format", PIXEL_DATA_FORMATS), GLenum("type", "the filter data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.const.p("data", "the filter data") ) DeprecatedGL..void( "CopyConvolutionFilter1D", """ Defines a one-dimensional filter in exactly the manner of #ConvolutionFilter1D(), except that image data are taken from the framebuffer, rather than from client memory. """, GLenum("target", "the convolution target", "#CONVOLUTION_1D"), GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS), GLint("x", "the left framebuffer pixel coordinate"), GLint("y", "the lower framebuffer pixel coordinate"), GLsizei("width", "the filter width") ) DeprecatedGL..void( "CopyConvolutionFilter2D", """ Defines a two-dimensional filter in exactly the manner of #ConvolutionFilter1D(), except that image data are taken from the framebuffer, rather than from client memory. """, GLenum("target", "the convolution target", "#CONVOLUTION_2D"), GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS), GLint("x", "the left framebuffer pixel coordinate"), GLint("y", "the lower framebuffer pixel coordinate"), GLsizei("width", "the filter width"), GLsizei("height", "the filter height") ) DeprecatedGL..void( "GetConvolutionFilter", "Returns the contents of a convolution filter.", GLenum("target", "the convolution target", "#CONVOLUTION_1D #CONVOLUTION_2D"), GLenum("format", "the filter data format", PIXEL_DATA_FORMATS), GLenum("type", "the filter data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.p("image", "the filter data") ) DeprecatedGL..void( "SeparableFilter2D", "Specifies a two-dimensional separable convolution filter.", GLenum("target", "the filter target", "#SEPARABLE_2D"), GLenum("internalformat", "the filter internal format", IMAGING_INTERNAL_FORMATS), GLsizei("width", "the filter width"), GLsizei("height", "the filter height"), GLenum("format", "the filter data format", PIXEL_DATA_FORMATS), GLenum("type", "the filter data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.const.p("row", "the horizontal filter data"), Unsafe..RawPointer..void.const.p("column", "the vertical filter data") ) DeprecatedGL..void( "GetSeparableFilter", "Returns the current contents of a separable convolution filter.", GLenum("target", "the filter target", "#SEPARABLE_2D"), GLenum("format", "the filter data format", PIXEL_DATA_FORMATS), GLenum("type", "the filter data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.p("row", "a buffer in which to return the filter row"), Unsafe..RawPointer..void.p("column", "a buffer in which to return the filter column"), Unsafe..nullable..void.p("span", "unused") ) DeprecatedGL..void( "ConvolutionParameteri", "Specifies the scale and bias of a convolution filter.", GLenum("target", "the filter target", "#CONVOLUTION_1D #CONVOLUTION_2D #SEPARABLE_2D"), GLenum("pname", "the parameter to set", "#CONVOLUTION_BORDER_MODE"), GLint("param", "the parameter value") ) DeprecatedGL..void( "ConvolutionParameteriv", "Pointer version of #ConvolutionParameteri().", GLenum("target", "the filter target"), GLenum("pname", "the parameter to set", "$CONVOLUTION_FILTER_PARAMS #CONVOLUTION_BORDER_COLOR"), Check(4)..GLint.const.p("params", "the parameter value") ) DeprecatedGL..void( "ConvolutionParameterf", "Float version of #ConvolutionParameteri()", GLenum("target", "the filter target"), GLenum("pname", "the parameter to set"), GLfloat("param", "the parameter value") ) DeprecatedGL..void( "ConvolutionParameterfv", "Pointer version of #ConvolutionParameterf().", GLenum("target", "the filter target"), GLenum("pname", "the parameter to set", "$CONVOLUTION_FILTER_PARAMS #CONVOLUTION_BORDER_COLOR"), Check(4)..GLfloat.const.p("params", "the parameter value") ) DeprecatedGL..void( "GetConvolutionParameteriv", "Returns the value of a convolution filter parameter.", GLenum("target", "the filter target", "#CONVOLUTION_1D #CONVOLUTION_2D #SEPARABLE_2D"), GLenum("pname", "the parameter to query", CONVOLUTION_FILTER_PROPERTIES), ReturnParam..Check(4)..GLint.p("params", "a buffer in which to return the parameter value") ) DeprecatedGL..void( "GetConvolutionParameterfv", "Float version of #GetConvolutionParameteriv().", GLenum("target", "the filter target"), GLenum("pname", "the parameter to query"), ReturnParam..Check(4)..GLfloat.p("params", "a buffer in which to return the parameter value") ) // HP_convolution_border_modes IntConstant( """ Accepted by the {@code param} parameter of ConvolutionParameteri, and ConvolutionParameterf, and by the {@code params} parameter of ConvolutionParameteriv and ConvolutionParameterfv, when the {@code pname} parameter is CONVOLUTION_BORDER_MODE. """, //"IGNORE_BORDER"..0x8150, "CONSTANT_BORDER"..0x8151, "REPLICATE_BORDER"..0x8153 ) IntConstant( "Accepted by the {@code pname} parameter of ConvolutionParameteriv, ConvolutionParameterfv, GetConvolutionParameteriv, and GetConvolutionParameterfv.", "CONVOLUTION_BORDER_COLOR"..0x8154 ) // SGI_color_matrix IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "COLOR_MATRIX"..0x80B1, "COLOR_MATRIX_STACK_DEPTH"..0x80B2, "MAX_COLOR_MATRIX_STACK_DEPTH"..0x80B3 ) IntConstant( "Accepted by the {@code pname} parameter of PixelTransfer*, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "POST_COLOR_MATRIX_RED_SCALE"..0x80B4, "POST_COLOR_MATRIX_GREEN_SCALE"..0x80B5, "POST_COLOR_MATRIX_BLUE_SCALE"..0x80B6, "POST_COLOR_MATRIX_ALPHA_SCALE"..0x80B7, "POST_COLOR_MATRIX_RED_BIAS"..0x80B8, "POST_COLOR_MATRIX_GREEN_BIAS"..0x80B9, "POST_COLOR_MATRIX_BLUE_BIAS"..0x80BA, "POST_COLOR_MATRIX_ALPHA_BIAS"..0x80BB ) // EXT_histogram IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev, and by the {@code target} parameter of Histogram, ResetHistogram, GetHistogram, GetHistogramParameteriv, and GetHistogramParameterfv. """, "HISTOGRAM"..0x8024 ) IntConstant( "Accepted by the {@code target} parameter of Histogram, GetHistogramParameteriv, and GetHistogramParameterfv.", "PROXY_HISTOGRAM"..0x8025 ) val HISTOGRAM_PROPERTIES = IntConstant( "Accepted by the {@code pname} parameter of GetHistogramParameteriv and GetHistogramParameterfv.", "HISTOGRAM_WIDTH"..0x8026, "HISTOGRAM_FORMAT"..0x8027, "HISTOGRAM_RED_SIZE"..0x8028, "HISTOGRAM_GREEN_SIZE"..0x8029, "HISTOGRAM_BLUE_SIZE"..0x802A, "HISTOGRAM_ALPHA_SIZE"..0x802B, "HISTOGRAM_LUMINANCE_SIZE"..0x802C, "HISTOGRAM_SINK"..0x802D ).javaDocLinks IntConstant( """ Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev, and by the {@code target} parameter of Minmax, ResetMinmax, GetMinmax, GetMinmaxParameteriv, and GetMinmaxParameterfv. """, "MINMAX"..0x802E ) IntConstant( "Accepted by the {@code pname} parameter of GetMinmaxParameteriv and GetMinmaxParameterfv.", "MINMAX_FORMAT"..0x802F, "MINMAX_SINK"..0x8030 ) DeprecatedGL..void( "Histogram", "Specifies the histogram table.", GLenum("target", "the histogram target", "#HISTOGRAM #PROXY_HISTOGRAM"), GLsizei("width", "the histogram width"), GLenum("internalformat", "the histogram internal format", IMAGING_INTERNAL_FORMATS), GLboolean( "sink", """ whether pixel groups will be consumed by the histogram operation (#TRUE) or passed on to the minmax operation (#FALSE) """ ) ) DeprecatedGL..void( "ResetHistogram", "Resets all counters of all elements of the histogram table to zero.", GLenum("target", "the histogram target", "#HISTOGRAM") ) DeprecatedGL..void( "GetHistogram", "Returns the current contents of the histogram table.", GLenum("target", "the histogram target", "#HISTOGRAM"), GLboolean( "reset", "if #TRUE, then all counters of all elements of the histogram are reset to zero. Counters are reset whether returned or not." ), GLenum("format", "the pixel data format", PIXEL_DATA_FORMATS), GLenum("type", "the pixel data types", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.p("values", "the pixel data") ) DeprecatedGL..void( "GetHistogramParameteriv", "Returns the integer values of the specified histogram parameter", GLenum("target", "the histogram target", "#HISTOGRAM"), GLenum("pname", "the parameter to query", HISTOGRAM_PROPERTIES), ReturnParam..Check(1)..GLint.p("params", "a buffer in which to return the parameter values") ) DeprecatedGL..void( "GetHistogramParameterfv", "Float version of #GetHistogramParameteriv().", GLenum("target", "the histogram target"), GLenum("pname", "the parameter to query"), ReturnParam..Check(1)..GLfloat.p("params", "a buffer in which to place the returned value") ) DeprecatedGL..void( "Minmax", "Specifies the minmax table.", GLenum("target", "the minmax target", "#MINMAX"), GLenum("internalformat", "the minmax table internal format", IMAGING_INTERNAL_FORMATS), GLboolean( "sink", "whether pixel groups will be consumed by the minmax operation (#TRUE) or passed on to final conversion (#FALSE)" ) ) DeprecatedGL..void( "ResetMinmax", "Resets all minimum and maximum values of {@code target} to to their maximum and minimum representable values, respectively.", GLenum("target", "the minmax target", "#MINMAX") ) DeprecatedGL..void( "GetMinmax", "Returns the current contents of the minmax table.", GLenum("target", "the minmax target", "#MINMAX"), GLboolean( "reset", """ If #TRUE, then each minimum value is reset to the maximum representable value, and each maximum value is reset to the minimum representable value. All values are reset, whether returned or not. """ ), GLenum("format", "the pixel data format", PIXEL_DATA_FORMATS), GLenum("type", "the pixel data type", PIXEL_DATA_TYPES), Unsafe..RawPointer..void.p("values", "a buffer in which to place the minmax values") ) DeprecatedGL..void( "GetMinmaxParameteriv", "Returns the integer value of the specified minmax parameter.", GLenum("target", "the minmax target", "#MINMAX"), GLenum("pname", "the parameter to query"), ReturnParam..Check(1)..GLint.p("params", "a buffer in which to place the returned value") ) DeprecatedGL..void( "GetMinmaxParameterfv", "Float version of #GetMinmaxParameteriv().", GLenum("target", "the minmax target", "#MINMAX"), GLenum("pname", "the parameter to query"), ReturnParam..Check(1)..GLfloat.p("params", "a buffer in which to place the returned value") ) // EXT_blend_color IntConstant( "Accepted by the {@code sfactor} and {@code dfactor} parameters of BlendFunc.", "CONSTANT_COLOR"..0x8001, "ONE_MINUS_CONSTANT_COLOR"..0x8002, "CONSTANT_ALPHA"..0x8003, "ONE_MINUS_CONSTANT_ALPHA"..0x8004 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "BLEND_COLOR"..0x8005 ) reuse(GL14C, "BlendColor") // EXT_blend_minmax IntConstant( "Accepted by the {@code mode} parameter of BlendEquation.", "FUNC_ADD"..0x8006, "MIN"..0x8007, "MAX"..0x8008 ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.", "BLEND_EQUATION"..0x8009 ) // EXT_blend_subtract IntConstant( "Accepted by the {@code mode} parameter of BlendEquation.", "FUNC_SUBTRACT"..0x800A, "FUNC_REVERSE_SUBTRACT"..0x800B ) reuse(GL14C, "BlendEquation") }
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_imaging.kt
3958705229
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package llvm.templates import llvm.* import org.lwjgl.generator.* val LLVMExecutionEngine = "LLVMExecutionEngine".nativeClass( Module.LLVM, prefixConstant = "LLVM", prefixMethod = "LLVM", binding = LLVM_BINDING_DELEGATE ) { documentation = "" void( "LinkInMCJIT", "", void() ) void( "LinkInInterpreter", "", void() ) LLVMGenericValueRef( "CreateGenericValueOfInt", "", LLVMTypeRef("Ty", ""), unsigned_long_long("N", ""), LLVMBool("IsSigned", "") ) LLVMGenericValueRef( "CreateGenericValueOfPointer", "", opaque_p("P", "") ) LLVMGenericValueRef( "CreateGenericValueOfFloat", "", LLVMTypeRef("Ty", ""), double("N", "") ) unsigned_int( "GenericValueIntWidth", "", LLVMGenericValueRef("GenValRef", "") ) unsigned_long_long( "GenericValueToInt", "", LLVMGenericValueRef("GenVal", ""), LLVMBool("IsSigned", "") ) opaque_p( "GenericValueToPointer", "", LLVMGenericValueRef("GenVal", "") ) double( "GenericValueToFloat", "", LLVMTypeRef("TyRef", ""), LLVMGenericValueRef("GenVal", "") ) void( "DisposeGenericValue", "", LLVMGenericValueRef("GenVal", "") ) LLVMBool( "CreateExecutionEngineForModule", "", Check(1)..LLVMExecutionEngineRef.p("OutEE", ""), LLVMModuleRef("M", ""), Check(1)..charUTF8.p.p("OutError", "") ) LLVMBool( "CreateInterpreterForModule", "", Check(1)..LLVMExecutionEngineRef.p("OutInterp", ""), LLVMModuleRef("M", ""), Check(1)..charUTF8.p.p("OutError", "") ) LLVMBool( "CreateJITCompilerForModule", "", Check(1)..LLVMExecutionEngineRef.p("OutJIT", ""), LLVMModuleRef("M", ""), unsigned_int("OptLevel", ""), Check(1)..charUTF8.p.p("OutError", "") ) void( "InitializeMCJITCompilerOptions", "", LLVMMCJITCompilerOptions.p("Options", ""), AutoSize("Options")..size_t("SizeOfOptions", "") ) LLVMBool( "CreateMCJITCompilerForModule", """ Create an MCJIT execution engine for a module, with the given options. It is the responsibility of the caller to ensure that all fields in {@code Options} up to the given {@code SizeOfOptions} are initialized. It is correct to pass a smaller value of {@code SizeOfOptions} that omits some fields. The canonical way of using this is: ${codeBlock(""" LLVMMCJITCompilerOptions options; LLVMInitializeMCJITCompilerOptions(&options, sizeof(options)); ... fill in those options you care about LLVMCreateMCJITCompilerForModule(&jit, mod, &options, sizeof(options), &error);""")} Note that this is also correct, though possibly suboptimal: ${codeBlock(""" LLVMCreateMCJITCompilerForModule(&jit, mod, 0, 0, &error);""")} """, Check(1)..LLVMExecutionEngineRef.p("OutJIT", ""), LLVMModuleRef("M", ""), LLVMMCJITCompilerOptions.p("Options", ""), AutoSize("Options")..size_t("SizeOfOptions", ""), Check(1)..charUTF8.p.p("OutError", "") ) void( "DisposeExecutionEngine", "", LLVMExecutionEngineRef("EE", "") ) void( "RunStaticConstructors", "", LLVMExecutionEngineRef("EE", "") ) void( "RunStaticDestructors", "", LLVMExecutionEngineRef("EE", "") ) int( "RunFunctionAsMain", "", LLVMExecutionEngineRef("EE", ""), LLVMValueRef("F", ""), AutoSize("ArgV")..unsigned_int("ArgC", ""), charUTF8.const.p.const.p("ArgV", ""), NullTerminated..charUTF8.const.p.const.p("EnvP", "") ) LLVMGenericValueRef( "RunFunction", "", LLVMExecutionEngineRef("EE", ""), LLVMValueRef("F", ""), AutoSize("Args")..unsigned_int("NumArgs", ""), LLVMGenericValueRef.p("Args", "") ) void( "FreeMachineCodeForFunction", "", LLVMExecutionEngineRef("EE", ""), LLVMValueRef("F", "") ) void( "AddModule", "", LLVMExecutionEngineRef("EE", ""), LLVMModuleRef("M", "") ) LLVMBool( "RemoveModule", "", LLVMExecutionEngineRef("EE", ""), LLVMModuleRef("M", ""), Check(1)..LLVMModuleRef.p("OutMod", ""), Check(1)..charUTF8.p.p("OutError", "") ) LLVMBool( "FindFunction", "", LLVMExecutionEngineRef("EE", ""), Check(1)..charUTF8.const.p("Name", ""), Check(1)..LLVMValueRef.p("OutFn", "") ) opaque_p( "RecompileAndRelinkFunction", "", LLVMExecutionEngineRef("EE", ""), LLVMValueRef("Fn", "") ) LLVMTargetDataRef( "GetExecutionEngineTargetData", "", LLVMExecutionEngineRef("EE", "") ) LLVMTargetMachineRef( "GetExecutionEngineTargetMachine", "", LLVMExecutionEngineRef("EE", "") ) void( "AddGlobalMapping", "", LLVMExecutionEngineRef("EE", ""), LLVMValueRef("Global", ""), opaque_p("Addr", "") ) opaque_p( "GetPointerToGlobal", "", LLVMExecutionEngineRef("EE", ""), LLVMValueRef("Global", "") ) uint64_t( "GetGlobalValueAddress", "", LLVMExecutionEngineRef("EE", ""), charUTF8.const.p("Name", "") ) uint64_t( "GetFunctionAddress", "", LLVMExecutionEngineRef("EE", ""), charUTF8.const.p("Name", "") ) IgnoreMissing..LLVMBool( "ExecutionEngineGetErrMsg", """ Returns true on error, false on success. If true is returned then the error message is copied to {@code OutStr} and cleared in the {@code ExecutionEngine} instance. """, LLVMExecutionEngineRef("EE", ""), Check(1)..charUTF8.p.p("OutError", ""), since = "11" ) LLVMMCJITMemoryManagerRef( "CreateSimpleMCJITMemoryManager", """ Create a simple custom MCJIT memory manager. This memory manager can intercept allocations in a module-oblivious way. This will return #NULL if any of the passed functions are #NULL. """, opaque_p("Opaque", "an opaque client object to pass back to the callbacks"), LLVMMemoryManagerAllocateCodeSectionCallback("AllocateCodeSection", "allocate a block of memory for executable code"), LLVMMemoryManagerAllocateDataSectionCallback("AllocateDataSection", "allocate a block of memory for data"), LLVMMemoryManagerFinalizeMemoryCallback("FinalizeMemory", "set page permissions and flush cache. Return 0 on success, 1 on error."), LLVMMemoryManagerDestroyCallback("Destroy", "") ) void( "DisposeMCJITMemoryManager", "", LLVMMCJITMemoryManagerRef("MM", "") ) IgnoreMissing..LLVMJITEventListenerRef("CreateGDBRegistrationListener", "", void()) IgnoreMissing..LLVMJITEventListenerRef("CreateIntelJITEventListener", "", void()) IgnoreMissing..LLVMJITEventListenerRef("CreateOProfileJITEventListener", "", void()) IgnoreMissing..LLVMJITEventListenerRef("CreatePerfJITEventListener", "", void()) }
modules/lwjgl/llvm/src/templates/kotlin/llvm/templates/LLVMExecutionEngine.kt
2828158171
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2018 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang.psi.mixins import com.demonwav.mcdev.nbt.lang.psi.NbttElement import com.demonwav.mcdev.nbt.tags.TagLong interface NbttLongMixin : NbttElement { fun getLongTag(): TagLong }
src/main/kotlin/com/demonwav/mcdev/nbt/lang/psi/mixins/NbttLongMixin.kt
1447465107
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.indicatorengine import org.hisp.dhis.android.core.analytics.aggregated.MetadataItem import org.hisp.dhis.android.core.analytics.aggregated.internal.AnalyticsServiceEvaluationItem import org.hisp.dhis.android.core.analytics.aggregated.internal.evaluator.AnalyticsEvaluator import org.hisp.dhis.android.core.arch.db.stores.internal.IdentifiableObjectStore import org.hisp.dhis.android.core.category.internal.CategoryOptionComboStore import org.hisp.dhis.android.core.dataelement.DataElement import org.hisp.dhis.android.core.program.ProgramIndicatorCollectionRepository import org.hisp.dhis.android.core.program.internal.ProgramStoreInterface import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttribute internal data class IndicatorContext( val dataElementStore: IdentifiableObjectStore<DataElement>, val trackedEntityAttributeStore: IdentifiableObjectStore<TrackedEntityAttribute>, val categoryOptionComboStore: CategoryOptionComboStore, val programStore: ProgramStoreInterface, val programIndicatorRepository: ProgramIndicatorCollectionRepository, val dataElementEvaluator: AnalyticsEvaluator, val programIndicatorEvaluator: AnalyticsEvaluator, val eventDataItemEvaluator: AnalyticsEvaluator, val evaluationItem: AnalyticsServiceEvaluationItem, val contextMetadata: Map<String, MetadataItem> )
core/src/main/java/org/hisp/dhis/android/core/analytics/aggregated/internal/evaluator/indicatorengine/IndicatorContext.kt
707218081
package com.tinmegali.myweather.dagger import android.arch.persistence.room.Room import android.content.Context import com.tinmegali.myweather.R import com.tinmegali.myweather.data.Database import com.tinmegali.myweather.data.PrefsDAO import com.tinmegali.myweather.data.WeatherDAO import com.tinmegali.myweather.web.ErrorUtils import com.tinmegali.myweather.web.LiveDataCallAdapterFactory import com.tinmegali.myweather.web.OpenWeatherApi import com.tinmegali.myweather.web.OpenWeatherService import dagger.Module import dagger.Provides import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class WebModule( appContext: Context ) { var openWeatherID: String = appContext.getString(R.string.openWeather) @Provides @Singleton fun providerOpenWeatherID(): String { return openWeatherID } @Provides @Singleton fun providesRetrofit() : Retrofit { return Retrofit.Builder() .baseUrl("http://api.openweathermap.org/data/2.5/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(LiveDataCallAdapterFactory()) .build() } @Provides @Singleton fun providesErrorUtil( retrofit: Retrofit ) : ErrorUtils { return ErrorUtils( retrofit ) } @Provides @Singleton fun providesOpenWeatherApi( retrofit: Retrofit ) : OpenWeatherApi { return retrofit.create( OpenWeatherApi::class.java ) } @Provides @Singleton fun providesOpenWeatherService( api: OpenWeatherApi, errorUtils: ErrorUtils, openWeatherId: String, prefsDAO: PrefsDAO ) : OpenWeatherService { return OpenWeatherService( api, errorUtils, openWeatherId, prefsDAO ) } }
app/src/main/java/com/tinmegali/myweather/dagger/WebModule.kt
2459019308
fun a( l0: /*T2@*/MutableMap.MutableEntry</*T0@*/Int, /*T1@*/String> ) { l0/*T2@MutableEntry<T0@Int, T1@String>*/.setValue(1/*LIT*/, "nya") } //T0 := T0 due to 'RECEIVER_PARAMETER' //T1 := T1 due to 'RECEIVER_PARAMETER' //T2 := LOWER due to 'USE_AS_RECEIVER'
plugins/kotlin/j2k/new/tests/testData/inference/mutability/mapEntryMutableCalls.kt
2654097417
/* * Copyright (c) 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 dev.hadrosaur.videodecodeencodedemo.AudioHelpers import androidx.collection.CircularArray import dev.hadrosaur.videodecodeencodedemo.MainActivity.Companion.logd import dev.hadrosaur.videodecodeencodedemo.Utils.CircularBuffer class AudioMixTrack(startTimeUs: Long = 0L) { val BUFFER_LENGTH = 250 // About 5secs at ~0.02s per buffer val SPLIT_BUFFER_LENGTH = 50 // Allocate some temporary space for split audio buffers val mediaClock = AudioMixTrackMediaClock(startTimeUs) private val audioBuffer = CircularBuffer<AudioBuffer>(BUFFER_LENGTH, AudioMainTrack.createEmptyAudioBuffer()) // This is temporary storage space, we will not pull from this buffer so allow overwriting private val splitBuffer = CircularBuffer<AudioBuffer>(SPLIT_BUFFER_LENGTH, AudioMainTrack.createEmptyAudioBuffer(), CircularBuffer.FULL_BEHAVIOUR.OVERWRITE) /** * Indicate if the buffer already has BUFFER_LENGTH - 1 elements so as not to make it auto-grow */ fun isFull() : Boolean { return audioBuffer.isFull() } fun getFirstPresentationTimeUs() : Long { return if (audioBuffer.isEmpty()) { Long.MAX_VALUE } else { // Buffers are in order so beginning of first buffer is first presentation time audioBuffer.peek().presentationTimeUs } } fun reset() { audioBuffer.clear() mediaClock.reset() } fun addAudioChunk(chunkToAdd: AudioBuffer) { audioBuffer.add(chunkToAdd) } // Pop audio chunk and update playhead. Note: mediaClock is not updated here. It is expected to // be updated manually from the main track fun popAudioChunk(): AudioBuffer? { if (!audioBuffer.isEmpty()) { return null } return audioBuffer.get() } // Pop all chunks that contain some audio >= fromUs and < toUs // This will simply discard chunks that are too early fun popChunksFromTo(fromUs: Long, toUs: Long) : CircularArray<AudioBuffer> { val chunksInRange = CircularArray<AudioBuffer>(2) while (!audioBuffer.isEmpty()) { var chunk = audioBuffer.get() var chunkStartUs = chunk.presentationTimeUs; var chunkEndUs = chunk.presentationTimeUs + chunk.lengthUs var splitBufferPointer: AudioBuffer? = null var isSplitBuffer = false // If the next chunk is after the range (starts at or after toUs), put it back and exit if (chunkStartUs >= toUs) { audioBuffer.rewindTail() // This "puts back" the chunk, avoiding a copy break } // If the chunk is earlier than the range, simply discard it if (chunkEndUs < fromUs) { continue } //TODO: If time doesn't line up exactly on a short boundary, there could be data loss // or silence added here. Maybe presentation times need to be byte/short aligned? // Or from -> to times? // Only latter part of chunk required, chop off beginning part and add chunk if (chunkStartUs < fromUs && chunkEndUs > fromUs) { val timeToDiscard = fromUs - chunkStartUs val bytesToDiscard = usToBytes(timeToDiscard) chunk.buffer.position(chunk.buffer.position() + bytesToDiscard) chunkStartUs = fromUs // Update new start for next check } // If only the first part is needed, copy the first part of the chunk into the split // buffer queue and adjust the old/new buffer positions. Note if a chunk is larger than // the from<->to window, both the above situation and this can apply: chop of some from // beginning and some from the end. if (chunkStartUs < toUs && chunkEndUs > toUs) { val timeToKeepUs = toUs - chunkStartUs; val bytesToKeep = usToBytes(timeToKeepUs) // Copy into split buffer queue and reduce the limit to "cut off the end" splitBufferPointer = splitBuffer.peekHead() // Get pointer to storage location splitBuffer.add(chunk, true) // Copy full chunk into split buffer queue // Adjust the copy to just be the first part splitBufferPointer.buffer.limit(chunk.buffer.position() + bytesToKeep) splitBufferPointer.lengthUs = toUs - chunkStartUs splitBufferPointer.size = bytesToKeep isSplitBuffer = true // Advance start position of original buffer and rewind queue to cut off front and // "put it back" in the queue for future playback chunk.buffer.position(chunk.buffer.position() + bytesToKeep) chunk.presentationTimeUs = toUs chunk.lengthUs = chunkEndUs - toUs chunk.size = chunk.size - bytesToKeep audioBuffer.rewindTail() } // If we reach this point, chunk is now perfectly in range if (isSplitBuffer) { chunksInRange.addLast(splitBufferPointer) } else { chunksInRange.addLast(chunk) } } return chunksInRange } }
app/src/main/java/dev/hadrosaur/videodecodeencodedemo/AudioHelpers/AudioMixTrack.kt
2732591016
// WITH_STDLIB // AFTER-WARNING: Parameter 'i' is never used fun foo(i: Int) {} fun test(s: String) { <caret>if (s.isNotBlank()) { foo(1) } else { foo(2) } }
plugins/kotlin/idea/tests/testData/intentions/invertIfCondition/isNotBlank.kt
2330236728
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createCallable import com.intellij.util.SmartList import org.jetbrains.kotlin.builtins.ReflectionTypes import org.jetbrains.kotlin.config.LanguageFeature import org.jetbrains.kotlin.descriptors.VariableAccessorDescriptor import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor import org.jetbrains.kotlin.diagnostics.Diagnostic import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.CallableInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.FunctionInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtProperty import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.util.OperatorNameConventions object CreatePropertyDelegateAccessorsActionFactory : CreateCallableMemberFromUsageFactory<KtExpression>() { override fun getElementOfInterest(diagnostic: Diagnostic): KtExpression? { return diagnostic.psiElement as? KtExpression } override fun extractFixData(element: KtExpression, diagnostic: Diagnostic): List<CallableInfo> { val context = element.analyze() fun isApplicableForAccessor(accessor: VariableAccessorDescriptor?): Boolean = accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null val property = element.getNonStrictParentOfType<KtProperty>() ?: return emptyList() val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, property] as? VariableDescriptorWithAccessors ?: return emptyList() if (propertyDescriptor is LocalVariableDescriptor && !element.languageVersionSettings.supportsFeature(LanguageFeature.LocalDelegatedProperties) ) { return emptyList() } val propertyReceiver = propertyDescriptor.extensionReceiverParameter ?: propertyDescriptor.dispatchReceiverParameter val propertyType = propertyDescriptor.type val accessorReceiverType = TypeInfo(element, Variance.IN_VARIANCE) val builtIns = propertyDescriptor.builtIns val thisRefParam = ParameterInfo(TypeInfo(propertyReceiver?.type ?: builtIns.nullableNothingType, Variance.IN_VARIANCE)) val kPropertyStarType = ReflectionTypes.createKPropertyStarType(propertyDescriptor.module) ?: return emptyList() val metadataParam = ParameterInfo(TypeInfo(kPropertyStarType, Variance.IN_VARIANCE), "property") val callableInfos = SmartList<CallableInfo>() val psiFactory = KtPsiFactory(element) if (isApplicableForAccessor(propertyDescriptor.getter)) { val getterInfo = FunctionInfo( name = OperatorNameConventions.GET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(propertyType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(getterInfo) } if (propertyDescriptor.isVar && isApplicableForAccessor(propertyDescriptor.setter)) { val newValueParam = ParameterInfo(TypeInfo(propertyType, Variance.IN_VARIANCE)) val setterInfo = FunctionInfo( name = OperatorNameConventions.SET_VALUE.asString(), receiverTypeInfo = accessorReceiverType, returnTypeInfo = TypeInfo(builtIns.unitType, Variance.OUT_VARIANCE), parameterInfos = listOf(thisRefParam, metadataParam, newValueParam), modifierList = psiFactory.createModifierList(KtTokens.OPERATOR_KEYWORD) ) callableInfos.add(setterInfo) } return callableInfos } }
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createCallable/CreatePropertyDelegateAccessorsActionFactory.kt
1417320020
package demo internal class Test { fun test(vararg args: Any) { var args = args args = arrayOf(1, 2, 3) } }
plugins/kotlin/j2k/old/tests/testData/fileOrElement/function/varVararg.kt
176581385
import java.lang.annotation.ElementType fun foo(){ var e : ElementType? = <caret> } // EXIST: { lookupString:"TYPE", itemText:"ElementType.TYPE", tailText:" (java.lang.annotation)", typeText:"ElementType" } // EXIST: { lookupString:"FIELD", itemText:"ElementType.FIELD", tailText:" (java.lang.annotation)", typeText:"ElementType" }
plugins/kotlin/completion/tests/testData/smart/JavaEnumMembersForNullable.kt
525992756
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package training.featuresSuggester import com.intellij.lang.Language import com.intellij.lang.LanguageExtensionPoint import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile @Suppress("TooManyFunctions") interface SuggesterSupport { companion object { private val EP_NAME: ExtensionPointName<LanguageExtensionPoint<SuggesterSupport>> = ExtensionPointName.create("training.ifs.suggesterSupport") private val extensions: List<LanguageExtensionPoint<SuggesterSupport>> get() = EP_NAME.extensionList fun getForLanguage(language: Language): SuggesterSupport? { return if (language == Language.ANY) { extensions.firstOrNull()?.instance } else { val langSupport = extensions.find { it.language == language.id }?.instance if (langSupport == null && language.baseLanguage != null) { val baseLanguage = language.baseLanguage!! extensions.find { it.language == baseLanguage.id }?.instance } else langSupport } } } fun isLoadedSourceFile(file: PsiFile): Boolean fun isIfStatement(element: PsiElement): Boolean fun isForStatement(element: PsiElement): Boolean fun isWhileStatement(element: PsiElement): Boolean fun isCodeBlock(element: PsiElement): Boolean fun getCodeBlock(element: PsiElement): PsiElement? fun getContainingCodeBlock(element: PsiElement): PsiElement? /** * element must be a code block @see [getCodeBlock], [getContainingCodeBlock], [isCodeBlock] */ fun getParentStatementOfBlock(element: PsiElement): PsiElement? /** * element must be a code block @see [getCodeBlock], [getContainingCodeBlock], [isCodeBlock] */ fun getStatements(element: PsiElement): List<PsiElement> fun getTopmostStatementWithText(psiElement: PsiElement, text: String): PsiElement? fun isSupportedStatementToIntroduceVariable(element: PsiElement): Boolean fun isPartOfExpression(element: PsiElement): Boolean fun isExpressionStatement(element: PsiElement): Boolean fun isVariableDeclaration(element: PsiElement): Boolean /** * element must be a variable declaration @see [isVariableDeclaration] */ fun getVariableName(element: PsiElement): String? /** * Return true if element is class, method or non local property definition */ fun isFileStructureElement(element: PsiElement): Boolean fun isIdentifier(element: PsiElement): Boolean fun isLiteralExpression(element: PsiElement): Boolean }
plugins/ide-features-trainer/src/training/featuresSuggester/SuggesterSupport.kt
1671759226
/* * Copyright 2016 Jasmine Villadarez * * 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.jv.practice.notes.domain.executor import java.util.concurrent.Executor /** * Created by Jasmine on 2/10/2016. */ interface ExecutorThread : Executor
Notes/app/src/main/kotlin/com/jv/practice/notes/domain/executor/ExecutorThread.kt
2085625114
class MainClass { companion object Na<caret>me { fun f() { } class T } }
plugins/kotlin/refIndex/tests/testData/compilerIndex/classOrObject/namedCompanion/Main.kt
3147440525
package org.amshove.kluent.tests.assertions.time.localdate import org.amshove.kluent.internal.assertFails import org.amshove.kluent.shouldBeIn import java.time.LocalDate import java.time.Month import kotlin.test.Test class ShouldBeInMonthShould { @Test fun passWhenPassingTheSameMonth() { val dateToTest = LocalDate.of(2017, 3, 1) dateToTest shouldBeIn Month.MARCH } @Test fun failWhenPassingADifferentMonth() { val dateToTest = LocalDate.of(2017, 3, 1) assertFails { dateToTest shouldBeIn Month.APRIL } } }
jvm/src/test/kotlin/org/amshove/kluent/tests/assertions/time/localdate/ShouldBeInMonthShould.kt
2921118582
package org.pixelndice.table.pixelserver.connection.main import org.apache.logging.log4j.LogManager import org.pixelndice.table.pixelprotocol.Protobuf import org.pixelndice.table.pixelserver.connection.main.state04hostgame.State05HostGame import org.pixelndice.table.pixelserver.connection.main.state04joingame.State05WaitingQueryGame import org.pixelndice.table.pixelserver.connection.main.state04joingame.State06LobbyUnreachableByPlayer import org.pixelndice.table.pixelserver.connection.main.state04listgame.State05WaitingListGame private val logger = LogManager.getLogger(State03JoinOrHostGame::class.java) class State03JoinOrHostGame : State { override fun process(ctx: Context) { val p = ctx.channel.peekPacket() if( p!=null){ when(p.payloadCase){ Protobuf.Packet.PayloadCase.LOBBYUNREACHABLE -> ctx.state = State06LobbyUnreachableByPlayer() Protobuf.Packet.PayloadCase.PUBLISHCAMPAIGN -> ctx.state = State05HostGame() Protobuf.Packet.PayloadCase.QUERYGAME -> ctx.state = State05WaitingQueryGame() Protobuf.Packet.PayloadCase.CHECKGAMELIST -> ctx.state = State05WaitingListGame() Protobuf.Packet.PayloadCase.END -> ctx.state = StateStop() Protobuf.Packet.PayloadCase.ENDWITHERROR -> ctx.state = StateStop() else -> { val resp = Protobuf.Packet.newBuilder() logger.error("Expecting Lobby Unreachable by player, PublishCampaign, QueryGame, CheckGameList, END or EndWithError. Instead Received: $p") val rend = Protobuf.EndWithError.newBuilder() rend.reason = "key.expecting_lobbyunreachable_publishcampaign_querygame_checkgamelist_end_endwitherror" resp.setEndWithError(rend) ctx.channel.packet = resp.build() } } } } }
src/main/kotlin/org/pixelndice/table/pixelserver/connection/main/State03JoinOrHostGame.kt
2287361194
package org.secfirst.umbrella.data.database.content import org.secfirst.umbrella.data.database.checklist.Checklist import org.secfirst.umbrella.data.database.difficulty.Difficulty import org.secfirst.umbrella.data.database.form.Form import org.secfirst.umbrella.data.database.lesson.Module import org.secfirst.umbrella.data.database.lesson.Subject import org.secfirst.umbrella.data.database.reader.FeedSource import org.secfirst.umbrella.data.database.reader.RSS import org.secfirst.umbrella.data.database.segment.Markdown import javax.inject.Inject class ContentRepository @Inject constructor(private val contentDao: ContentDao) : ContentRepo { override suspend fun resetContent() = contentDao.resetContent() override suspend fun insertDefaultRSS(rssList: List<RSS>) = contentDao.insertDefaultRSS(rssList) override suspend fun getSubject(subjectId: String) = contentDao.getSubject(subjectId) override suspend fun getDifficulty(difficultyId: String) = contentDao.getDifficulty(difficultyId) override suspend fun getModule(moduleId: String) = contentDao.getModule(moduleId) override suspend fun getMarkdown(markdownId: String) = contentDao.getMarkdown(markdownId) override suspend fun getChecklist(checklistId: String) = contentDao.getChecklist(checklistId) override suspend fun getForm(formId: String) = contentDao.getForm(formId) override suspend fun saveAllChecklists(checklists: List<Checklist>) = contentDao.saveChecklists(checklists) override suspend fun saveAllMarkdowns(markdowns: List<Markdown>) = contentDao.saveMarkdowns(markdowns) override suspend fun saveAllModule(modules: List<Module>) = contentDao.saveModules(modules) override suspend fun saveAllDifficulties(difficulties: List<Difficulty>) = contentDao.saveDifficulties(difficulties) override suspend fun saveAllForms(forms: List<Form>) = contentDao.saveForms(forms) override suspend fun saveAllSubjects(subjects: List<Subject>) = contentDao.saveSubjects(subjects) override suspend fun insertFeedSource(feedSources: List<FeedSource>) = contentDao.insertFeedSource(feedSources) override suspend fun insertAllLessons(contentData: ContentData) = contentDao.insertAllContent(contentData) }
app/src/main/java/org/secfirst/umbrella/data/database/content/ContentRepository.kt
2411457338
package org.secfirst.umbrella.component import android.annotation.TargetApi import android.graphics.Bitmap import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.View.INVISIBLE import android.view.View.VISIBLE import android.view.ViewGroup import android.webkit.WebResourceError import android.webkit.WebResourceRequest import android.webkit.WebView import android.webkit.WebViewClient import kotlinx.android.synthetic.main.web_view.* import org.secfirst.umbrella.R import org.secfirst.umbrella.feature.base.view.BaseController class WebViewController(bundle: Bundle) : BaseController(bundle) { private val url by lazy { args.getString(EXTRA_WEB_VIEW_URL) } private var refreshEnable: Boolean = false companion object { const val EXTRA_WEB_VIEW_URL = "url" } constructor(url: String) : this(Bundle().apply { putString(EXTRA_WEB_VIEW_URL, url) }) override fun onInject() { } override fun onAttach(view: View) { super.onAttach(view) setUpWebView() setUpToolbar() enableNavigation(false) } override fun onDestroyView(view: View) { enableNavigation(true) super.onDestroyView(view) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View { return inflater.inflate(R.layout.web_view, container, false) } private fun setUpWebView() { webView?.let { it.loadUrl(url) it.webViewClient = object : WebViewClient() { override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) { webViewLoad?.visibility = INVISIBLE webViewSwipe?.isEnabled = false } @TargetApi(android.os.Build.VERSION_CODES.M) override fun onReceivedError(view: WebView, req: WebResourceRequest, rerr: WebResourceError) { onReceivedError(view, rerr.errorCode, rerr.description.toString(), req.url.toString()) webViewLoad?.visibility = INVISIBLE webViewSwipe?.isEnabled = false if (refreshEnable) webViewSwipe?.isRefreshing = false } override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) { if (!refreshEnable) webViewLoad?.visibility = VISIBLE Handler().postDelayed({ webViewLoad?.visibility = INVISIBLE webViewSwipe?.isRefreshing = false }, 30000) } override fun onPageFinished(view: WebView, url: String) { webViewLoad?.visibility = INVISIBLE if (refreshEnable) webViewSwipe?.isRefreshing = false } } } } private fun setUpToolbar() { webViewToolbar?.let { mainActivity.setSupportActionBar(it) mainActivity.supportActionBar?.setDisplayShowHomeEnabled(true) mainActivity.supportActionBar?.setDisplayHomeAsUpEnabled(true) } } }
app/src/main/java/org/secfirst/umbrella/component/WebViewController.kt
1230013775
package com.mgaetan89.showsrage.fragment import android.app.Dialog import android.content.DialogInterface import android.os.Bundle import android.support.v4.app.DialogFragment import android.support.v7.app.AlertDialog import android.widget.Spinner import com.mgaetan89.showsrage.Constants import com.mgaetan89.showsrage.R import com.mgaetan89.showsrage.network.SickRageApi class ChangeQualityFragment : DialogFragment(), DialogInterface.OnClickListener { override fun onClick(dialog: DialogInterface?, which: Int) { val indexerId = this.arguments?.getInt(Constants.Bundle.INDEXER_ID) ?: return val parentFragment = this.parentFragment if (this.dialog == null || indexerId <= 0 || parentFragment !is ShowOverviewFragment) { return } val allowedQualitySpinner = this.dialog.findViewById(R.id.allowed_quality) as Spinner? val allowedQuality = this.getAllowedQuality(allowedQualitySpinner) val preferredQualitySpinner = this.dialog.findViewById(R.id.preferred_quality) as Spinner? val preferredQuality = this.getPreferredQuality(preferredQualitySpinner) val callback = parentFragment.getSetShowQualityCallback() SickRageApi.instance.services?.setShowQuality(indexerId, allowedQuality, preferredQuality, callback) } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val context = this.context ?: return super.onCreateDialog(savedInstanceState) val builder = AlertDialog.Builder(context) builder.setTitle(R.string.change_quality) builder.setView(R.layout.fragment_change_quality) builder.setNegativeButton(R.string.cancel, null) builder.setPositiveButton(R.string.change, this) return builder.show() } internal fun getAllowedQuality(allowedQualitySpinner: Spinner?): String? { var allowedQualityIndex = 0 if (allowedQualitySpinner != null) { // Skip the "Ignore" first item allowedQualityIndex = allowedQualitySpinner.selectedItemPosition - 1 } if (allowedQualityIndex >= 0) { val qualities = this.resources.getStringArray(R.array.allowed_qualities_keys) if (allowedQualityIndex < qualities.size) { return qualities[allowedQualityIndex] } } return null } internal fun getPreferredQuality(preferredQualitySpinner: Spinner?): String? { var preferredQualityIndex = 0 if (preferredQualitySpinner != null) { // Skip the "Ignore" first item preferredQualityIndex = preferredQualitySpinner.selectedItemPosition - 1 } if (preferredQualityIndex >= 0) { val qualities = this.resources.getStringArray(R.array.preferred_qualities_keys) if (preferredQualityIndex < qualities.size) { return qualities[preferredQualityIndex] } } return null } companion object { fun newInstance(indexerId: Int) = ChangeQualityFragment().apply { this.arguments = Bundle().apply { this.putInt(Constants.Bundle.INDEXER_ID, indexerId) } } } }
app/src/main/kotlin/com/mgaetan89/showsrage/fragment/ChangeQualityFragment.kt
2846256753
package xyz.sachil.essence.util sealed class LoadState object Success : LoadState() object NoMoreData : LoadState() object Failed : LoadState() object Loading : LoadState() object Refreshing : LoadState()
app/src/main/java/xyz/sachil/essence/util/LoadState.kt
2880142072
package top.zbeboy.isy.service.graduate.design import org.jooq.Record import top.zbeboy.isy.domain.tables.pojos.GraduationDesignTeacher import top.zbeboy.isy.web.bean.graduate.design.teacher.GraduationDesignTeacherBean import top.zbeboy.isy.web.util.DataTablesUtils import java.util.* /** * Created by zbeboy 2018-01-17 . **/ interface GraduationDesignTeacherService { /** * 通过主键查询 * * @param id 主键 * @return 数据 */ fun findById(id: String): GraduationDesignTeacher /** * 通过毕业设计发布id与教职工id查询 * * @param graduationDesignReleaseId 毕业设计发布id * @param staffId 教职工id * @return 数据 */ fun findByGraduationDesignReleaseIdAndStaffId(graduationDesignReleaseId: String, staffId: Int): Optional<Record> /** * 根据毕业设计发布id查询 * * @param graduationDesignReleaseId 毕业设计发布id * @return 数据 */ fun findByGraduationDesignReleaseId(graduationDesignReleaseId: String): List<GraduationDesignTeacher> /** * 根据毕业设计发布id关联查询 教职工 * * @param graduationDesignReleaseId 毕业设计发布id * @return 数据 */ fun findByGraduationDesignReleaseIdRelationForStaff(graduationDesignReleaseId: String): List<GraduationDesignTeacherBean> /** * 根据毕业设计发布id删除 * * @param graduationDesignReleaseId 毕业设计发布id */ fun deleteByGraduationDesignReleaseId(graduationDesignReleaseId: String) /** * 保存 * * @param graduationDesignTeacher 数据 */ fun save(graduationDesignTeacher: GraduationDesignTeacher) /** * 更新 * * @param graduationDesignTeacher 数据 */ fun update(graduationDesignTeacher: GraduationDesignTeacher) /** * 批量更新 * * @param graduationDesignTeachers 数据 */ fun update(graduationDesignTeachers: List<GraduationDesignTeacher>) /** * 分页查询 数据 * * @param dataTablesUtils datatables工具类 * @return 分页数据 */ fun findAllByPage(dataTablesUtils: DataTablesUtils<GraduationDesignTeacherBean>, graduationDesignTeacherBean: GraduationDesignTeacherBean): List<GraduationDesignTeacherBean> /** * 数据 总数 * * @return 总数 */ fun countAll(graduationDesignTeacherBean: GraduationDesignTeacherBean): Int /** * 根据条件查询总数 数据 * * @return 条件查询总数 */ fun countByCondition(dataTablesUtils: DataTablesUtils<GraduationDesignTeacherBean>, graduationDesignTeacherBean: GraduationDesignTeacherBean): Int }
src/main/java/top/zbeboy/isy/service/graduate/design/GraduationDesignTeacherService.kt
3836201905
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.search import com.intellij.openapi.util.io.FileUtil import com.intellij.psi.PsiModifierListOwner import com.intellij.psi.search.searches.AnnotatedElementsSearch import com.intellij.testFramework.LightProjectDescriptor import junit.framework.TestCase import org.jetbrains.kotlin.idea.search.PsiBasedClassResolver import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor abstract class AbstractAnnotatedMembersSearchTest : AbstractSearcherTest() { override fun getProjectDescriptor(): LightProjectDescriptor { return KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE } fun doTest(unused: String) { val testDataFile = dataFile() myFixture.configureByFile(fileName()) val fileText = FileUtil.loadFile(testDataFile, true) val directives = InTextDirectivesUtils.findListWithPrefixes(fileText, "// ANNOTATION: ") TestCase.assertFalse("Specify ANNOTATION directive in test file", directives.isEmpty()) val annotationClassName = directives.first() val psiClass = getPsiClass(annotationClassName) PsiBasedClassResolver.trueHits.set(0) PsiBasedClassResolver.falseHits.set(0) val actualResult = AnnotatedElementsSearch.searchElements( psiClass, projectScope, PsiModifierListOwner::class.java ) checkResult(testDataFile, actualResult) val optimizedTrue = InTextDirectivesUtils.getPrefixedInt(fileText, "// OPTIMIZED_TRUE:") if (optimizedTrue != null) { TestCase.assertEquals(optimizedTrue.toInt(), PsiBasedClassResolver.trueHits.get()) } val optimizedFalse = InTextDirectivesUtils.getPrefixedInt(fileText, "// OPTIMIZED_FALSE:") if (optimizedFalse != null) { TestCase.assertEquals(optimizedFalse.toInt(), PsiBasedClassResolver.falseHits.get()) } } }
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/search/AnnotatedMembersSearchTest.kt
1666338112
fun f() { val numbers = mutableListOf("one", "two", "three", "four") numbers.a<caret>dd ("five") numbers.add("zero") numbers.add(getStr()) numbers.add(getStr() + "a") numbers.add(getStr() + "b") }
plugins/kotlin/idea/tests/testData/findUsages/similarity/listAdd.kt
1986405348
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradleJava.configuration.kpm import com.intellij.build.events.MessageEvent import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.ProjectKeys import com.intellij.openapi.externalSystem.model.project.* import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil import com.intellij.openapi.externalSystem.util.ExternalSystemConstants import com.intellij.openapi.externalSystem.util.Order import com.intellij.openapi.roots.DependencyScope import com.intellij.util.PlatformUtils import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.kotlin.gradle.kpm.idea.* import org.jetbrains.kotlin.idea.base.externalSystem.findAll import org.jetbrains.kotlin.idea.base.util.KotlinPlatformUtils import org.jetbrains.kotlin.idea.configuration.multiplatform.KotlinMultiplatformNativeDebugSuggester import org.jetbrains.kotlin.idea.gradle.configuration.ResolveModulesPerSourceSetInMppBuildIssue import org.jetbrains.kotlin.idea.gradle.configuration.buildClasspathData import org.jetbrains.kotlin.idea.gradle.configuration.findChildModuleById import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ContentRootsCreator import org.jetbrains.kotlin.idea.gradle.configuration.kpm.ModuleDataInitializer import org.jetbrains.kotlin.idea.gradle.ui.notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded import org.jetbrains.kotlin.idea.gradleTooling.* import org.jetbrains.kotlin.tooling.core.Extras import org.jetbrains.plugins.gradle.model.ProjectImportModelProvider import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext import org.jetbrains.plugins.gradle.util.GradleConstants import java.io.File @Order(ExternalSystemConstants.UNORDERED + 1) open class KotlinKPMGradleProjectResolver : AbstractProjectResolverExtension() { override fun getExtraProjectModelClasses(): Set<Class<out Any>> = throw UnsupportedOperationException("Use getModelProvider() instead!") override fun getModelProvider(): ProjectImportModelProvider? = IdeaKpmProjectProvider override fun getToolingExtensionsClasses(): Set<Class<out Any>> = setOf( IdeaKpmProject::class.java, // representative of kotlin-gradle-plugin-idea Extras::class.java, // representative of kotlin-tooling-core Unit::class.java // representative of kotlin-stdlib ) override fun populateModuleExtraModels(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { if (ExternalSystemApiUtil.find(ideModule, BuildScriptClasspathData.KEY) == null) { val buildScriptClasspathData = buildClasspathData(gradleModule, resolverCtx) ideModule.createChild(BuildScriptClasspathData.KEY, buildScriptClasspathData) } super.populateModuleExtraModels(gradleModule, ideModule) } override fun createModule(gradleModule: IdeaModule, projectDataNode: DataNode<ProjectData>): DataNode<ModuleData>? { return super.createModule(gradleModule, projectDataNode)?.also { mainModuleNode -> val initializerContext = ModuleDataInitializer.Context.EMPTY ModuleDataInitializer.EP_NAME.extensions.forEach { moduleDataInitializer -> moduleDataInitializer.initialize(gradleModule, mainModuleNode, projectDataNode, resolverCtx, initializerContext) } suggestNativeDebug(gradleModule, resolverCtx) } } override fun populateModuleContentRoots(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>) { if (!modelExists(gradleModule)) { return super.populateModuleContentRoots(gradleModule, ideModule) } ContentRootsCreator.EP_NAME.extensions.forEach { contentRootsCreator -> contentRootsCreator.populateContentRoots(gradleModule, ideModule, resolverCtx) } } override fun populateModuleDependencies(gradleModule: IdeaModule, ideModule: DataNode<ModuleData>, ideProject: DataNode<ProjectData>) { if (!modelExists(gradleModule)) { return super.populateModuleDependencies(gradleModule, ideModule, ideProject) } populateDependenciesByFragmentData(gradleModule, ideModule, ideProject, resolverCtx) } private fun modelExists(gradleModule: IdeaModule): Boolean = resolverCtx.getIdeaKpmProject(gradleModule) != null companion object { private val nativeDebugSuggester = object : KotlinMultiplatformNativeDebugSuggester<IdeaKpmProject>() { override fun hasKotlinNativeHome(model: IdeaKpmProject?): Boolean = model?.kotlinNativeHome?.exists() ?: false } internal fun ProjectResolverContext.getIdeaKpmProject(gradleModule: IdeaModule): IdeaKpmProject? { return this.getExtraProject(gradleModule, IdeaKpmProjectContainer::class.java)?.instanceOrNull } private fun suggestNativeDebug(gradleModule: IdeaModule, resolverCtx: ProjectResolverContext) { nativeDebugSuggester.suggestNativeDebug(resolverCtx.getIdeaKpmProject(gradleModule), resolverCtx) if (!resolverCtx.isResolveModulePerSourceSet && !KotlinPlatformUtils.isAndroidStudio && !PlatformUtils.isMobileIde() && !PlatformUtils.isAppCode() ) { notifyLegacyIsResolveModulePerSourceSetSettingIfNeeded(resolverCtx.projectPath) resolverCtx.report(MessageEvent.Kind.WARNING, ResolveModulesPerSourceSetInMppBuildIssue()) } } //TODO check this internal fun extractPackagePrefix(fragment: IdeaKpmFragment): String? = null internal fun extractContentRootSources(model: IdeaKpmProject): Collection<IdeaKpmFragment> = model.modules.flatMap { it.fragments } //TODO replace with proper implementation, like with KotlinTaskProperties internal fun extractPureKotlinSourceFolders(fragment: IdeaKpmFragment): Collection<File> = fragment.sourceDirs //TODO Unite with KotlinGradleProjectResolverExtension.getSourceSetName internal val IdeaKpmProject.pureKotlinSourceFolders: Collection<String> get() = extractContentRootSources(this).flatMap { extractPureKotlinSourceFolders(it) }.map { it.absolutePath } internal val DataNode<out ModuleData>.sourceSetName get() = (data as? GradleSourceSetData)?.id?.substringAfterLast(':') //TODO Unite with KotlinGradleProjectResolverExtension.addDependency internal fun addModuleDependency( dependentModule: DataNode<out ModuleData>, dependencyModule: DataNode<out ModuleData>, ) { val moduleDependencyData = ModuleDependencyData(dependentModule.data, dependencyModule.data) //TODO Replace with proper scope from dependency moduleDependencyData.scope = DependencyScope.COMPILE moduleDependencyData.isExported = false moduleDependencyData.isProductionOnTestDependency = dependencyModule.sourceSetName == "test" dependentModule.createChild(ProjectKeys.MODULE_DEPENDENCY, moduleDependencyData) } private fun populateDependenciesByFragmentData( gradleModule: IdeaModule, ideModule: DataNode<ModuleData>, ideProject: DataNode<ProjectData>, resolverCtx: ProjectResolverContext ) { val allGradleModules = gradleModule.project.modules val allModuleDataNodes = ExternalSystemApiUtil.findAll(ideProject, ProjectKeys.MODULE) val allFragmentModulesById = allModuleDataNodes.flatMap { ExternalSystemApiUtil.findAll(it, GradleSourceSetData.KEY) } .associateBy { it.data.id } val sourceSetDataWithFragmentData = ExternalSystemApiUtil.findAll(ideModule, GradleSourceSetData.KEY) .mapNotNull { ExternalSystemApiUtil.find(it, KotlinFragmentData.KEY)?.data?.let { fragmentData -> it to fragmentData } } .sortedBy { it.second.refinesFragmentIds.size } for ((fragmentSourceSetNode, kpmFragmentData) in sourceSetDataWithFragmentData) { val refinesFragmentNodes = kpmFragmentData.refinesFragmentIds.mapNotNull { ideModule.findChildModuleById(it) } refinesFragmentNodes.forEach { addModuleDependency(fragmentSourceSetNode, it) } val sourceDependencyIds = kpmFragmentData.fragmentDependencies .filterIsInstance<IdeaKpmFragmentDependency>() .mapNotNull { fragmentDependency -> val foundGradleModule = allGradleModules.singleOrNull { dependencyGradleModule -> dependencyGradleModule.name == fragmentDependency.coordinates.module.projectName } ?: return@mapNotNull null // Probably it's worth to log fragmentDependency to foundGradleModule } .map { (dependency, module) -> calculateKotlinFragmentModuleId(module, dependency.coordinates, resolverCtx) } val dependencyModuleNodes = sourceDependencyIds.mapNotNull { allFragmentModulesById[it] } dependencyModuleNodes.forEach { addModuleDependency(fragmentSourceSetNode, it) } val groupedBinaryDependencies = kpmFragmentData.fragmentDependencies .filterIsInstance<IdeaKpmResolvedBinaryDependency>() .groupBy { it.coordinates.toString() } .map { (coordinates, binariesWithType) -> GroupedLibraryDependency(coordinates, binariesWithType.map { it.binaryFile to it.binaryType.toBinaryType() }) } groupedBinaryDependencies.forEach { populateLibraryDependency(fragmentSourceSetNode, ideProject, it) } } } private fun String.toBinaryType(): LibraryPathType = when (this) { IdeaKpmDependency.CLASSPATH_BINARY_TYPE -> LibraryPathType.BINARY IdeaKpmDependency.SOURCES_BINARY_TYPE -> LibraryPathType.SOURCE IdeaKpmDependency.DOCUMENTATION_BINARY_TYPE -> LibraryPathType.DOC else -> LibraryPathType.EXCLUDED } private data class GroupedLibraryDependency( val coordinates: String?, val binariesWithType: Collection<Pair<File, LibraryPathType>> ) private fun populateLibraryDependency( dependentModule: DataNode<out ModuleData>, projectDataNode: DataNode<out ProjectData>, binaryDependency: GroupedLibraryDependency ) { val coordinates = binaryDependency.coordinates ?: return val existingLibraryNodeWithData = projectDataNode.findAll(ProjectKeys.LIBRARY).find { it.data.owner == GradleConstants.SYSTEM_ID && it.data.externalName == coordinates } val libraryData: LibraryData if (existingLibraryNodeWithData != null) { libraryData = existingLibraryNodeWithData.data } else { libraryData = LibraryData(GradleConstants.SYSTEM_ID, coordinates).apply { binaryDependency.binariesWithType.forEach { (binaryFile, pathType) -> addPath(pathType, binaryFile.absolutePath) } } projectDataNode.createChild(ProjectKeys.LIBRARY, libraryData) } val libraryDependencyData = LibraryDependencyData(dependentModule.data, libraryData, LibraryLevel.PROJECT) dependentModule.createChild(ProjectKeys.LIBRARY_DEPENDENCY, libraryDependencyData) } } }
plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/configuration/kpm/KotlinKPMGradleProjectResolver.kt
3910761229
package com.github.vhromada.catalog.web.connector.entity /** * A class represents request for changing music. * * @author Vladimir Hromada */ data class ChangeMusicRequest( /** * Name */ val name: String, /** * URL to english Wikipedia page about music */ val wikiEn: String?, /** * URL to czech Wikipedia page about music */ val wikiCz: String?, /** * Count of media */ val mediaCount: Int, /** * Note */ val note: String? )
web/src/main/kotlin/com/github/vhromada/catalog/web/connector/entity/ChangeMusicRequest.kt
3456394982
/* * Copyright (C) 2011 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 okhttp3.internal.io import okio.Buffer import okio.ExperimentalFileSystem import okio.FileSystem import okio.ForwardingFileSystem import okio.ForwardingSink import okio.Path import okio.Sink import java.io.IOException import java.util.LinkedHashSet @OptIn(ExperimentalFileSystem::class) class FaultyFileSystem constructor(delegate: FileSystem?) : ForwardingFileSystem(delegate!!) { private val writeFaults: MutableSet<Path> = LinkedHashSet() private val deleteFaults: MutableSet<Path> = LinkedHashSet() private val renameFaults: MutableSet<Path> = LinkedHashSet() fun setFaultyWrite(file: Path, faulty: Boolean) { if (faulty) { writeFaults.add(file) } else { writeFaults.remove(file) } } fun setFaultyDelete(file: Path, faulty: Boolean) { if (faulty) { deleteFaults.add(file) } else { deleteFaults.remove(file) } } fun setFaultyRename(file: Path, faulty: Boolean) { if (faulty) { renameFaults.add(file) } else { renameFaults.remove(file) } } @Throws(IOException::class) override fun atomicMove(source: Path, target: Path) { if (renameFaults.contains(source) || renameFaults.contains(target)) throw IOException("boom!") super.atomicMove(source, target) } @Throws(IOException::class) override fun delete(path: Path) { if (deleteFaults.contains(path)) throw IOException("boom!") super.delete(path) } @Throws(IOException::class) override fun deleteRecursively(fileOrDirectory: Path) { if (deleteFaults.contains(fileOrDirectory)) throw IOException("boom!") super.deleteRecursively(fileOrDirectory) } override fun appendingSink(file: Path): Sink = FaultySink(super.appendingSink(file), file) override fun sink(file: Path): Sink = FaultySink(super.sink(file), file) inner class FaultySink(sink: Sink, private val file: Path) : ForwardingSink(sink) { override fun write(source: Buffer, byteCount: Long) { if (writeFaults.contains(file)) { throw IOException("boom!") } else { super.write(source, byteCount) } } } }
okhttp/src/test/java/okhttp3/internal/io/FaultyFileSystem.kt
4013986537
package com.nononsenseapps.feeder.ui.compose.navdrawer import android.util.Log import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.animation.expandVertically import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.shrinkVertically import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ExpandLess import androidx.compose.material3.Divider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.rotate import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.CustomAccessibilityAction import androidx.compose.ui.semantics.clearAndSetSemantics import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.customActions import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.stateDescription import androidx.compose.ui.semantics.testTag import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import coil.compose.AsyncImage import coil.request.ImageRequest import coil.size.Precision import coil.size.Scale import com.nononsenseapps.feeder.R import com.nononsenseapps.feeder.ui.compose.theme.FeederTheme import com.nononsenseapps.feeder.ui.compose.utils.ImmutableHolder import com.nononsenseapps.feeder.ui.compose.utils.immutableListHolderOf import java.net.URL const val COLLAPSE_ANIMATION_DURATION = 300 @ExperimentalAnimationApi @Composable @Preview(showBackground = true) private fun ListOfFeedsAndTagsPreview() { FeederTheme { Surface { ListOfFeedsAndTags( immutableListHolderOf( DrawerTop(unreadCount = 100, totalChildren = 4), DrawerTag( tag = "News tag", unreadCount = 3, -1111, totalChildren = 2, ), DrawerFeed( id = 1, displayTitle = "Times", tag = "News tag", unreadCount = 1 ), DrawerFeed( id = 2, displayTitle = "Post", imageUrl = URL("https://cowboyprogrammer.org/apple-touch-icon.png"), tag = "News tag", unreadCount = 2 ), DrawerTag( tag = "Funny tag", unreadCount = 6, -2222, totalChildren = 1 ), DrawerFeed( id = 3, displayTitle = "Hidden", tag = "Funny tag", unreadCount = 6 ), DrawerFeed( id = 4, displayTitle = "Top Dog", unreadCount = 99, tag = "" ), DrawerFeed( id = 5, imageUrl = URL("https://cowboyprogrammer.org/apple-touch-icon.png"), displayTitle = "Cowboy Programmer", unreadCount = 7, tag = "" ), ), ImmutableHolder( setOf( "News tag", "Funny tag" ) ), {}, ) {} } } } @ExperimentalAnimationApi @Composable fun ListOfFeedsAndTags( feedsAndTags: ImmutableHolder<List<DrawerItemWithUnreadCount>>, expandedTags: ImmutableHolder<Set<String>>, onToggleTagExpansion: (String) -> Unit, onItemClick: (DrawerItemWithUnreadCount) -> Unit, ) { val firstTopFeed by remember(feedsAndTags) { derivedStateOf { feedsAndTags.item.asSequence().filterIsInstance<DrawerFeed>() .filter { it.tag.isEmpty() }.firstOrNull() } } LazyColumn( contentPadding = WindowInsets.systemBars.asPaddingValues(), modifier = Modifier .fillMaxSize() .semantics { testTag = "feedsAndTags" } ) { items(feedsAndTags.item, key = { it.uiId }) { item -> when (item) { is DrawerTag -> { ExpandableTag( expanded = item.tag in expandedTags.item, onToggleExpansion = onToggleTagExpansion, unreadCount = item.unreadCount, title = item.title(), onItemClick = { onItemClick(item) } ) } is DrawerFeed -> { when { item.tag.isEmpty() -> { if (item.id == firstTopFeed?.id) { Divider( modifier = Modifier.fillMaxWidth() ) } TopLevelFeed( unreadCount = item.unreadCount, title = item.title(), imageUrl = item.imageUrl, onItemClick = { onItemClick(item) } ) } else -> { ChildFeed( unreadCount = item.unreadCount, title = item.title(), imageUrl = item.imageUrl, visible = item.tag in expandedTags.item, onItemClick = { onItemClick(item) } ) } } } is DrawerTop -> AllFeeds( unreadCount = item.unreadCount, title = item.title(), onItemClick = { onItemClick(item) } ) } } } } @ExperimentalAnimationApi @Preview(showBackground = true) @Composable private fun ExpandableTag( title: String = "Foo", unreadCount: Int = 99, expanded: Boolean = true, onToggleExpansion: (String) -> Unit = {}, onItemClick: () -> Unit = {}, ) { val angle: Float by animateFloatAsState( targetValue = if (expanded) 0f else 180f, animationSpec = tween() ) val toggleExpandLabel = stringResource(id = R.string.toggle_tag_expansion) val expandedLabel = stringResource(id = R.string.expanded_tag) val contractedLabel = stringResource(id = R.string.contracted_tag) Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clickable(onClick = onItemClick) .padding(top = 2.dp, bottom = 2.dp, end = 16.dp) .fillMaxWidth() .height(48.dp) .semantics(mergeDescendants = true) { try { stateDescription = if (expanded) { expandedLabel } else { contractedLabel } customActions = listOf( CustomAccessibilityAction(toggleExpandLabel) { onToggleExpansion(title) true } ) } catch (e: Exception) { // Observed nullpointer exception when setting customActions // No clue why it could be null Log.e("FeederNavDrawer", "Exception in semantics", e) } } ) { ExpandArrow(degrees = angle, onClick = { onToggleExpansion(title) }) Box( modifier = Modifier .fillMaxHeight() .weight(1.0f, fill = true) ) { Text( text = title, maxLines = 1, modifier = Modifier .padding(end = 2.dp) .fillMaxWidth() .align(Alignment.CenterStart) ) } val unreadLabel = LocalContext.current.resources.getQuantityString( R.plurals.n_unread_articles, unreadCount, unreadCount ) Text( text = unreadCount.toString(), maxLines = 1, modifier = Modifier .padding(start = 2.dp) .semantics { contentDescription = unreadLabel } ) } } @Composable private fun ExpandArrow( degrees: Float, onClick: () -> Unit, ) { IconButton(onClick = onClick, modifier = Modifier.clearAndSetSemantics { }) { Icon( Icons.Filled.ExpandLess, contentDescription = stringResource(id = R.string.toggle_tag_expansion), modifier = Modifier.rotate(degrees = degrees) ) } } @Preview(showBackground = true) @Composable private fun AllFeeds( title: String = "Foo", unreadCount: Int = 99, onItemClick: () -> Unit = {}, ) = Feed( title = title, imageUrl = null, unreadCount = unreadCount, startPadding = 16.dp, onItemClick = onItemClick, ) @Preview(showBackground = true) @Composable private fun TopLevelFeed( title: String = "Foo", unreadCount: Int = 99, onItemClick: () -> Unit = {}, imageUrl: URL? = null, ) = Feed( title = title, imageUrl = imageUrl, unreadCount = unreadCount, startPadding = when (imageUrl) { null -> 48.dp else -> 0.dp }, onItemClick = onItemClick, ) @Preview(showBackground = true) @Composable private fun ChildFeed( title: String = "Foo", imageUrl: URL? = null, unreadCount: Int = 99, visible: Boolean = true, onItemClick: () -> Unit = {}, ) { AnimatedVisibility( visible = visible, enter = fadeIn() + expandVertically(expandFrom = Alignment.Top), exit = shrinkVertically(shrinkTowards = Alignment.Top) + fadeOut() ) { Feed( title = title, imageUrl = imageUrl, unreadCount = unreadCount, startPadding = when (imageUrl) { null -> 48.dp else -> 0.dp }, onItemClick = onItemClick, ) } } @Composable private fun Feed( title: String, imageUrl: URL?, unreadCount: Int, startPadding: Dp, onItemClick: () -> Unit, ) { Row( horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier .clickable(onClick = onItemClick) .padding( start = startPadding, end = 16.dp, top = 2.dp, bottom = 2.dp ) .fillMaxWidth() .height(48.dp) ) { if (imageUrl != null) { Box( contentAlignment = Alignment.Center, modifier = Modifier .height(48.dp) // Taking 4dp spacing into account .width(44.dp), ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(imageUrl.toString()).listener(onError = { a, b -> Log.e("FEEDER_DRAWER", "error ${a.data}", b.throwable) }).scale(Scale.FIT).size(64).precision(Precision.INEXACT).build(), contentDescription = stringResource(id = R.string.feed_icon), contentScale = ContentScale.Crop, modifier = Modifier.size(24.dp) ) } } Box( modifier = Modifier .fillMaxHeight() .weight(1.0f, fill = true) ) { Text( text = title, maxLines = 1, modifier = Modifier .fillMaxWidth() .align(Alignment.CenterStart) ) } val unreadLabel = LocalContext.current.resources.getQuantityString( R.plurals.n_unread_articles, unreadCount, unreadCount ) Text( text = unreadCount.toString(), maxLines = 1, modifier = Modifier.semantics { contentDescription = unreadLabel } ) } }
app/src/main/java/com/nononsenseapps/feeder/ui/compose/navdrawer/NavDrawer.kt
3294466703
package org.stepik.android.domain.course_list.interactor import org.stepic.droid.preferences.SharedPreferenceHelper import org.stepik.android.domain.base.DataSourceType import org.stepik.android.domain.user_courses.repository.UserCoursesRepository import javax.inject.Inject class RemindAppNotificationInteractor @Inject constructor( private val sharedPreferenceHelper: SharedPreferenceHelper, private val userCoursesRepository: UserCoursesRepository ) { fun isNotificationShown(): Boolean { val isFirstDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_ONE) val isSevenDayNotificationShown = sharedPreferenceHelper.isNotificationWasShown(SharedPreferenceHelper.NotificationDay.DAY_SEVEN) // already shown. // do not show again return isFirstDayNotificationShown && isSevenDayNotificationShown } fun hasUserInteractedWithApp(): Boolean = sharedPreferenceHelper.authResponseFromStore == null || sharedPreferenceHelper.isStreakNotificationEnabled || hasEnrolledCourses() || sharedPreferenceHelper.anyStepIsSolved() private fun hasEnrolledCourses(): Boolean = userCoursesRepository .getUserCourses(sourceType = DataSourceType.CACHE) .blockingGet() .isNotEmpty() }
app/src/main/java/org/stepik/android/domain/course_list/interactor/RemindAppNotificationInteractor.kt
4270619024
package com.baculsoft.kotlin.android.internal.data.local import org.parceler.Parcel import org.parceler.ParcelConstructor import org.parceler.ParcelProperty /** * @author Budi Oktaviyan Suryanto ([email protected]) */ @Parcel(Parcel.Serialization.BEAN) data class TwitterSearch @ParcelConstructor constructor( @ParcelProperty(value = "twitterSearchResults") val twitterSearchResults: List<TwitterSearchResult>, @ParcelProperty(value = "count") val count: Int )
app/src/main/kotlin/com/baculsoft/kotlin/android/internal/data/local/TwitterSearch.kt
1438274807
package com.foebalapp.backend.security import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter @Configuration @EnableWebSecurity(debug = false) class SecurityConfig : WebSecurityConfigurerAdapter() { @Throws(Exception::class) override fun configure(http: HttpSecurity) { http.addFilterBefore(FirebaseFilter(), WebAsyncManagerIntegrationFilter::class.java) http.anonymous().disable() .exceptionHandling().disable() .logout().disable() .requestCache().disable() .securityContext().disable() .servletApi().disable() .sessionManagement().disable() .csrf().disable() .headers().and() .authorizeRequests().antMatchers("/**").authenticated() } }
backend/src/main/kotlin/com/foebalapp/backend/security/SecurityConfig.kt
724710843
/* * 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.jetbrains.python.console import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.ProcessHandler import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.util.Ref import com.intellij.remote.CredentialsType import com.intellij.remote.ext.CredentialsCase import com.jetbrains.python.PyBundle import com.jetbrains.python.remote.PyRemotePathMapper import com.jetbrains.python.remote.PyRemoteSdkAdditionalDataBase import com.jetbrains.python.remote.PyRemoteSocketToLocalHostProvider import java.io.IOException interface PythonConsoleRemoteProcessCreator<T> { val credentialsType: CredentialsType<T> @Throws(ExecutionException::class) fun createRemoteConsoleProcess(commandLine: GeneralCommandLine, pathMapper: PyRemotePathMapper, project: Project, data: PyRemoteSdkAdditionalDataBase, runnerFileFromHelpers: String, credentials: T): RemoteConsoleProcessData /** * Tries to create a remote tunnel. * @return Port on the remote server or null if port forwarding by this method is not implemented. */ @JvmDefault @Throws(IOException::class) fun createRemoteTunnel(project: Project, data: PyRemoteSdkAdditionalDataBase, localPort: Int): Int? = localPort companion object { @JvmField val EP_NAME: ExtensionPointName<PythonConsoleRemoteProcessCreator<Any>> = ExtensionPointName.create<PythonConsoleRemoteProcessCreator<Any>>( "Pythonid.remoteConsoleProcessCreator") } } data class RemoteConsoleProcessData(val remoteProcessHandlerBase: ProcessHandler, val pydevConsoleCommunication: PydevConsoleCommunication, val commandLine: String?, val process: Process, val socketProvider: PyRemoteSocketToLocalHostProvider) @Throws(ExecutionException::class) fun createRemoteConsoleProcess(commandLine: GeneralCommandLine, pathMapper: PyRemotePathMapper, project: Project, data: PyRemoteSdkAdditionalDataBase, runnerFileFromHelpers: String): RemoteConsoleProcessData { val extensions = PythonConsoleRemoteProcessCreator.EP_NAME.extensions val result = Ref.create<RemoteConsoleProcessData>() val exception = Ref.create<ExecutionException>() val collectedCases = extensions.map { object : CredentialsCase<Any> { override fun getType(): CredentialsType<Any> = it.credentialsType override fun process(credentials: Any) { try { val remoteConsoleProcess = it.createRemoteConsoleProcess(commandLine = commandLine, pathMapper = pathMapper, project = project, data = data, runnerFileFromHelpers = runnerFileFromHelpers, credentials = credentials) result.set(remoteConsoleProcess) } catch (e: ExecutionException) { exception.set(e) } } } as CredentialsCase<Any> } data.switchOnConnectionType(*collectedCases.toTypedArray()) if (!exception.isNull) { throw exception.get() } else if (!result.isNull) { return result.get() } else { throw ExecutionException(PyBundle.message("python.console.not.supported", data.remoteConnectionType.name)) } }
python/src/com/jetbrains/python/console/PythonConsoleRemoteProcessCreator.kt
2975123031
package gdl.dreamteam.skynet.Others import gdl.dreamteam.skynet.Models.Zone import java.util.concurrent.CompletableFuture /** * Created by christopher on 28/08/17. */ interface IDataRepository { fun addZone(zone: Zone): CompletableFuture<Unit> fun getZone(name: String): CompletableFuture<Zone?> fun deleteZone(name: String): CompletableFuture<Unit> fun updateZone(name: String, zone: Zone): CompletableFuture<Unit> }
SkyNet/app/src/main/java/gdl/dreamteam/skynet/Others/IDataRepository.kt
3797180080
package com.richodemus.chronicler.server.core interface EventCreationListener { fun onEvent(event: Event) }
server/core/src/main/kotlin/com/richodemus/chronicler/server/core/EventCreationListener.kt
2322731441
package i_introduction._1_Java_To_Kotlin_Converter import kotlin.test.* import org.junit.Test import org.junit.Assert class _01_Functions() { @Test fun collection() { Assert.assertEquals("{1, 2, 3, 42, 555}", task1(listOf(1, 2, 3, 42, 555))) } }
test/i_introduction/_1_Java_To_Kotlin_Converter/_01_Functions.kt
567217435
// Copyright 2000-2019 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 git4idea.ignore import com.intellij.configurationStore.saveComponentManager import com.intellij.dvcs.ignore.VcsRepositoryIgnoredFilesHolderBase import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.module.ModuleType import com.intellij.openapi.roots.CompilerProjectExtension import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.vcs.VcsApplicationSettings import com.intellij.openapi.vcs.changes.VcsIgnoreManagerImpl import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.PsiTestUtil import com.intellij.util.TimeoutUtil import com.intellij.vcsUtil.VcsImplUtil import com.intellij.vfs.AsyncVfsEventsPostProcessorImpl import git4idea.repo.GitRepositoryFiles.GITIGNORE import git4idea.test.GitSingleRepoTest import java.io.File class ConvertExcludedToGitIgnoredTest : GitSingleRepoTest() { private lateinit var moduleContentRoot: VirtualFile private lateinit var gitIgnore: File override fun getProjectDirOrFile() = getProjectDirOrFile(true) override fun setUp() { super.setUp() VcsApplicationSettings.getInstance().MANAGE_IGNORE_FILES = true Registry.get("vcs.ignorefile.generation").setValue(true, testRootDisposable) Registry.get("ide.hide.excluded.files").setValue(false, testRootDisposable) gitIgnore = File("$projectPath/$GITIGNORE") } override fun setUpProject() { super.setUpProject() invokeAndWaitIfNeeded { saveComponentManager(project) } //will create .idea directory } override fun setUpModule() { runWriteAction { myModule = createMainModule() moduleContentRoot = myModule.moduleFile!!.parent myModule.addContentRoot(moduleContentRoot) } } fun testExcludedFolder() { val excluded = createChildDirectory(moduleContentRoot, "exc") createChildData(excluded, "excluded.txt") //Don't mark empty directories like ignored since versioning such directories not supported in Git PsiTestUtil.addExcludedRoot(myModule, excluded) generateIgnoreFileAndWaitHoldersUpdate() assertGitignoreValid(gitIgnore, """ # Project exclude paths /exc/ """) assertFalse(changeListManager.isIgnoredFile(moduleContentRoot)) assertTrue(changeListManager.isIgnoredFile(excluded)) } fun testModuleOutput() { val output = createChildDirectory(moduleContentRoot, "out") PsiTestUtil.setCompilerOutputPath(myModule, output.url, false) createChildData(output, "out.class") generateIgnoreFileAndWaitHoldersUpdate() assertGitignoreValid(gitIgnore, """ # Project exclude paths /out/ """) assertFalse(changeListManager.isIgnoredFile(moduleContentRoot)) assertTrue(changeListManager.isIgnoredFile(output)) } fun testProjectOutput() { val output = createChildDirectory(projectRoot, "projectOutput") createChildData(output, "out.class") CompilerProjectExtension.getInstance(project)!!.compilerOutputUrl = output.url generateIgnoreFileAndWaitHoldersUpdate() assertGitignoreValid(gitIgnore, """ # Project exclude paths /projectOutput/ """) assertTrue(changeListManager.isIgnoredFile(output)) } fun testModuleOutputUnderProjectOutput() { val output = createChildDirectory(projectRoot, "projectOutput") createChildData(output, "out.class") CompilerProjectExtension.getInstance(project)!!.compilerOutputUrl = output.url val moduleOutput = createChildDirectory(output, "module") PsiTestUtil.setCompilerOutputPath(myModule, moduleOutput.url, false) generateIgnoreFileAndWaitHoldersUpdate() assertGitignoreValid(gitIgnore, """ # Project exclude paths /projectOutput/ """) assertTrue(changeListManager.isIgnoredFile(output)) assertTrue(changeListManager.isIgnoredFile(moduleOutput)) } fun testModuleOutputUnderExcluded() { val excluded = createChildDirectory(moduleContentRoot, "target") createChildData(excluded, "out.class") PsiTestUtil.addExcludedRoot(myModule, excluded) val moduleOutput = createChildDirectory(excluded, "classes") createChildData(moduleOutput, "out.class") PsiTestUtil.setCompilerOutputPath(myModule, moduleOutput.url, false) generateIgnoreFileAndWaitHoldersUpdate() assertGitignoreValid(gitIgnore, """ # Project exclude paths /target/ """) assertTrue(changeListManager.isIgnoredFile(excluded)) assertTrue(changeListManager.isIgnoredFile(moduleOutput)) } fun testDoNotIgnoreInnerModuleExplicitlyMarkedAsExcludedFromOuterModule() { val inner = createChildDirectory(moduleContentRoot, "inner") createChildData(inner, "inner.txt") PsiTestUtil.addModule(myProject, ModuleType.EMPTY, "inner", inner) PsiTestUtil.addExcludedRoot(myModule, inner) assertFalse(changeListManager.isIgnoredFile(inner)) } private fun generateIgnoreFileAndWaitHoldersUpdate() { AsyncVfsEventsPostProcessorImpl.waitEventsProcessed() flushIgnoreHoldersQueue() val waiter = (repo.ignoredFilesHolder as VcsRepositoryIgnoredFilesHolderBase<*>).createWaiter() VcsImplUtil.generateIgnoreFileIfNeeded(project, vcs, projectRoot) waiter.waitFor() } private fun flushIgnoreHoldersQueue() { with(VcsIgnoreManagerImpl.getInstanceImpl(project).ignoreRefreshQueue) { flush() while (isFlushing) { TimeoutUtil.sleep(100) } } } }
plugins/git4idea/tests/git4idea/ignore/ConvertExcludedToGitIgnoredTest.kt
589338143
/* * Copyright (C) 2017 Darel Bitsy * 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.dbeginc.dbweatherdata.proxies.local.weather import android.support.annotation.RestrictTo /** * Created by darel on 16.09.17. * * Local Daily Data */ @RestrictTo(RestrictTo.Scope.LIBRARY) data class LocalDailyData( val time: Long, val summary: String, val icon: String, val temperatureHigh: Double, val temperatureHighTime: Long, val temperatureLow: Double, val temperatureLowTime: Long, val apparentTemperatureHigh: Double, val apparentTemperatureHighTime: Long, val apparentTemperatureLow: Double, val apparentTemperatureLowTime: Long, val dewPoint: Double, val humidity: Double, val pressure: Double, val windSpeed: Double, val windGust: Double, val windGustTime: Long, val windBearing: Long, val cloudCover: Double, val moonPhase: Double, val visibility: Double, val uvIndex: Long, val uvIndexTime: Long, val sunsetTime: Long, val sunriseTime: Long, val precipIntensity: Double, val precipIntensityMax: Double, val precipProbability: Double, val precipType: String? )
dbweatherdata/src/main/java/com/dbeginc/dbweatherdata/proxies/local/weather/LocalDailyData.kt
3596044893
/* * Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte.entity import com.github.moko256.latte.client.base.ApiClient import com.github.moko256.latte.client.base.MediaUrlConverter import com.github.moko256.latte.client.base.entity.AccessToken import com.github.moko256.latte.client.base.entity.Friendship import com.github.moko256.latte.client.twitter.CLIENT_TYPE_TWITTER import com.github.moko256.twitlatte.cacheMap.PostCache import com.github.moko256.twitlatte.cacheMap.StatusCacheMap import com.github.moko256.twitlatte.cacheMap.UserCacheMap import com.github.moko256.twitlatte.collections.LruCache /** * Created by moko256 on 2018/11/28. * * @author moko256 */ data class Client( val accessToken: AccessToken, val apiClient: ApiClient, val mediaUrlConverter: MediaUrlConverter, val statusCache: StatusCacheMap, val userCache: UserCacheMap, val friendshipCache: LruCache<Long, Friendship> ) { val postCache: PostCache = PostCache(statusCache, userCache) val statusLimit: Int = if (accessToken.clientType == CLIENT_TYPE_TWITTER) 200 else 40 }
app/src/main/java/com/github/moko256/twitlatte/entity/Client.kt
1814617554
import A.B import A.B.C class A { class B { class C } } fun box(): String { val a = A() val b = B() val ab = A.B() val c = C() val bc = B.C() val abc = A.B.C() return "OK" }
backend.native/tests/external/codegen/box/innerNested/importNestedClass.kt
3306872705
// !DIAGNOSTICS: -UNUSED_PARAMETER // IGNORE_BACKEND_WITHOUT_CHECK: JS tailrec fun Int.foo(x: Int) { if (x == 0) return return 1.foo(x - 1) } fun box(): String { 1.foo(1000000) return "OK" }
backend.native/tests/external/codegen/box/diagnostics/functions/tailRecursion/extensionTailCall.kt
4284701740
import kotlin.test.* fun <T> compare(expected: T, actual: T, block: CompareContext<T>.() -> Unit) { CompareContext(expected, actual).block() } class CompareContext<out T>(public val expected: T, public val actual: T) { public fun equals(message: String = "") { assertEquals(expected, actual, message) } public fun <P> propertyEquals(message: String = "", getter: T.() -> P) { assertEquals(expected.getter(), actual.getter(), message) } public fun propertyFails(getter: T.() -> Unit) { assertFailEquals({ expected.getter() }, { actual.getter() }) } public fun <P> compareProperty(getter: T.() -> P, block: CompareContext<P>.() -> Unit) { compare(expected.getter(), actual.getter(), block) } private fun assertFailEquals(expected: () -> Unit, actual: () -> Unit) { val expectedFail = assertFails(expected) val actualFail = assertFails(actual) //assertEquals(expectedFail != null, actualFail != null) assertTypeEquals(expectedFail, actualFail) } } fun <T> CompareContext<Iterator<T>>.iteratorBehavior() { propertyEquals { hasNext() } while (expected.hasNext()) { propertyEquals { next() } propertyEquals { hasNext() } } propertyFails { next() } } public fun <N : Any> doTest( sequence: Iterable<N>, expectedFirst: N, expectedLast: N, expectedIncrement: Number, expectedElements: List<N> ) { val first: Any val last: Any val increment: Number when (sequence) { is IntProgression -> { first = sequence.first last = sequence.last increment = sequence.step } is LongProgression -> { first = sequence.first last = sequence.last increment = sequence.step } is CharProgression -> { first = sequence.first last = sequence.last increment = sequence.step } else -> throw IllegalArgumentException("Unsupported sequence type: $sequence") } assertEquals(expectedFirst, first) assertEquals(expectedLast, last) assertEquals(expectedIncrement, increment) if (expectedElements.isEmpty()) assertTrue(sequence.none()) else assertEquals(expectedElements, sequence.toList()) compare(expectedElements.iterator(), sequence.iterator()) { iteratorBehavior() } } fun box() { doTest(5..5, 5, 5, 1, listOf(5)) doTest(5.toByte()..5.toByte(), 5, 5, 1, listOf(5)) doTest(5.toShort()..5.toShort(), 5, 5, 1, listOf(5)) doTest(5.toLong()..5.toLong(), 5.toLong(), 5.toLong(), 1.toLong(), listOf(5.toLong())) doTest('k'..'k', 'k', 'k', 1, listOf('k')) }
backend.native/tests/external/stdlib/ranges/RangeIterationTest/oneElementRange.kt
4003613644
/* * This file is part of Blokada. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. * * Copyright © 2021 Blocka AB. All rights reserved. * * @author Karol Gusak ([email protected]) */ package repository import android.content.pm.ApplicationInfo import android.content.pm.PackageManager import android.graphics.drawable.Drawable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.async import model.App import model.AppId import model.BypassedAppIds import service.ContextService import service.PersistenceService import ui.utils.cause import utils.Logger object AppRepository { private val log = Logger("AppRepository") private val context = ContextService private val persistence = PersistenceService private val scope = GlobalScope private var bypassedAppIds = persistence.load(BypassedAppIds::class).ids set(value) { persistence.save(BypassedAppIds(value)) field = value } private val alwaysBypassed by lazy { listOf<AppId>( // This app package name context.requireContext().packageName ) } private val bypassedForFakeVpn = listOf( "com.android.vending", "com.android.providers.downloads", "com.google.android.apps.fireball", "com.google.android.apps.authenticator2", "com.google.android.apps.docs", "com.google.android.apps.tachyon", "com.google.android.gm", "com.google.android.apps.photos", "com.google.android.play.games", "org.thoughtcrime.securesms", "com.plexapp.android", "org.kde.kdeconnect_tp", "com.samsung.android.email.provider", "com.xda.labs", "com.android.incallui", "com.android.phone", "com.android.providers.telephony", "com.huawei.systemmanager", "com.android.service.ims.RcsServiceApp", "com.google.android.carriersetup", "com.google.android.ims", "com.codeaurora.ims", "com.android.carrierconfig", "ch.threema.app", "ch.threema.app.work", "ch.threema.app.hms", "ch.threema.app.work.hms", "com.xiaomi.discover", "eu.siacs.conversations", "org.jitsi.meet", "com.tomtom.speedcams.android.map", "com.tomtom.amigo.huawei", // RCS: https://github.com/blokadaorg/blokadaorg.github.io/pull/31 "com.android.service.ims.RcsServiceApp", "com.google.android.carriersetup", "com.google.android.ims", "com.codeaurora.ims", "com.android.carrierconfig", // MaaiiConnect #885 "com.m800.liveconnect.mobile.agent.prod", "com.m800.liveconnect.mobile.agent.tb", // TomTom Go #878 "com.tomtom.gplay.navapp" ) fun getPackageNamesOfAppsToBypass(forRealTunnel: Boolean = false): List<AppId> { return if (forRealTunnel) alwaysBypassed + bypassedAppIds else alwaysBypassed + bypassedForFakeVpn + bypassedAppIds } suspend fun getApps(): List<App> { return scope.async(Dispatchers.Default) { log.v("Fetching apps") val ctx = context.requireContext() val installed = try { ctx.packageManager.getInstalledApplications(PackageManager.GET_META_DATA) .filter { it.packageName != ctx.packageName } } catch (ex: Exception) { log.w("Could not fetch apps, ignoring".cause(ex)) emptyList<ApplicationInfo>() } log.v("Fetched ${installed.size} apps, mapping") val apps = installed.mapNotNull { try { App( id = it.packageName, name = ctx.packageManager.getApplicationLabel(it).toString(), isSystem = (it.flags and ApplicationInfo.FLAG_SYSTEM) != 0, isBypassed = isAppBypassed(it.packageName) ) } catch (ex: Exception) { log.w("Could not map app, ignoring".cause(ex)) null } } log.v("Mapped ${apps.size} apps") apps }.await() } fun isAppBypassed(id: AppId): Boolean { return bypassedAppIds.contains(id) } fun switchBypassForApp(id: AppId) { if (isAppBypassed(id)) bypassedAppIds -= id else bypassedAppIds += id } fun getAppIcon(id: AppId): Drawable? { return try { val ctx = context.requireContext() ctx.packageManager.getApplicationIcon( ctx.packageManager.getApplicationInfo(id, PackageManager.GET_META_DATA) ) } catch (e: Exception) { null } } }
android5/app/src/main/java/repository/AppRepository.kt
1777169494
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* var x = true private suspend fun foo(): String { if (x) { return suspendCoroutineOrReturn<String> { it.resume("OK") COROUTINE_SUSPENDED } } return "fail" } fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } fun box(): String { var res = "" builder { res = foo() } return res }
backend.native/tests/external/codegen/box/coroutines/suspendFunctionAsCoroutine/privateInFile.kt
2134430935
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import androidx.compose.foundation.text.matchers.isZero import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.ExperimentalTextApi import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.createFontFamilyResolver import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.sp import androidx.test.filters.SmallTest import androidx.test.platform.app.InstrumentationRegistry import com.google.common.truth.Truth.assertThat import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 import kotlin.math.floor @OptIn(InternalFoundationTextApi::class) @RunWith(AndroidJUnit4::class) @SmallTest class TextLayoutResultIntegrationTest { private val fontFamily = TEST_FONT_FAMILY private val density = Density(density = 1f) private val context = InstrumentationRegistry.getInstrumentation().context @OptIn(ExperimentalTextApi::class) private val fontFamilyResolver = createFontFamilyResolver(context) private val layoutDirection = LayoutDirection.Ltr @Test fun width_getter() { with(density) { val fontSize = 20.sp val text = "Hello" val spanStyle = SpanStyle(fontSize = fontSize, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = this, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(0, 200), layoutDirection) assertThat(layoutResult.size.width).isEqualTo( (fontSize.toPx() * text.length).toIntPx() ) } } @Test fun width_getter_with_small_width() { val text = "Hello" val width = 80 val spanStyle = SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = density, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(maxWidth = width), layoutDirection) assertThat(layoutResult.size.width).isEqualTo(width) } @Test fun height_getter() { with(density) { val fontSize = 20.sp val spanStyle = SpanStyle(fontSize = fontSize, fontFamily = fontFamily) val text = "hello" val annotatedString = AnnotatedString(text, spanStyle) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = this, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(), layoutDirection) assertThat(layoutResult.size.height).isEqualTo((fontSize.toPx()).toIntPx()) } } @Test fun layout_build_layoutResult() { val textDelegate = TextDelegate( text = AnnotatedString(text = "Hello"), style = TextStyle.Default, density = density, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(0, 20), layoutDirection) assertThat(layoutResult).isNotNull() } @Test fun getPositionForOffset_First_Character() { val text = "Hello" val annotatedString = AnnotatedString( text, SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) ) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = density, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(), layoutDirection) val selection = layoutResult.getOffsetForPosition(Offset.Zero) assertThat(selection).isZero() } @Test fun getPositionForOffset_other_Character() { with(density) { val fontSize = 20.sp val characterIndex = 2 // Start from 0. val text = "Hello" val annotatedString = AnnotatedString( text, SpanStyle(fontSize = fontSize, fontFamily = fontFamily) ) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = this, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(), layoutDirection) val selection = layoutResult.getOffsetForPosition( position = Offset((fontSize.toPx() * characterIndex + 1), 0f) ) assertThat(selection).isEqualTo(characterIndex) } } @Test fun hasOverflowShaderFalse() { val text = "Hello" val spanStyle = SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = density, fontFamilyResolver = fontFamilyResolver ) val layoutResult = textDelegate.layout(Constraints(), layoutDirection) assertThat(layoutResult.hasVisualOverflow).isFalse() // paint should not throw exception TextDelegate.paint(Canvas(android.graphics.Canvas()), layoutResult) } @Test fun didOverflowHeight_isTrue_when_maxLines_exceeded() { val text = "HelloHellowHelloHello" val spanStyle = SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val maxLines = 3 val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, maxLines = maxLines, density = density, fontFamilyResolver = fontFamilyResolver ) textDelegate.layoutIntrinsics(layoutDirection) // Tries to make 5 lines of text, which exceeds the given maxLines(3). val maxWidth = textDelegate.maxIntrinsicWidth / 5 val layoutResult = textDelegate.layout( Constraints(maxWidth = maxWidth), layoutDirection ) assertThat(layoutResult.didOverflowHeight).isTrue() } @Test fun didOverflowHeight_isFalse_when_maxLines_notExceeded() { val text = "HelloHellowHelloHello" val spanStyle = SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val maxLines = 10 val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, maxLines = maxLines, density = density, fontFamilyResolver = fontFamilyResolver ) textDelegate.layoutIntrinsics(layoutDirection) // Tries to make 5 lines of text, which doesn't exceed the given maxLines(10). val maxWidth = textDelegate.maxIntrinsicWidth / 5 val layoutResult = textDelegate.layout( Constraints(maxWidth = maxWidth), layoutDirection ) assertThat(layoutResult.didOverflowHeight).isFalse() } @Test fun didOverflowHeight_isTrue_when_maxHeight_exceeded() { val text = "HelloHellowHelloHello" val spanStyle = SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = density, fontFamilyResolver = fontFamilyResolver ) val maxIntrinsicsHeight = textDelegate.layout( Constraints(), layoutDirection ).multiParagraph.height // Make maxHeight smaller than needed. val maxHeight = floor(maxIntrinsicsHeight / 2).toInt() val layoutResult = textDelegate.layout( Constraints(maxHeight = maxHeight), layoutDirection ) assertThat(layoutResult.didOverflowHeight).isTrue() } @Test fun didOverflowHeight_isFalse_when_maxHeight_notExceeded() { val text = "HelloHellowHelloHello" val spanStyle = SpanStyle(fontSize = 20.sp, fontFamily = fontFamily) val annotatedString = AnnotatedString(text, spanStyle) val textDelegate = TextDelegate( text = annotatedString, style = TextStyle.Default, density = density, fontFamilyResolver = fontFamilyResolver ) val maxIntrinsicsHeight = textDelegate.layout( Constraints(), layoutDirection ).multiParagraph.height // Make max height larger than the needed. val maxHeight = floor(maxIntrinsicsHeight * 2).toInt() val layoutResult = textDelegate.layout( Constraints(maxHeight = maxHeight), layoutDirection ) assertThat(layoutResult.didOverflowHeight).isFalse() } }
compose/foundation/foundation/src/androidAndroidTest/kotlin/androidx/compose/foundation/text/TextLayoutResultIntegrationTest.kt
2001974871
package de.kleinelamas.svbrockscheid.injection import dagger.Module import dagger.android.ContributesAndroidInjector import de.kleinelamas.svbrockscheid.MainActivity import de.kleinelamas.svbrockscheid.fragments.GamesFragment /** * @author Matthias Kutscheid * Module for dagger bindings */ @Module abstract class BindingModule { @ContributesAndroidInjector abstract fun mainActivity(): MainActivity @ContributesAndroidInjector abstract fun gamesFragment(): GamesFragment }
app/src/main/java/de/kleinelamas/svbrockscheid/injection/BindingModule.kt
1995696803
// "Replace with 'newFun(p)'" "true" @Deprecated("", ReplaceWith("newFun(p)")) infix fun String.oldFun(p: Int) { newFun(p) } infix fun String.newFun(p: Int) { } fun foo() { "" <caret>oldFun 1 }
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/keepInfixCall.kt
3665589923
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.diff.tools.util.base import com.intellij.diff.util.DiffPlaces import com.intellij.diff.util.DiffUtil import com.intellij.openapi.Disposable import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.util.Key import com.intellij.util.EventDispatcher import com.intellij.util.xmlb.annotations.OptionTag import com.intellij.util.xmlb.annotations.Transient import com.intellij.util.xmlb.annotations.XMap import java.util.* @State( name = "TextDiffSettings", storages = arrayOf(Storage(value = DiffUtil.DIFF_CONFIG)) ) class TextDiffSettingsHolder : PersistentStateComponent<TextDiffSettingsHolder.State> { companion object { @JvmField val CONTEXT_RANGE_MODES: IntArray = intArrayOf(1, 2, 4, 8, -1) @JvmField val CONTEXT_RANGE_MODE_LABELS: Array<String> = arrayOf("1", "2", "4", "8", "Disable") } data class SharedSettings( // Fragments settings var CONTEXT_RANGE: Int = 4, var MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES: Boolean = false, var MERGE_LST_GUTTER_MARKERS: Boolean = true ) data class PlaceSettings( // Diff settings var HIGHLIGHT_POLICY: HighlightPolicy = HighlightPolicy.BY_WORD, var IGNORE_POLICY: IgnorePolicy = IgnorePolicy.DEFAULT, // Presentation settings var ENABLE_SYNC_SCROLL: Boolean = true, // Editor settings var SHOW_WHITESPACES: Boolean = false, var SHOW_LINE_NUMBERS: Boolean = true, var SHOW_INDENT_LINES: Boolean = false, var USE_SOFT_WRAPS: Boolean = false, var HIGHLIGHTING_LEVEL: HighlightingLevel = HighlightingLevel.INSPECTIONS, var READ_ONLY_LOCK: Boolean = true, // Fragments settings var EXPAND_BY_DEFAULT: Boolean = true ) { @Transient val eventDispatcher: EventDispatcher<TextDiffSettings.Listener> = EventDispatcher.create(TextDiffSettings.Listener::class.java) } class TextDiffSettings internal constructor(private val SHARED_SETTINGS: SharedSettings, private val PLACE_SETTINGS: PlaceSettings) { constructor() : this(SharedSettings(), PlaceSettings()) fun addListener(listener: Listener, disposable: Disposable) { PLACE_SETTINGS.eventDispatcher.addListener(listener, disposable) } // Presentation settings var isEnableSyncScroll: Boolean get() = PLACE_SETTINGS.ENABLE_SYNC_SCROLL set(value) { PLACE_SETTINGS.ENABLE_SYNC_SCROLL = value } // Diff settings var highlightPolicy: HighlightPolicy get() = PLACE_SETTINGS.HIGHLIGHT_POLICY set(value) { PLACE_SETTINGS.HIGHLIGHT_POLICY = value PLACE_SETTINGS.eventDispatcher.multicaster.highlightPolicyChanged() } var ignorePolicy: IgnorePolicy get() = PLACE_SETTINGS.IGNORE_POLICY set(value) { PLACE_SETTINGS.IGNORE_POLICY = value PLACE_SETTINGS.eventDispatcher.multicaster.ignorePolicyChanged() } // // Merge // var isAutoApplyNonConflictedChanges: Boolean get() = SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES set(value) { SHARED_SETTINGS.MERGE_AUTO_APPLY_NON_CONFLICTED_CHANGES = value } var isEnableLstGutterMarkersInMerge: Boolean get() = SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS set(value) { SHARED_SETTINGS.MERGE_LST_GUTTER_MARKERS = value } // Editor settings var isShowLineNumbers: Boolean get() = PLACE_SETTINGS.SHOW_LINE_NUMBERS set(value) { PLACE_SETTINGS.SHOW_LINE_NUMBERS = value } var isShowWhitespaces: Boolean get() = PLACE_SETTINGS.SHOW_WHITESPACES set(value) { PLACE_SETTINGS.SHOW_WHITESPACES = value } var isShowIndentLines: Boolean get() = PLACE_SETTINGS.SHOW_INDENT_LINES set(value) { PLACE_SETTINGS.SHOW_INDENT_LINES = value } var isUseSoftWraps: Boolean get() = PLACE_SETTINGS.USE_SOFT_WRAPS set(value) { PLACE_SETTINGS.USE_SOFT_WRAPS = value } var highlightingLevel: HighlightingLevel get() = PLACE_SETTINGS.HIGHLIGHTING_LEVEL set(value) { PLACE_SETTINGS.HIGHLIGHTING_LEVEL = value } var contextRange: Int get() = SHARED_SETTINGS.CONTEXT_RANGE set(value) { SHARED_SETTINGS.CONTEXT_RANGE = value } var isExpandByDefault: Boolean get() = PLACE_SETTINGS.EXPAND_BY_DEFAULT set(value) { PLACE_SETTINGS.EXPAND_BY_DEFAULT = value } var isReadOnlyLock: Boolean get() = PLACE_SETTINGS.READ_ONLY_LOCK set(value) { PLACE_SETTINGS.READ_ONLY_LOCK = value } // // Impl // companion object { @JvmField val KEY: Key<TextDiffSettings> = Key.create("TextDiffSettings") @JvmStatic fun getSettings(): TextDiffSettings = getSettings(null) @JvmStatic fun getSettings(place: String?): TextDiffSettings = service<TextDiffSettingsHolder>().getSettings(place) } interface Listener : EventListener { fun highlightPolicyChanged() {} fun ignorePolicyChanged() {} } } fun getSettings(place: String?): TextDiffSettings { val placeKey = place ?: DiffPlaces.DEFAULT val placeSettings = myState.PLACES_MAP.getOrPut(placeKey, { defaultPlaceSettings(placeKey) }) return TextDiffSettings(myState.SHARED_SETTINGS, placeSettings) } private fun copyStateWithoutDefaults(): State { val result = State() result.SHARED_SETTINGS = myState.SHARED_SETTINGS result.PLACES_MAP = DiffUtil.trimDefaultValues(myState.PLACES_MAP, { defaultPlaceSettings(it) }) return result } private fun defaultPlaceSettings(place: String): PlaceSettings { val settings = PlaceSettings() if (place == DiffPlaces.CHANGES_VIEW) { settings.EXPAND_BY_DEFAULT = false } if (place == DiffPlaces.COMMIT_DIALOG) { settings.EXPAND_BY_DEFAULT = false } return settings } class State { @OptionTag @XMap @JvmField var PLACES_MAP: TreeMap<String, PlaceSettings> = TreeMap() @JvmField var SHARED_SETTINGS = SharedSettings() } private var myState: State = State() override fun getState(): State { return copyStateWithoutDefaults() } override fun loadState(state: State) { myState = state } }
platform/diff-impl/src/com/intellij/diff/tools/util/base/TextDiffSettingsHolder.kt
3664041244
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide.formatter import com.intellij.psi.codeStyle.CodeStyleSettings import org.toml.ide.formatter.settings.TomlCodeStyleSettings val CodeStyleSettings.toml: TomlCodeStyleSettings get() = getCustomSettings(TomlCodeStyleSettings::class.java)
plugins/toml/core/src/main/kotlin/org/toml/ide/formatter/utils.kt
2845803047
@file:JvmName("Foo") @JvmOverloads fun <caret>foo(x: Int = 0, n: Int, y: Double = 0.0, z: String = "0") { }
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/JvmOverloadedAddNonDefault2After.kt
160308050
// WITH_STDLIB val x = sequenceOf("1").<caret>mapNotNullTo(mutableSetOf()) { it.toInt() }
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/uselessCallOnCollection/MapNotNullToOnSequence.kt
1769284420
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.run import com.intellij.execution.Location import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.LazyRunConfigurationProducer import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.Ref import com.intellij.psi.PsiElement import com.intellij.psi.util.ClassUtil import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.asJava.toLightClass import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName import org.jetbrains.kotlin.idea.MainFunctionDetector import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.util.ProjectRootsUtil import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfType import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class KotlinRunConfigurationProducer : LazyRunConfigurationProducer<KotlinRunConfiguration>() { override fun setupConfigurationFromContext( configuration: KotlinRunConfiguration, context: ConfigurationContext, sourceElement: Ref<PsiElement> ): Boolean { val location = context.location ?: return false val module = location.module?.asJvmModule() ?: return false val container = getEntryPointContainer(location) ?: return false val startClassFQName = getStartClassFqName(container) ?: return false configuration.setModule(module) configuration.runClass = startClassFQName configuration.setGeneratedName() return true } private fun getEntryPointContainer(location: Location<*>?): KtDeclarationContainer? { if (location == null) return null if (DumbService.getInstance(location.project).isDumb) return null return getEntryPointContainer(location.psiElement) } override fun isConfigurationFromContext(configuration: KotlinRunConfiguration, context: ConfigurationContext): Boolean { val entryPointContainer = getEntryPointContainer(context.location) ?: return false val startClassFQName = getStartClassFqName(entryPointContainer) ?: return false return configuration.runClass == startClassFQName && context.module?.asJvmModule() == configuration.configurationModule?.module } companion object { fun getEntryPointContainer(locationElement: PsiElement): KtDeclarationContainer? { val psiFile = locationElement.containingFile if (!(psiFile is KtFile && ProjectRootsUtil.isInProjectOrLibSource(psiFile))) return null val mainFunctionDetector = MainFunctionDetector(psiFile.languageVersionSettings) { it.resolveToDescriptorIfAny(BodyResolveMode.FULL) } var currentElement = locationElement.declarationContainer(false) while (currentElement != null) { var entryPointContainer = currentElement if (entryPointContainer is KtClass) { entryPointContainer = entryPointContainer.companionObjects.singleOrNull() } if (entryPointContainer != null && mainFunctionDetector.hasMain(entryPointContainer.declarations)) return entryPointContainer currentElement = (currentElement as PsiElement).declarationContainer(true) } return null } fun getStartClassFqName(container: KtDeclarationContainer): String? = when (container) { is KtFile -> container.javaFileFacadeFqName.asString() is KtClassOrObject -> { if (!container.isValid) { null } else if (container is KtObjectDeclaration && container.isCompanion()) { val containerClass = container.getParentOfType<KtClass>(true) containerClass?.toLightClass()?.let { ClassUtil.getJVMClassName(it) } } else { container.toLightClass()?.let { ClassUtil.getJVMClassName(it) } } } else -> null } private fun PsiElement.declarationContainer(strict: Boolean): KtDeclarationContainer? { val element = if (strict) PsiTreeUtil.getParentOfType(this, KtClassOrObject::class.java, KtFile::class.java) else PsiTreeUtil.getNonStrictParentOfType(this, KtClassOrObject::class.java, KtFile::class.java) return element } } override fun getConfigurationFactory(): ConfigurationFactory = KotlinRunConfigurationType.instance }
plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/run/KotlinRunConfigurationProducer.kt
137090845
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.refactoring.extractMethod.newImpl import com.intellij.openapi.util.Key import com.intellij.openapi.util.TextRange import com.intellij.psi.* import com.intellij.psi.util.PsiTreeUtil data class ChangedExpression(val pattern: PsiExpression, val candidate: PsiExpression) data class Duplicate(val pattern: List<PsiElement>, val candidate: List<PsiElement>, val changedExpressions: List<ChangedExpression>) class JavaDuplicatesFinder(pattern: List<PsiElement>, private val predefinedChanges: Set<PsiExpression> = emptySet()) { companion object { private val ELEMENT_IN_PHYSICAL_FILE = Key<PsiElement>("ELEMENT_IN_PHYSICAL_FILE") /** * Ensures that all [PsiMember] elements in copied [root] will be linked to [PsiMember] in the original [root] element. * These links are used to compare references between copied and original files. */ fun linkCopiedClassMembersWithOrigin(root: PsiElement) { SyntaxTraverser.psiTraverser(root).filter(PsiMember::class.java).forEach { member -> member.putCopyableUserData(ELEMENT_IN_PHYSICAL_FILE, member) } } private fun getElementInPhysicalFile(element: PsiElement): PsiElement? = element.getCopyableUserData(ELEMENT_IN_PHYSICAL_FILE) fun textRangeOf(range: List<PsiElement>) = TextRange(range.first().textRange.startOffset, range.last().textRange.endOffset) } private val pattern: List<PsiElement> = pattern.filterNot(::isNoise) fun withPredefinedChanges(predefinedChanges: Set<PsiExpression>): JavaDuplicatesFinder { return JavaDuplicatesFinder(pattern, this.predefinedChanges + predefinedChanges) } fun findDuplicates(scope: PsiElement): List<Duplicate> { val ignoredElements = HashSet<PsiElement>(pattern) val duplicates = mutableListOf<Duplicate>() val patternExpression = pattern.singleOrNull() as? PsiExpression val visitor = if (patternExpression != null) { object : JavaRecursiveElementWalkingVisitor(){ override fun visitExpression(expression: PsiExpression) { if (expression in ignoredElements) return val duplicate = createDuplicate(childrenOf(patternExpression), childrenOf(expression)) if (duplicate != null) { duplicates += duplicate.copy(pattern = listOf(patternExpression), candidate = listOf(expression)) } else { super.visitExpression(expression) } } } } else { object: JavaRecursiveElementWalkingVisitor() { override fun visitStatement(statement: PsiStatement) { if (statement in ignoredElements) return val siblings = siblingsOf(statement).take(pattern.size).toList() val duplicate = createDuplicate(pattern, siblings) if (duplicate != null) { duplicates += duplicate ignoredElements += duplicate.candidate } else { super.visitStatement(statement) } } } } scope.accept(visitor) return duplicates.filterNot(::isOvercomplicated) } private fun isNoise(it: PsiElement) = it is PsiWhiteSpace || it is PsiComment || it is PsiEmptyStatement private fun siblingsOf(element: PsiElement?): Sequence<PsiElement> { return if (element != null) { generateSequence(element) { it.nextSibling }.filterNot(::isNoise) } else { emptySequence() } } private fun childrenOf(element: PsiElement?): List<PsiElement> { return siblingsOf(element?.firstChild).toList() } fun createExpressionDuplicate(pattern: PsiExpression, candidate: PsiExpression): Duplicate? { return createDuplicate(childrenOf(pattern), childrenOf(candidate)) ?.copy(pattern = listOf(pattern), candidate = listOf(candidate)) } fun createDuplicate(pattern: List<PsiElement>, candidate: List<PsiElement>): Duplicate? { val changedExpressions = ArrayList<ChangedExpression>() if (!traverseAndCollectChanges(pattern, candidate, changedExpressions)) return null return removeInternalReferences(Duplicate(pattern, candidate, changedExpressions)) } private fun removeInternalReferences(duplicate: Duplicate): Duplicate? { val patternDeclarations = duplicate.pattern.flatMap { PsiTreeUtil.findChildrenOfType(it, PsiVariable::class.java) } val candidateDeclarations = duplicate.candidate.flatMap { PsiTreeUtil.findChildrenOfType(it, PsiVariable::class.java) } val declarationsMapping = patternDeclarations.zip(candidateDeclarations).toMap() val changedExpressions = duplicate.changedExpressions.filterNot { (pattern, candidate) -> val patternVariable = (pattern as? PsiReferenceExpression)?.resolve() val candidateVariable = (candidate as? PsiReferenceExpression)?.resolve() if (patternVariable !in declarationsMapping.keys && candidateVariable !in declarationsMapping.values) return@filterNot false if (declarationsMapping[patternVariable] != candidateVariable) return null return@filterNot true } if (ExtractMethodHelper.hasReferencesToScope(duplicate.pattern, changedExpressions.map{ change -> change.pattern }) || ExtractMethodHelper.hasReferencesToScope(duplicate.candidate, changedExpressions.map { change -> change.candidate })){ return null } return duplicate.copy(changedExpressions = changedExpressions) } fun traverseAndCollectChanges(pattern: List<PsiElement>, candidate: List<PsiElement>, changedExpressions: MutableList<ChangedExpression>): Boolean { if (candidate.size != pattern.size) return false val notEqualElements = pattern.zip(candidate).filterNot { (pattern, candidate) -> pattern !in predefinedChanges && areEquivalent(pattern, candidate) && traverseAndCollectChanges(childrenOf(pattern), childrenOf(candidate), changedExpressions) } if (notEqualElements.any { (pattern, candidate) -> ! canBeReplaced(pattern, candidate) }) return false changedExpressions += notEqualElements.map { (pattern, candidate) -> ChangedExpression(pattern as PsiExpression, candidate as PsiExpression) } return true } fun areEquivalent(pattern: PsiElement, candidate: PsiElement): Boolean { return when { pattern is PsiTypeElement && candidate is PsiTypeElement -> canBeReplaced(pattern.type, candidate.type) pattern is PsiJavaCodeReferenceElement && candidate is PsiJavaCodeReferenceElement -> areElementsEquivalent(pattern.resolve(), candidate.resolve()) pattern is PsiLiteralExpression && candidate is PsiLiteralExpression -> pattern.text == candidate.text pattern.node?.elementType == candidate.node?.elementType -> true else -> false } } private fun areElementsEquivalent(pattern: PsiElement?, candidate: PsiElement?): Boolean { val manager = pattern?.manager ?: return false return manager.areElementsEquivalent(getElementInPhysicalFile(pattern) ?: pattern, candidate) } private fun canBeReplaced(pattern: PsiElement, candidate: PsiElement): Boolean { return when { pattern.parent is PsiExpressionStatement -> false pattern is PsiReferenceExpression && pattern.parent is PsiCall -> false pattern is PsiExpression && candidate is PsiExpression -> pattern.type != PsiType.VOID && canBeReplaced(pattern.type, candidate.type) else -> false } } private fun canBeReplaced(pattern: PsiType?, candidate: PsiType?): Boolean { if (pattern == null || candidate == null) return false if (pattern is PsiDiamondType && candidate is PsiDiamondType) { val patternTypes = getInferredTypes(pattern) ?: return false val candidateTypes = getInferredTypes(candidate) ?: return false if (patternTypes.size != candidateTypes.size) return false return patternTypes.indices.all { i -> canBeReplaced(patternTypes[i], candidateTypes[i]) } } return pattern.isAssignableFrom(candidate) } private fun getInferredTypes(diamondType: PsiDiamondType): List<PsiType>? { return diamondType.resolveInferredTypes()?.takeIf { resolveResult -> !resolveResult.failedToInfer() }?.inferredTypes } private fun isOvercomplicated(duplicate: Duplicate): Boolean { val singleChangedExpression = duplicate.changedExpressions.singleOrNull()?.pattern ?: return false val singleDeclaration = duplicate.pattern.singleOrNull() as? PsiDeclarationStatement val variable = singleDeclaration?.declaredElements?.singleOrNull() as? PsiVariable return variable?.initializer == singleChangedExpression } }
java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/JavaDuplicatesFinder.kt
845699175
package com.psenchanka.comant.dao import java.io.Serializable interface AbstractDao<T, Id : Serializable> { fun save(t: T) fun findAll(): List<T> fun findById(id: Id): T? fun update(t: T) }
comant-site/src/main/kotlin/com/psenchanka/comant/dao/AbstractDao.kt
3607888671
class Exponent { private val doubles = doubleArrayOf( 5e5, +5e5, -5e5, 5e+5, 5e-5, 5E5, +5E5, -5E5, 5E+5, 5E-5, 2.5e5, +2.5e5, -2.5e5, 2.5e+5, 2.5e-5, 2.5E5, +2.5E5, -2.5E5, 2.5E+5, 2.5E-5, 5e5, 5e5, 5e5, 5e5, 5e-6, 7e+8, 9e-1, 2e+3, 4e5, 6e7 ) }
plugins/kotlin/j2k/new/tests/testData/newJ2k/literalExpression/exponentDouble.kt
61754326
val fo ="<caret>"
plugins/kotlin/idea/tests/testData/copyPaste/plainTextLiteral/NoSpecialCharsToSingleQuote.kt
4153161905
package chat.willow.kale.irc.message.extension.batch import chat.willow.kale.core.message.IrcMessage import chat.willow.kale.irc.prefix.prefix import org.junit.Assert.assertEquals import org.junit.Assert.assertNull import org.junit.Before import org.junit.Test class BatchEndMessageTests { private lateinit var messageParser: BatchMessage.End.Message.Parser private lateinit var messageSerialiser: BatchMessage.End.Message.Serialiser @Before fun setUp() { messageParser = BatchMessage.End.Message.Parser messageSerialiser= BatchMessage.End.Message.Serialiser } @Test fun test_parse_ReferenceWithCorrectToken() { val message = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("-batch1"))) assertEquals(BatchMessage.End.Message(source = prefix("someone"), reference = "batch1"), message) } @Test fun test_parse_MissingMinusCharacter_ReturnsNull() { val message = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("batch1"))) assertNull(message) } @Test fun test_parse_TooFewParameters_ReturnsNull() { val messageOne = messageParser.parse(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf())) assertNull(messageOne) } @Test fun test_parse_NoPrefix_ReturnsNull() { val messageOne = messageParser.parse(IrcMessage(command = "BATCH", prefix = null, parameters = listOf("-batch1"))) assertNull(messageOne) } @Test fun test_serialise_WithReference() { val message = messageSerialiser.serialise(BatchMessage.End.Message(source = prefix("someone"), reference = "reference")) assertEquals(IrcMessage(command = "BATCH", prefix = "someone", parameters = listOf("-reference")), message) } }
src/test/kotlin/chat/willow/kale/irc/message/extension/batch/BatchEndMessageTests.kt
1700968203
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.gradle.plugins import java.io.File import javax.xml.parsers.DocumentBuilderFactory import org.gradle.api.GradleException import org.w3c.dom.Element import org.w3c.dom.NodeList data class Project( val name: String, val group: String = "com.example", val version: String = "undefined", val latestReleasedVersion: String? = null, val projectDependencies: Set<Project> = setOf(), val externalDependencies: Set<Artifact> = setOf(), val releaseWith: Project? = null, val customizePom: String? = null, val publishJavadoc: Boolean = false, val libraryType: LibraryType = LibraryType.ANDROID ) { fun generateBuildFile(): String { return """ plugins { id 'firebase-${if (libraryType == LibraryType.JAVA) "java-" else ""}library' } group = '$group' version = '$version' ${if (latestReleasedVersion != null) "ext.latestReleasedVersion = $latestReleasedVersion" else ""} firebaseLibrary { ${if (releaseWith != null) "releaseWith project(':${releaseWith.name}')" else ""} ${if (customizePom != null) "customizePom {$customizePom}" else ""} ${"publishJavadoc = $publishJavadoc"} } ${if (libraryType == LibraryType.ANDROID) "android.compileSdkVersion = 26" else ""} dependencies { ${projectDependencies.joinToString("\n") { "implementation project(':${it.name}')" }} ${externalDependencies.joinToString("\n") { "implementation '${it.simpleDepString}'" }} } """ } fun getPublishedPom(rootDirectory: String): Pom? { val v = releaseWith?.version ?: version return File(rootDirectory) .walk() .asSequence() .filter { it.isFile } .filter { it.path.matches(Regex(".*/${group.replace('.', '/')}/$name/$v.*/.*\\.pom$")) } .map(Pom::parse) .firstOrNull() } } data class License(val name: String, val url: String) enum class Type { JAR, AAR } data class Artifact( val groupId: String, val artifactId: String, val version: String, val type: Type = Type.JAR, val scope: String = "" ) { val simpleDepString: String get() = "$groupId:$artifactId:$version" } data class Pom( val artifact: Artifact, val license: License = License( name = "The Apache Software License, Version 2.0", url = "http://www.apache.org/licenses/LICENSE-2.0.txt" ), val dependencies: List<Artifact> = listOf() ) { companion object { fun parse(file: File): Pom { val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file) val childNodes = document.documentElement.childNodes var groupId: String? = null var artifactId: String? = null var version: String? = null var type = Type.JAR var license: License? = null var deps: List<Artifact> = listOf() for (i in 0 until childNodes.length) { val child = childNodes.item(i) if (child !is Element) { continue } when (child.tagName) { "groupId" -> groupId = child.textContent.trim() "artifactId" -> artifactId = child.textContent.trim() "version" -> version = child.textContent.trim() "packaging" -> type = Type.valueOf(child.textContent.trim().toUpperCase()) "licenses" -> license = parseLicense(child.getElementsByTagName("license")) "dependencies" -> deps = parseDeps(child.getElementsByTagName("dependency")) } } if (groupId == null) { throw GradleException("'<groupId>' missing in pom") } if (artifactId == null) { throw GradleException("'<artifactId>' missing in pom") } if (version == null) { throw GradleException("'<version>' missing in pom") } if (license == null) { throw GradleException("'<license>' missing in pom") } return Pom(Artifact(groupId, artifactId, version, type), license, deps) } private fun parseDeps(nodes: NodeList): List<Artifact> { val deps = mutableListOf<Artifact>() for (i in 0 until nodes.length) { val child = nodes.item(i) if (child !is Element) { continue } deps.add(parseDep(child)) } return deps } private fun parseDep(dependencies: Element): Artifact { var groupId: String? = null var artifactId: String? = null var version: String? = null var type = Type.JAR var scope: String? = null val nodes = dependencies.childNodes for (i in 0 until nodes.length) { val child = nodes.item(i) if (child !is Element) { continue } when (child.tagName) { "groupId" -> groupId = child.textContent.trim() "artifactId" -> artifactId = child.textContent.trim() "version" -> version = child.textContent.trim() "type" -> type = Type.valueOf(child.textContent.trim().toUpperCase()) "scope" -> scope = child.textContent.trim() } } if (groupId == null) { throw GradleException("'<groupId>' missing in pom") } if (artifactId == null) { throw GradleException("'<artifactId>' missing in pom") } if (version == null) { throw GradleException("'<version>' missing in pom") } if (scope == null) { throw GradleException("'<scope>' missing in pom") } return Artifact(groupId, artifactId, version, type, scope) } private fun parseLicense(nodes: NodeList): License? { if (nodes.length == 0) { return null } val license = nodes.item(0) as Element val urlElements = license.getElementsByTagName("url") val url = if (urlElements.length == 0) "" else urlElements.item(0).textContent.trim() val nameElements = license.getElementsByTagName("name") val name = if (nameElements.length == 0) "" else nameElements.item(0).textContent.trim() return License(name = name, url = url) } } }
buildSrc/src/test/kotlin/com/google/firebase/gradle/plugins/publishing.kt
2199124917
package com.example.test3 import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DuplicatedApkNameTests { @Test fun test0() = Unit @Test fun test1() = Unit @Test fun test2() = Unit }
test_projects/android/dir3/testModule/src/androidTest/java/com/example/test3/DuplicatedApkNameTests.kt
1962871617
package com.antwerkz.gridfs import com.mongodb.MongoClient import com.mongodb.client.MongoDatabase import com.mongodb.client.gridfs.GridFSBucket import com.mongodb.client.gridfs.GridFSBuckets import java.nio.file.FileStore import java.nio.file.FileSystem import java.nio.file.Path import java.nio.file.PathMatcher import java.nio.file.WatchService import java.nio.file.attribute.UserPrincipalLookupService import java.nio.file.spi.FileSystemProvider class GridFSFileSystem(private val provider: GridFSFileSystemProvider, mongoClient: MongoClient, dbName: String?, bucketName: String) : FileSystem() { private var open = true val database: MongoDatabase val client: MongoClient val bucketName: String val bucket: GridFSBucket init { client = mongoClient database = client.getDatabase(dbName) this.bucketName = bucketName bucket = GridFSBuckets.create(database, bucketName) } override fun getSeparator(): String { return "/" } override fun newWatchService(): WatchService? { throw UnsupportedOperationException() } override fun supportedFileAttributeViews(): MutableSet<String>? { throw UnsupportedOperationException() } override fun isReadOnly(): Boolean { return false } override fun getFileStores(): MutableIterable<FileStore>? { throw UnsupportedOperationException() } override fun getPath(first: String, vararg more: String): GridFSPath { return if (more.size == 0) GridFSPath(this, first) else GridFSPath(this, listOf(first) + more.asList()) } override fun provider(): FileSystemProvider { return provider } override fun isOpen(): Boolean { return open } override fun getUserPrincipalLookupService(): UserPrincipalLookupService? { throw UnsupportedOperationException() } override fun close() { open = false client.close() } override fun getPathMatcher(syntaxAndPattern: String?): PathMatcher? { throw UnsupportedOperationException() } override fun getRootDirectories(): MutableIterable<Path>? { throw UnsupportedOperationException() } override fun equals(other: Any?): Boolean{ if (this === other) return true if (other?.javaClass != javaClass) return false other as GridFSFileSystem if (database != other.database) return false if (bucketName != other.bucketName) return false return true } override fun hashCode(): Int{ var result = database.hashCode() result += 31 * result + bucketName.hashCode() return result } }
core/src/main/kotlin/com/antwerkz/gridfs/GridFSFileSystem.kt
873136252
package com.cout970.modeler.gui.leguicomp import com.cout970.glutilities.device.Keyboard import org.liquidengine.legui.component.TextArea import org.liquidengine.legui.component.event.textinput.TextInputContentChangeEvent import org.liquidengine.legui.event.FocusEvent import org.liquidengine.legui.event.KeyEvent class MultilineStringInput( text: String, posX: Float = 0f, posY: Float = 0f, sizeX: Float = 80f, sizeY: Float = 24f ) : TextArea(posX, posY, sizeX, sizeY) { var onLoseFocus: (() -> Unit)? = null var onEnterPress: (() -> Unit)? = null var onTextChange: ((TextInputContentChangeEvent<*>) -> Unit)? = null init { textState.text = text defaultTextColor() classes("multiline_input") listenerMap.addListener(FocusEvent::class.java) { if (!it.isFocused) { onLoseFocus?.invoke() } } listenerMap.addListener(KeyEvent::class.java) { if (it.key == Keyboard.KEY_ENTER) { onEnterPress?.invoke() } } listenerMap.addListener(TextInputContentChangeEvent::class.java) { onTextChange?.invoke(it) } } }
src/main/kotlin/com/cout970/modeler/gui/leguicomp/MultilineStringInput.kt
3164118815
package org.droidplanner.android.fragments.widget.telemetry import android.content.* import android.location.Location import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import android.widget.Toast import com.o3dr.services.android.lib.drone.attribute.AttributeEvent import com.o3dr.services.android.lib.drone.attribute.AttributeType import com.o3dr.services.android.lib.drone.property.Gps import org.droidplanner.android.R import org.droidplanner.android.fragments.widget.TowerWidget import org.droidplanner.android.fragments.widget.TowerWidgets /** * Created by Fredia Huya-Kouadio on 9/20/15. */ public class MiniWidgetGeoInfo : TowerWidget() { companion object { private val filter = initFilter() private fun initFilter(): IntentFilter { val temp = IntentFilter() temp.addAction(AttributeEvent.GPS_POSITION) temp.addAction(AttributeEvent.HOME_UPDATED) return temp } } private val receiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { when (intent.action) { AttributeEvent.GPS_POSITION, AttributeEvent.HOME_UPDATED -> onPositionUpdate() } } } private var latitude: TextView? = null private var longitude: TextView? = null override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater?.inflate(R.layout.fragment_mini_widget_geo_info, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?){ super.onViewCreated(view, savedInstanceState) latitude = view.findViewById(R.id.latitude_telem) as TextView? longitude = view.findViewById(R.id.longitude_telem) as TextView? val clipboardMgr = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val container = view.findViewById(R.id.mini_widget_geo_info_layout) container?.setOnClickListener { val drone = drone if(drone.isConnected) { val droneGps = drone.getAttribute<Gps>(AttributeType.GPS) if(droneGps.isValid) { //Copy the lat long to the clipboard. val latLongText = "${droneGps.position.latitude}, ${droneGps.position.longitude}" val clipData = ClipData.newPlainText("Vehicle Lat/Long", latLongText) clipboardMgr.primaryClip = clipData Toast.makeText(context, "Copied lat/long data", Toast.LENGTH_SHORT).show() } } } } override fun getWidgetType() = TowerWidgets.GEO_INFO override fun onApiConnected() { onPositionUpdate() broadcastManager.registerReceiver(receiver, filter) } override fun onApiDisconnected() { broadcastManager.unregisterReceiver(receiver) } private fun onPositionUpdate() { if (!isAdded) return val drone = drone val droneGps = drone.getAttribute<Gps>(AttributeType.GPS) ?: return if (droneGps.isValid) { val latitudeValue = droneGps.position.latitude val longitudeValue = droneGps.position.longitude latitude?.text = getString(R.string.latitude_telem, Location.convert(latitudeValue, Location.FORMAT_DEGREES).toString()) longitude?.text = getString(R.string.longitude_telem, Location.convert(longitudeValue, Location.FORMAT_DEGREES).toString()) } } }
Research/Tower-develop/Tower-develop/Android/src/org/droidplanner/android/fragments/widget/telemetry/MiniWidgetGeoInfo.kt
412803284
package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import info.nightscout.androidaps.R import info.nightscout.androidaps.plugins.general.automation.elements.InputString import info.nightscout.androidaps.queue.Callback import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.anyString import org.mockito.ArgumentMatchers.eq import org.mockito.Mockito import org.mockito.Mockito.`when` import org.powermock.modules.junit4.PowerMockRunner @RunWith(PowerMockRunner::class) class ActionSendSMSTest : ActionsTestBase() { private lateinit var sut: ActionSendSMS @Before fun setup() { `when`(resourceHelper.gs(eq(R.string.sendsmsactionlabel), anyString())).thenReturn("Send SMS: %s") `when`(resourceHelper.gs(R.string.sendsmsactiondescription)).thenReturn("Send SMS to all numbers") sut = ActionSendSMS(injector) } @Test fun friendlyNameTest() { Assert.assertEquals(R.string.sendsmsactiondescription, sut.friendlyName()) } @Test fun shortDescriptionTest() { Assert.assertEquals("Send SMS: %s", sut.shortDescription()) } @Test fun iconTest() { Assert.assertEquals(R.drawable.ic_notifications, sut.icon()) } @Test fun doActionTest() { `when`(smsCommunicatorPlugin.sendNotificationToAllNumbers(anyString())).thenReturn(true) sut.text = InputString(injector, "Asd") sut.doAction(object : Callback() { override fun run() { Assert.assertTrue(result.success) } }) } @Test fun hasDialogTest() { Assert.assertTrue(sut.hasDialog()) } @Test fun toJSONTest() { sut.text = InputString(injector, "Asd") Assert.assertEquals("{\"data\":{\"text\":\"Asd\"},\"type\":\"info.nightscout.androidaps.plugins.general.automation.actions.ActionSendSMS\"}", sut.toJSON()) } @Test fun fromJSONTest() { sut.fromJSON("{\"text\":\"Asd\"}") Assert.assertEquals("Asd", sut.text.value) } }
app/src/test/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMSTest.kt
4158380698
class A<X> { fun <Y, <caret>Z> foo() { } }
plugins/kotlin/idea/tests/testData/refactoring/safeDelete/deleteTypeParameter/kotlinTypeParameterWithJava/subst5.kt
3226575249
class Generic1<T> class Generic2<T1, T2> fun foo(): G<caret> // EXIST: { lookupString: "Generic1", itemText: "Generic1", tailText: "<T> (<root>)" } // EXIST: { lookupString: "Generic2", itemText: "Generic2", tailText: "<T1, T2> (<root>)" }
plugins/kotlin/completion/tests/testData/basic/common/GenericKotlinClass.kt
618628947
// WITH_RUNTIME fun testIf(x: Any) { <caret>if (x is String) { println(x) for (c in x) { if (c == ' ') break // do not change } } else { println(x) } }
plugins/kotlin/idea/tests/testData/intentions/branched/ifWhen/ifToWhen/withInternalLoopOnly.kt
4132205581
package org.schabi.newpipe.player.gesture import android.util.Log import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import android.widget.ProgressBar import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.content.res.AppCompatResources import androidx.core.math.MathUtils import androidx.core.view.isVisible import org.schabi.newpipe.MainActivity import org.schabi.newpipe.R import org.schabi.newpipe.ktx.AnimationType import org.schabi.newpipe.ktx.animate import org.schabi.newpipe.player.Player import org.schabi.newpipe.player.helper.AudioReactor import org.schabi.newpipe.player.helper.PlayerHelper import org.schabi.newpipe.player.ui.MainPlayerUi import org.schabi.newpipe.util.ThemeHelper.getAndroidDimenPx import kotlin.math.abs /** * GestureListener for the player * * While [BasePlayerGestureListener] contains the logic behind the single gestures * this class focuses on the visual aspect like hiding and showing the controls or changing * volume/brightness during scrolling for specific events. */ class MainPlayerGestureListener( private val playerUi: MainPlayerUi ) : BasePlayerGestureListener(playerUi), OnTouchListener { private var isMoving = false override fun onTouch(v: View, event: MotionEvent): Boolean { super.onTouch(v, event) if (event.action == MotionEvent.ACTION_UP && isMoving) { isMoving = false onScrollEnd(event) } return when (event.action) { MotionEvent.ACTION_DOWN, MotionEvent.ACTION_MOVE -> { v.parent?.requestDisallowInterceptTouchEvent(playerUi.isFullscreen) true } MotionEvent.ACTION_UP -> { v.parent?.requestDisallowInterceptTouchEvent(false) false } else -> true } } override fun onSingleTapConfirmed(e: MotionEvent): Boolean { if (DEBUG) Log.d(TAG, "onSingleTapConfirmed() called with: e = [$e]") if (isDoubleTapping) return true super.onSingleTapConfirmed(e) if (player.currentState != Player.STATE_BLOCKED) onSingleTap() return true } private fun onScrollVolume(distanceY: Float) { val bar: ProgressBar = binding.volumeProgressBar val audioReactor: AudioReactor = player.audioReactor // If we just started sliding, change the progress bar to match the system volume if (!binding.volumeRelativeLayout.isVisible) { val volumePercent: Float = audioReactor.volume / audioReactor.maxVolume.toFloat() bar.progress = (volumePercent * bar.max).toInt() } // Update progress bar binding.volumeProgressBar.incrementProgressBy(distanceY.toInt()) // Update volume val currentProgressPercent: Float = bar.progress / bar.max.toFloat() val currentVolume = (audioReactor.maxVolume * currentProgressPercent).toInt() audioReactor.volume = currentVolume if (DEBUG) { Log.d(TAG, "onScroll().volumeControl, currentVolume = $currentVolume") } // Update player center image binding.volumeImageView.setImageDrawable( AppCompatResources.getDrawable( player.context, when { currentProgressPercent <= 0 -> R.drawable.ic_volume_off currentProgressPercent < 0.25 -> R.drawable.ic_volume_mute currentProgressPercent < 0.75 -> R.drawable.ic_volume_down else -> R.drawable.ic_volume_up } ) ) // Make sure the correct layout is visible if (!binding.volumeRelativeLayout.isVisible) { binding.volumeRelativeLayout.animate(true, 200, AnimationType.SCALE_AND_ALPHA) } binding.brightnessRelativeLayout.isVisible = false } private fun onScrollBrightness(distanceY: Float) { val parent: AppCompatActivity = playerUi.parentActivity.orElse(null) ?: return val window = parent.window val layoutParams = window.attributes val bar: ProgressBar = binding.brightnessProgressBar // Update progress bar val oldBrightness = layoutParams.screenBrightness bar.progress = (bar.max * MathUtils.clamp(oldBrightness, 0f, 1f)).toInt() bar.incrementProgressBy(distanceY.toInt()) // Update brightness val currentProgressPercent = bar.progress.toFloat() / bar.max layoutParams.screenBrightness = currentProgressPercent window.attributes = layoutParams // Save current brightness level PlayerHelper.setScreenBrightness(parent, currentProgressPercent) if (DEBUG) { Log.d( TAG, "onScroll().brightnessControl, " + "currentBrightness = " + currentProgressPercent ) } // Update player center image binding.brightnessImageView.setImageDrawable( AppCompatResources.getDrawable( player.context, when { currentProgressPercent < 0.25 -> R.drawable.ic_brightness_low currentProgressPercent < 0.75 -> R.drawable.ic_brightness_medium else -> R.drawable.ic_brightness_high } ) ) // Make sure the correct layout is visible if (!binding.brightnessRelativeLayout.isVisible) { binding.brightnessRelativeLayout.animate(true, 200, AnimationType.SCALE_AND_ALPHA) } binding.volumeRelativeLayout.isVisible = false } override fun onScrollEnd(event: MotionEvent) { super.onScrollEnd(event) if (binding.volumeRelativeLayout.isVisible) { binding.volumeRelativeLayout.animate(false, 200, AnimationType.SCALE_AND_ALPHA, 200) } if (binding.brightnessRelativeLayout.isVisible) { binding.brightnessRelativeLayout.animate(false, 200, AnimationType.SCALE_AND_ALPHA, 200) } } override fun onScroll( initialEvent: MotionEvent, movingEvent: MotionEvent, distanceX: Float, distanceY: Float ): Boolean { if (!playerUi.isFullscreen) { return false } // Calculate heights of status and navigation bars val statusBarHeight = getAndroidDimenPx(player.context, "status_bar_height") val navigationBarHeight = getAndroidDimenPx(player.context, "navigation_bar_height") // Do not handle this event if initially it started from status or navigation bars val isTouchingStatusBar = initialEvent.y < statusBarHeight val isTouchingNavigationBar = initialEvent.y > (binding.root.height - navigationBarHeight) if (isTouchingStatusBar || isTouchingNavigationBar) { return false } val insideThreshold = abs(movingEvent.y - initialEvent.y) <= MOVEMENT_THRESHOLD if ( !isMoving && (insideThreshold || abs(distanceX) > abs(distanceY)) || player.currentState == Player.STATE_COMPLETED ) { return false } isMoving = true // -- Brightness and Volume control -- val isBrightnessGestureEnabled = PlayerHelper.isBrightnessGestureEnabled(player.context) val isVolumeGestureEnabled = PlayerHelper.isVolumeGestureEnabled(player.context) if (isBrightnessGestureEnabled && isVolumeGestureEnabled) { if (getDisplayHalfPortion(initialEvent) === DisplayPortion.LEFT_HALF) { onScrollBrightness(distanceY) } else /* DisplayPortion.RIGHT_HALF */ { onScrollVolume(distanceY) } } else if (isBrightnessGestureEnabled) { onScrollBrightness(distanceY) } else if (isVolumeGestureEnabled) { onScrollVolume(distanceY) } return true } override fun getDisplayPortion(e: MotionEvent): DisplayPortion { return when { e.x < binding.root.width / 3.0 -> DisplayPortion.LEFT e.x > binding.root.width * 2.0 / 3.0 -> DisplayPortion.RIGHT else -> DisplayPortion.MIDDLE } } override fun getDisplayHalfPortion(e: MotionEvent): DisplayPortion { return when { e.x < binding.root.width / 2.0 -> DisplayPortion.LEFT_HALF else -> DisplayPortion.RIGHT_HALF } } companion object { private val TAG = MainPlayerGestureListener::class.java.simpleName private val DEBUG = MainActivity.DEBUG private const val MOVEMENT_THRESHOLD = 40 } }
app/src/main/java/org/schabi/newpipe/player/gesture/MainPlayerGestureListener.kt
2040043122