path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
utbot-js/src/main/kotlin/service/TernService.kt
|
UnitTestBot
| 480,810,501 | false | null |
package service
import com.google.javascript.rhino.Node
import framework.api.js.JsClassId
import framework.api.js.JsMultipleClassId
import framework.api.js.util.jsUndefinedClassId
import java.io.File
import org.json.JSONException
import org.json.JSONObject
import parser.JsParserUtils
import parser.JsParserUtils.getAbstractFunctionName
import parser.JsParserUtils.getAbstractFunctionParams
import parser.JsParserUtils.getClassName
import parser.JsParserUtils.getConstructor
import providers.imports.IImportsProvider
import utils.JsCmdExec
import utils.constructClass
import utils.data.MethodTypes
/**
* Installs and sets up scripts for running Tern.js type guesser.
*/
class TernService(context: ServiceContext) : ContextOwner by context {
private val importProvider = IImportsProvider.providerByPackageJson(packageJson, context)
private fun ternScriptCode() = """
${generateImportsSection()}
var condenseDir = "";
function runTest(options) {
var server = new tern.Server({
projectDir: util.resolve(condenseDir),
defs: [util.ecmascript],
plugins: options.plugins,
getFile: function(name) {
return fs.readFileSync(path.resolve(condenseDir, name), "utf8");
}
});
options.load.forEach(function(file) {
server.addFile(file)
});
server.flush(function() {
var origins = options.include || options.load;
var condensed = condense.condense(origins, null, {sortOutput: true});
var out = JSON.stringify(condensed, null, 2);
console.log(out)
});
}
function test(options) {
options = {load: options};
runTest(options);
}
test(["${filePathToInference.joinToString(separator = "\", \"")}"])
"""
init {
with(context) {
setupTernEnv("$projectPath/$utbotDir")
runTypeInferencer()
}
}
private lateinit var json: JSONObject
private fun generateImportsSection(): String = importProvider.ternScriptImports
private fun setupTernEnv(path: String) {
File(path).mkdirs()
val ternScriptFile = File("$path/ternScript.js")
ternScriptFile.writeText(ternScriptCode())
}
private fun runTypeInferencer() {
val (inputText, _) = JsCmdExec.runCommand(
dir = "$projectPath/$utbotDir/",
shouldWait = true,
timeout = 20,
cmd = arrayOf("\"${settings.pathToNode}\"", "\"${projectPath}/$utbotDir/ternScript.js\""),
)
json = try {
JSONObject(inputText.replaceAfterLast("}", ""))
} catch (_: Throwable) {
JSONObject()
}
}
fun processConstructor(classNode: Node): List<JsClassId> {
return try {
val classJson = json.getJSONObject(classNode.getClassName())
val constructorFunc = classJson.getString("!type")
.filterNot { setOf(' ', '+').contains(it) }
extractParameters(constructorFunc)
} catch (e: JSONException) {
classNode.getConstructor()?.getAbstractFunctionParams()?.map { jsUndefinedClassId } ?: emptyList()
}
}
private fun extractParameters(line: String): List<JsClassId> {
val parametersRegex = Regex("fn[(](.+)[)]")
return parametersRegex.find(line)?.groups?.get(1)?.let { matchResult ->
val value = matchResult.value
val paramGroupList = Regex("(\\w+:\\[\\w+(,\\w+)*]|\\w+:\\w+)|\\w+:\\?").findAll(value).toList()
paramGroupList.map { paramGroup ->
val paramReg = Regex("\\w*:(.*)")
try {
val param = paramGroup.groups[0]!!.value
makeClassId(
paramReg.find(param)?.groups?.get(1)?.value
?: throw IllegalStateException()
)
} catch (t: Throwable) {
jsUndefinedClassId
}
}
} ?: emptyList()
}
private fun extractReturnType(line: String): JsClassId {
val returnTypeRegex = Regex("->(.*)")
return returnTypeRegex.find(line)?.groups?.get(1)?.let { matchResult ->
val value = matchResult.value
try {
makeClassId(value)
} catch (t: Throwable) {
jsUndefinedClassId
}
} ?: jsUndefinedClassId
}
fun processMethod(className: String?, funcNode: Node, isToplevel: Boolean = false): MethodTypes {
// Js doesn't support nested classes, so if the function is not top-level, then we can check for only one parent class.
try {
var scope = className?.let {
if (!isToplevel) json.getJSONObject(it) else json
} ?: json
try {
scope.getJSONObject(funcNode.getAbstractFunctionName())
} catch (e: JSONException) {
scope = scope.getJSONObject("prototype")
}
val methodJson = scope.getJSONObject(funcNode.getAbstractFunctionName())
val typesString = methodJson.getString("!type")
.filterNot { setOf(' ', '+').contains(it) }
val parametersList = lazy { extractParameters(typesString) }
val returnType = lazy { extractReturnType(typesString) }
return MethodTypes(parametersList, returnType)
} catch (e: Exception) {
return MethodTypes(
lazy { funcNode.getAbstractFunctionParams().map { jsUndefinedClassId } },
lazy { jsUndefinedClassId }
)
}
}
private fun makeClassId(name: String): JsClassId {
val classId = when {
name == "?" || name.toIntOrNull() != null || name.contains('!') -> jsUndefinedClassId
Regex("\\[(.*)]").matches(name) -> {
val arrType = Regex("\\[(.*)]").find(name)?.groups?.get(1)?.value?.substringBefore(",")
?: throw IllegalStateException()
JsClassId(
jsName = "Array",
elementClassId = makeClassId(arrType)
)
}
name.contains('|') -> JsMultipleClassId(name)
else -> JsClassId(name)
}
return try {
val classNode = JsParserUtils.searchForClassDecl(
className = name,
parsedFile = parsedFile,
strict = true,
)
classNode?.let {
JsClassId(name).constructClass(this, it)
} ?: classId
} catch (e: Exception) {
classId
}
}
}
| 398 | null |
32
| 91 |
abb62682c70d7d2ecc4ad610851d304f7ad716e4
| 6,643 |
UTBotJava
|
Apache License 2.0
|
app/src/main/java/com/jinglebroda/looktocook/di/module/DataModules.kt
|
jingleBroda
| 629,142,633 | false | null |
package com.jinglebroda.looktocook.di.module
import com.jinglebroda.looktocook.di.module.nestedDataModules.RepositoryModule
import com.jinglebroda.looktocook.di.module.nestedDataModules.RetrofitModule
import dagger.Module
@Module(
includes = [
RetrofitModule::class,
RepositoryModule::class,
]
)
class DataModules
| 0 |
Kotlin
|
0
| 0 |
acfa4d2443684c002b197ddf524a7afed1afe37c
| 339 |
Look_to_cook
|
MIT License
|
v201/src/main/kotlin/com/monta/library/ocpp/v201/blocks/remotecontrol/TriggerMessage.kt
|
monta-app
| 852,955,703 | false |
{"Kotlin": 565115}
|
package com.monta.library.ocpp.v201.blocks.remotecontrol
import com.monta.library.ocpp.common.profile.Feature
import com.monta.library.ocpp.common.profile.OcppConfirmation
import com.monta.library.ocpp.common.profile.OcppRequest
import com.monta.library.ocpp.v201.common.CustomData
import com.monta.library.ocpp.v201.common.EVSE
import com.monta.library.ocpp.v201.common.StatusInfo
/**
* F06 Trigger Message
*/
object TriggerMessageFeature : Feature {
override val name: String = "TriggerMessage"
override val requestType: Class<out OcppRequest> = TriggerMessageRequest::class.java
override val confirmationType: Class<out OcppConfirmation> = TriggerMessageResponse::class.java
}
data class TriggerMessageRequest(
val requestedMessage: RequestedMessage,
val evse: EVSE? = null,
val customData: CustomData? = null
) : OcppRequest {
enum class RequestedMessage {
BootNotification,
LogStatusNotification,
FirmwareStatusNotification,
Heartbeat,
MeterValues,
SignChargingStationCertificate,
SignV2GCertificate,
StatusNotification,
TransactionEvent,
SignCombinedCertificate,
PublishFirmwareStatusNotification
}
}
data class TriggerMessageResponse(
val status: Status,
val statusInfo: StatusInfo? = null,
val customData: CustomData? = null
) : OcppConfirmation {
enum class Status {
Accepted,
Rejected,
NotImplemented
}
}
| 1 |
Kotlin
|
0
| 0 |
cee4e7dd2f624c925918aaa7ecd2a971b75fd614
| 1,485 |
library-ocpp
|
Apache License 2.0
|
app/src/main/java/com/example/meli/feature/items/ui/adapter/ItemAdapter.kt
|
081292
| 709,587,771 | false |
{"Kotlin": 34898}
|
package com.example.meli.feature.items.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.navigation.NavController
import androidx.recyclerview.widget.RecyclerView
import com.example.meli.R
import com.example.meli.feature.items.ui.ItemUIModel
class ItemAdapter(private val itemUIModelList: List<ItemUIModel>, private val findNavController: NavController) : RecyclerView.Adapter<ItemViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
return ItemViewHolder(layoutInflater.inflate(R.layout.item_item, parent, false), findNavController)
}
override fun getItemCount(): Int = itemUIModelList.size
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = itemUIModelList[position]
holder.render(item)
}
}
| 0 |
Kotlin
|
0
| 0 |
c78e4be173219bd9d9bead68b58ef003d1243a62
| 927 |
MeLi
|
Apache License 2.0
|
app/src/main/java/com/dm/bomber/services/core/Service.kt
|
dmitrijkotov634
| 385,968,201 | false |
{"Kotlin": 526757, "Java": 3148}
|
package com.dm.bomber.services.core
import okhttp3.OkHttpClient
import kotlin.random.Random
abstract class Service(vararg val countryCodes: Int) {
abstract fun run(client: OkHttpClient, callback: Callback, phone: Phone)
companion object {
private fun randomString(min: Char, max: Char, length: Int): String =
(1..length)
.map { Random.nextInt((max.code - min.code + 1) + min.code).toChar() }
.joinToString("")
val russianName: String
get() = randomString('а', 'я', 5)
val userName: String
get() = randomString('a', 'z', 12)
val email: String
get() = userName + "@" + arrayOf("gmail.com", "mail.ru", "yandex.ru")[Random.nextInt(3)]
}
}
| 6 |
Kotlin
|
63
| 379 |
e39f4520dbc1d1dacecc333863a2d75a6d51b547
| 766 |
android-bomber
|
MIT License
|
shared/src/commonMain/kotlin/io/ballerine/kmp/example/Platform.kt
|
ballerine-io
| 515,267,367 | false |
{"Kotlin": 14086, "Swift": 6149, "Ruby": 1783}
|
package io.ballerine.kmp.example
expect class Platform() {
val platform: String
}
| 0 |
Kotlin
|
0
| 4 |
a231844d6e8b7f44bf0f5e54c022fbe60a24336f
| 86 |
ballerine-kmp-example
|
Apache License 2.0
|
processor/src/main/kotlin/com/dbflow5/processor/definition/column/ReferenceColumnDefinition.kt
|
MEiDIK
| 197,241,524 | false |
{"Git Config": 1, "Gradle": 18, "Markdown": 29, "INI": 12, "Proguard": 5, "Shell": 1, "Text": 1, "Ignore List": 8, "EditorConfig": 1, "Kotlin": 315, "JSON": 1, "XML": 14, "Java Properties": 1, "Java": 5, "SQL": 1}
|
package com.dbflow5.processor.definition.column
import com.grosner.kpoet.S
import com.grosner.kpoet.`return`
import com.grosner.kpoet.case
import com.dbflow5.annotation.ColumnMap
import com.dbflow5.annotation.ConflictAction
import com.dbflow5.annotation.ForeignKey
import com.dbflow5.annotation.ForeignKeyAction
import com.dbflow5.annotation.ForeignKeyReference
import com.dbflow5.annotation.QueryModel
import com.dbflow5.annotation.Table
import com.dbflow5.processor.ColumnValidator
import com.dbflow5.processor.ProcessorManager
import com.dbflow5.processor.definition.BaseTableDefinition
import com.dbflow5.processor.definition.QueryModelDefinition
import com.dbflow5.processor.definition.TableDefinition
import com.dbflow5.processor.utils.annotation
import com.dbflow5.processor.utils.fromTypeMirror
import com.dbflow5.processor.utils.implementsClass
import com.dbflow5.processor.utils.isNullOrEmpty
import com.dbflow5.processor.utils.isSubclass
import com.dbflow5.processor.utils.toTypeElement
import com.dbflow5.processor.utils.toTypeErasedElement
import com.dbflow5.quote
import com.dbflow5.quoteIfNeeded
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
import com.squareup.javapoet.FieldSpec
import com.squareup.javapoet.MethodSpec
import com.squareup.javapoet.NameAllocator
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import com.squareup.javapoet.TypeSpec
import java.util.concurrent.atomic.AtomicInteger
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.type.MirroredTypeException
import javax.lang.model.type.TypeMirror
/**
* Description: Represents both a [ForeignKey] and [ColumnMap]. Builds up the model of fields
* required to generate definitions.
*/
class ReferenceColumnDefinition(manager: ProcessorManager, tableDefinition: BaseTableDefinition,
element: Element, isPackagePrivate: Boolean)
: ColumnDefinition(manager, element, tableDefinition, isPackagePrivate) {
private val _referenceDefinitionList: MutableList<ReferenceDefinition> = arrayListOf()
val referenceDefinitionList: List<ReferenceDefinition>
get() {
checkNeedsReferences()
return _referenceDefinitionList
}
var referencedClassName: ClassName? = null
var onDelete = ForeignKeyAction.NO_ACTION
var onUpdate = ForeignKeyAction.NO_ACTION
var isStubbedRelationship: Boolean = false
var isReferencingTableObject: Boolean = false
var implementsModel = false
var extendsBaseModel = false
var references: List<ReferenceSpecificationDefinition>? = null
var nonModelColumn: Boolean = false
var saveForeignKeyModel: Boolean = false
var deleteForeignKeyModel: Boolean = false
var needsReferences = true
var deferred = false
var isColumnMap = false
override val typeConverterElementNames: List<TypeName?>
get() {
val uniqueTypes = mutableSetOf<TypeName?>()
referenceDefinitionList.filter { it.hasTypeConverter }.mapTo(uniqueTypes) { it.columnClassName }
return uniqueTypes.toList()
}
init {
element.annotation<ColumnMap>()?.let {
isColumnMap = true
// column map is stubbed
isStubbedRelationship = true
findReferencedClassName(manager)
typeElement?.let { typeElement ->
QueryModelDefinition(typeElement, manager).apply {
databaseTypeName = tableDefinition.databaseTypeName
manager.addQueryModelDefinition(this)
}
}
references = it.references.map {
var typeConverterClassName: ClassName? = null
var typeMirror: TypeMirror? = null
try {
it.typeConverter
} catch (mte: MirroredTypeException) {
typeMirror = mte.typeMirror
typeConverterClassName = fromTypeMirror(typeMirror, manager)
}
ReferenceSpecificationDefinition(columnName = it.columnName,
referenceName = it.columnMapFieldName,
onNullConflictAction = it.notNull.onNullConflict,
defaultValue = it.defaultValue,
typeConverterClassName = typeConverterClassName,
typeConverterTypeMirror = typeMirror)
}
}
element.annotation<ForeignKey>()?.let { foreignKey ->
if (tableDefinition !is TableDefinition) {
manager.logError("Class $elementName cannot declare a @ForeignKey. Use @ColumnMap instead.")
}
onUpdate = foreignKey.onUpdate
onDelete = foreignKey.onDelete
deferred = foreignKey.deferred
isStubbedRelationship = foreignKey.stubbedRelationship
try {
foreignKey.tableClass
} catch (mte: MirroredTypeException) {
referencedClassName = fromTypeMirror(mte.typeMirror, manager)
}
val erasedElement = element.toTypeErasedElement()
// hopefully intentionally left blank
if (referencedClassName == TypeName.OBJECT) {
findReferencedClassName(manager)
}
if (referencedClassName == null) {
manager.logError("Referenced was null for $element within $elementTypeName")
}
extendsBaseModel = erasedElement.isSubclass(manager.processingEnvironment, com.dbflow5.processor.ClassNames.BASE_MODEL)
implementsModel = erasedElement.implementsClass(manager.processingEnvironment, com.dbflow5.processor.ClassNames.MODEL)
isReferencingTableObject = implementsModel || erasedElement.annotation<Table>() != null
nonModelColumn = !isReferencingTableObject
saveForeignKeyModel = foreignKey.saveForeignKeyModel
deleteForeignKeyModel = foreignKey.deleteForeignKeyModel
references = foreignKey.references.map {
ReferenceSpecificationDefinition(columnName = it.columnName,
referenceName = it.foreignKeyColumnName,
onNullConflictAction = it.notNull.onNullConflict,
defaultValue = it.defaultValue)
}
}
if (isNotNullType) {
manager.logError("Foreign Keys must be nullable. Please remove the non-null annotation if using " +
"Java, or add ? to the type for Kotlin.")
}
}
private fun findReferencedClassName(manager: ProcessorManager) {
if (elementTypeName is ParameterizedTypeName) {
val args = (elementTypeName as ParameterizedTypeName).typeArguments
if (args.size > 0) {
referencedClassName = ClassName.get(args[0].toTypeElement(manager))
}
} else {
if (referencedClassName == null || referencedClassName == ClassName.OBJECT) {
referencedClassName = elementTypeName.toTypeElement()?.let { ClassName.get(it) }
}
}
}
override fun addPropertyDefinition(typeBuilder: TypeSpec.Builder, tableClass: TypeName) {
referenceDefinitionList.forEach {
var propParam: TypeName? = null
val colClassName = it.columnClassName
colClassName?.let {
propParam = ParameterizedTypeName.get(com.dbflow5.processor.ClassNames.PROPERTY, it.box())
}
if (it.columnName.isNullOrEmpty()) {
manager.logError("Found empty reference name at ${it.foreignColumnName}" +
" from table ${baseTableDefinition.elementName}")
}
typeBuilder.addField(FieldSpec.builder(propParam, it.columnName,
Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL)
.initializer("new \$T(\$T.class, \$S)", propParam, tableClass, it.columnName)
.addJavadoc(if (isColumnMap) "Column Mapped Field" else ("Foreign Key" + if (isPrimaryKey) " / Primary Key" else "")).build())
}
}
override fun addPropertyCase(methodBuilder: MethodSpec.Builder) {
referenceDefinitionList.forEach {
methodBuilder.case(it.columnName.quoteIfNeeded().S) {
`return`(it.columnName)
}
}
}
override fun appendIndexInitializer(initializer: CodeBlock.Builder, index: AtomicInteger) {
if (nonModelColumn) {
super.appendIndexInitializer(initializer, index)
} else {
referenceDefinitionList.forEach {
if (index.get() > 0) {
initializer.add(", ")
}
initializer.add(it.columnName)
index.incrementAndGet()
}
}
}
override fun addColumnName(codeBuilder: CodeBlock.Builder) {
for (i in referenceDefinitionList.indices) {
val reference = referenceDefinitionList[i]
if (i > 0) {
codeBuilder.add(",")
}
codeBuilder.add(reference.columnName)
}
}
override val updateStatementBlock: CodeBlock
get() {
val builder = CodeBlock.builder()
referenceDefinitionList.indices.forEach { i ->
if (i > 0) {
builder.add(",")
}
val referenceDefinition = referenceDefinitionList[i]
builder.add(CodeBlock.of("${referenceDefinition.columnName.quote()}=?"))
}
return builder.build()
}
override val insertStatementColumnName: CodeBlock
get() {
val builder = CodeBlock.builder()
referenceDefinitionList.indices.forEach { i ->
if (i > 0) {
builder.add(",")
}
val referenceDefinition = referenceDefinitionList[i]
builder.add(referenceDefinition.columnName.quote())
}
return builder.build()
}
override val insertStatementValuesString: CodeBlock
get() {
val builder = CodeBlock.builder()
referenceDefinitionList.indices.forEach { i ->
if (i > 0) {
builder.add(",")
}
builder.add("?")
}
return builder.build()
}
override val creationName: CodeBlock
get() {
val builder = CodeBlock.builder()
referenceDefinitionList.indices.forEach { i ->
if (i > 0) {
builder.add(" ,")
}
val referenceDefinition = referenceDefinitionList[i]
builder.add(referenceDefinition.creationStatement)
if (referenceDefinition.notNull) {
builder.add(" NOT NULL ON CONFLICT \$L", referenceDefinition.onNullConflict)
}
}
return builder.build()
}
override val primaryKeyName: String
get() {
val builder = CodeBlock.builder()
referenceDefinitionList.indices.forEach { i ->
if (i > 0) {
builder.add(" ,")
}
val referenceDefinition = referenceDefinitionList[i]
builder.add(referenceDefinition.primaryKeyName)
}
return builder.build().toString()
}
override val contentValuesStatement: CodeBlock
get() = if (nonModelColumn) {
super.contentValuesStatement
} else {
val codeBuilder = CodeBlock.builder()
referencedClassName?.let {
val foreignKeyCombiner = ForeignKeyAccessCombiner(columnAccessor)
referenceDefinitionList.forEach {
foreignKeyCombiner.fieldAccesses += it.contentValuesField
}
foreignKeyCombiner.addCode(codeBuilder, AtomicInteger(0))
}
codeBuilder.build()
}
override fun getSQLiteStatementMethod(index: AtomicInteger, defineProperty: Boolean): CodeBlock {
if (nonModelColumn) {
return super.getSQLiteStatementMethod(index, defineProperty)
} else {
val codeBuilder = CodeBlock.builder()
referencedClassName?.let {
val foreignKeyCombiner = ForeignKeyAccessCombiner(columnAccessor)
referenceDefinitionList.forEach {
foreignKeyCombiner.fieldAccesses += it.sqliteStatementField
}
foreignKeyCombiner.addCode(codeBuilder, index, defineProperty)
}
return codeBuilder.build()
}
}
override fun getLoadFromCursorMethod(endNonPrimitiveIf: Boolean, index: AtomicInteger, nameAllocator: NameAllocator): CodeBlock {
if (nonModelColumn) {
return super.getLoadFromCursorMethod(endNonPrimitiveIf, index, nameAllocator)
} else {
val code = CodeBlock.builder()
referencedClassName?.let { referencedTableClassName ->
val tableDefinition = manager.getReferenceDefinition(
baseTableDefinition.databaseDefinition?.elementTypeName, referencedTableClassName)
val outputClassName = tableDefinition?.outputClassName
outputClassName?.let {
val foreignKeyCombiner = ForeignKeyLoadFromCursorCombiner(columnAccessor,
referencedTableClassName, outputClassName, isStubbedRelationship, nameAllocator)
referenceDefinitionList.forEach {
foreignKeyCombiner.fieldAccesses += it.partialAccessor
}
foreignKeyCombiner.addCode(code, index)
}
}
return code.build()
}
}
override fun appendPropertyComparisonAccessStatement(codeBuilder: CodeBlock.Builder) {
when {
nonModelColumn -> PrimaryReferenceAccessCombiner(combiner).apply {
checkNeedsReferences()
codeBuilder.addCode(references!![0].columnName, getDefaultValueBlock(), 0, modelBlock)
}
columnAccessor is TypeConverterScopeColumnAccessor -> super.appendPropertyComparisonAccessStatement(codeBuilder)
else -> referencedClassName?.let {
val foreignKeyCombiner = ForeignKeyAccessCombiner(columnAccessor)
referenceDefinitionList.forEach {
foreignKeyCombiner.fieldAccesses += it.primaryReferenceField
}
foreignKeyCombiner.addCode(codeBuilder, AtomicInteger(0))
}
}
}
fun appendSaveMethod(codeBuilder: CodeBlock.Builder) {
if (!nonModelColumn && columnAccessor !is TypeConverterScopeColumnAccessor) {
referencedClassName?.let { referencedTableClassName ->
val saveAccessor = ForeignKeyAccessField(columnName,
SaveModelAccessCombiner(Combiner(columnAccessor, referencedTableClassName, wrapperAccessor,
wrapperTypeName, subWrapperAccessor), implementsModel, extendsBaseModel))
saveAccessor.addCode(codeBuilder, 0, modelBlock)
}
}
}
fun appendDeleteMethod(codeBuilder: CodeBlock.Builder) {
if (!nonModelColumn && columnAccessor !is TypeConverterScopeColumnAccessor) {
referencedClassName?.let { referencedTableClassName ->
val deleteAccessor = ForeignKeyAccessField(columnName,
DeleteModelAccessCombiner(Combiner(columnAccessor, referencedTableClassName, wrapperAccessor,
wrapperTypeName, subWrapperAccessor), implementsModel, extendsBaseModel))
deleteAccessor.addCode(codeBuilder, 0, modelBlock)
}
}
}
/**
* If [ForeignKey] has no [ForeignKeyReference]s, we use the primary key the referenced
* table. We do this post-evaluation so all of the [TableDefinition] can be generated.
*/
fun checkNeedsReferences() {
val tableDefinition = baseTableDefinition
val referencedTableDefinition = manager.getReferenceDefinition(tableDefinition.databaseTypeName, referencedClassName)
if (referencedTableDefinition == null) {
manager.logError(ReferenceColumnDefinition::class,
"Could not find the referenced ${Table::class.java.simpleName} " +
"or ${QueryModel::class.java.simpleName} definition $referencedClassName" +
" from ${tableDefinition.elementName}. " +
"Ensure it exists in the same database as ${tableDefinition.databaseTypeName}")
} else if (needsReferences) {
val primaryColumns =
if (isColumnMap) referencedTableDefinition.columnDefinitions
else referencedTableDefinition.primaryColumnDefinitions
if (references?.isEmpty() != false) {
primaryColumns.forEach {
val foreignKeyReferenceDefinition = ReferenceDefinition(manager,
elementName, it.elementName, it, this, primaryColumns.size,
if (isColumnMap) it.elementName else "",
defaultValue = it.defaultValue)
_referenceDefinitionList.add(foreignKeyReferenceDefinition)
}
needsReferences = false
} else {
references?.forEach { reference ->
val foundDefinition = primaryColumns.find { it.columnName == reference.referenceName }
if (foundDefinition == null) {
manager.logError(ReferenceColumnDefinition::class,
"Could not find referenced column ${reference.referenceName} " +
"from reference named ${reference.columnName}")
} else {
_referenceDefinitionList.add(
ReferenceDefinition(manager, elementName,
foundDefinition.elementName, foundDefinition, this,
primaryColumns.size, reference.columnName,
reference.onNullConflictAction,
reference.defaultValue,
reference.typeConverterClassName,
reference.typeConverterTypeMirror))
}
}
needsReferences = false
}
if (nonModelColumn && _referenceDefinitionList.size == 1) {
columnName = _referenceDefinitionList[0].columnName
}
_referenceDefinitionList.forEach {
if (it.columnClassName?.isPrimitive == true
&& !it.defaultValue.isNullOrEmpty()) {
manager.logWarning(ColumnValidator::class.java,
"Default value of \"${it.defaultValue}\" from " +
"${tableDefinition.elementName}.$elementName is ignored for primitive columns.")
}
}
}
}
}
/**
* Description: defines a ForeignKeyReference or ColumnMapReference.
*/
class ReferenceSpecificationDefinition(val columnName: String,
val referenceName: String,
val onNullConflictAction: ConflictAction,
val defaultValue: String,
val typeConverterClassName: ClassName? = null,
val typeConverterTypeMirror: TypeMirror? = null)
| 1 | null |
1
| 1 |
299a76343b75bafb82e9ba1de77270dd8c0ed1e0
| 19,965 |
dbflow
|
MIT License
|
src/main/kotlin/com/strumenta/kolasu/mapping/Mapping.kt
|
lanarimarco
| 313,685,830 | true |
{"Kotlin": 71183, "ANTLR": 993}
|
package com.strumenta.kolasu.mapping
import com.strumenta.kolasu.model.*
import org.antlr.v4.runtime.ParserRuleContext
import org.antlr.v4.runtime.Token
interface ParseTreeToAstMapper<in PTN : ParserRuleContext, out ASTN : Node> {
fun map(parseTreeNode: PTN): ASTN
}
val Token.length
get() = if (this.type == Token.EOF) 0 else text.length
val ParserRuleContext.position: Position
get() = Position(start.startPoint, stop.endPoint)
fun ParserRuleContext.toPosition(considerPosition: Boolean = true): Position? {
return if (considerPosition && start != null && stop != null) {
position
} else null
}
| 0 | null |
0
| 0 |
9d984a6bcc4fe528386032572bb7873989b829f7
| 630 |
kolasu
|
Apache License 2.0
|
feature/survey/src/main/java/com/wap/wapp/feature/survey/answer/SubjectiveSurveyForm.kt
|
pknu-wap
| 689,890,586 | false |
{"Kotlin": 326232, "Shell": 233}
|
package com.wap.wapp.feature.survey.answer
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.wap.designsystem.WappTheme
import com.wap.designsystem.component.WappRoundedTextField
import com.wap.wapp.feature.survey.R
@Composable
internal fun SubjectiveSurveyForm(
questionTitle: String,
answer: String,
onAnswerChanged: (String) -> Unit,
) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(32.dp),
) {
Text(
text = questionTitle,
style = WappTheme.typography.titleRegular,
color = WappTheme.colors.white,
fontSize = 22.sp,
)
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(4.dp),
) {
WappRoundedTextField(
value = answer,
onValueChange = onAnswerChanged,
placeholder = R.string.subjective_answer_hint,
modifier = Modifier
.height(200.dp)
.fillMaxWidth(),
)
val textCount = answer.length
TextCounter(textCount = textCount)
}
}
}
@Composable
private fun TextCounter(
textCount: Int,
) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End,
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = textCount.toString(),
color = WappTheme.colors.yellow34,
style = WappTheme.typography.labelMedium,
)
Text(
text = stringResource(R.string.text_counter_content),
color = WappTheme.colors.white,
style = WappTheme.typography.labelMedium,
)
}
}
| 6 |
Kotlin
|
1
| 8 |
dadd9aba8148061d4198a6030d4b14f70454d77a
| 2,289 |
WAPP
|
MIT License
|
feature-news-ui/src/main/kotlin/dev/bogdanzurac/marp/feature/news/ui/NewsDetailsScreen.kt
|
bogdanzurac
| 606,411,511 | false | null |
package dev.bogdanzurac.marp.feature.news.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import dev.bogdanzurac.marp.core.ui.DateTimeAttribute.DATE_TIME_SHORT
import dev.bogdanzurac.marp.core.ui.composable.BaseScreen
import dev.bogdanzurac.marp.core.ui.composable.EmptyView
import dev.bogdanzurac.marp.core.ui.composable.LoadingView
import dev.bogdanzurac.marp.core.ui.composable.SelectableText
import dev.bogdanzurac.marp.core.ui.format
import dev.bogdanzurac.marp.core.ui.toLocalDateTime
import dev.bogdanzurac.marp.feature.news.domain.NewsArticle
import dev.bogdanzurac.marp.feature.news.ui.NewsDetailsViewModel.NewsDetailsUiState.*
import org.koin.androidx.compose.koinViewModel
import org.koin.core.parameter.parametersOf
@Composable
internal fun NewsDetailsScreen(
articleId: String,
viewModel: NewsDetailsViewModel = koinViewModel(parameters = { parametersOf(articleId) })
) = BaseScreen(viewModel) { state ->
when (val uiState = state.value) {
is Loading -> LoadingView()
is Error -> EmptyView()
is Success -> NewsDetailsView(uiState.newsArticle)
}
}
@Composable
private fun NewsDetailsView(newsArticle: NewsArticle) {
Column(Modifier.verticalScroll(rememberScrollState())) {
AsyncImage(
model = newsArticle.imageUrl,
modifier = Modifier.fillMaxWidth(),
contentDescription = newsArticle.title,
contentScale = ContentScale.FillWidth,
)
Column(Modifier.padding(16.dp)) {
SelectableText(
text = newsArticle.title,
style = MaterialTheme.typography.headlineMedium
)
Text(
text = newsArticle.publishDate
.toLocalDateTime()
.format(LocalContext.current, DATE_TIME_SHORT),
style = MaterialTheme.typography.labelSmall
)
newsArticle.author?.let {
Text(
text = it.joinToString(", "),
style = MaterialTheme.typography.bodyMedium
)
}
newsArticle.description?.let {
SelectableText(
text = it,
textAlign = TextAlign.Justify,
modifier = Modifier.padding(top = 16.dp, start = 16.dp, end = 16.dp),
style = MaterialTheme.typography.bodyLarge
)
}
newsArticle.content?.let {
SelectableText(
text = it,
textAlign = TextAlign.Justify,
modifier = Modifier.padding(top = 16.dp),
style = MaterialTheme.typography.bodyMedium
)
}
}
}
}
@Composable
@Preview
private fun NewsDetailsPreview() {
MaterialTheme {
NewsDetailsView(composeNewsArticleModelPreview)
}
}
| 0 |
Kotlin
|
0
| 2 |
1b8859f92a7c20837817b0abf897530bb691caba
| 3,550 |
marp-app-client-android
|
Apache License 2.0
|
rpgJavaInterpreter-core/src/main/kotlin/com/smeup/rpgparser/interpreter/Evaluator.kt
|
smeup
| 170,714,014 | false | null |
package com.smeup.rpgparser.interpreter
import com.smeup.rpgparser.parsing.ast.*
import com.smeup.rpgparser.parsing.parsetreetoast.LogicalCondition
interface Evaluator {
fun eval(expression: IntLiteral): Value
fun eval(expression: RealLiteral): Value
fun eval(expression: StringLiteral): Value
fun eval(expression: NumberOfElementsExpr): Value
fun eval(expression: DataRefExpr): Value
fun eval(expression: EqualityExpr): Value
fun eval(expression: DifferentThanExpr): Value
fun eval(expression: GreaterThanExpr): Value
fun eval(expression: GreaterEqualThanExpr): Value
fun eval(expression: LessEqualThanExpr): Value
fun eval(expression: LessThanExpr): Value
fun eval(expression: BlanksRefExpr): BlanksValue
fun eval(expression: DecExpr): Value
fun eval(expression: PlusExpr): Value
fun eval(expression: MinusExpr): Value
fun eval(expression: MultExpr): Value
fun eval(expression: CharExpr): Value
fun eval(expression: LookupExpr): Value
fun eval(expression: ArrayAccessExpr): Value
fun eval(expression: HiValExpr): HiValValue
fun eval(expression: LowValExpr): LowValValue
fun eval(expression: ZeroExpr): ZeroValue
fun eval(expression: AllExpr): AllValue
fun eval(expression: TranslateExpr): Value
fun eval(expression: LogicalAndExpr): Value
fun eval(expression: LogicalOrExpr): Value
fun eval(expression: LogicalCondition): Value
fun eval(expression: OnRefExpr): BooleanValue
fun eval(expression: NotExpr): BooleanValue
fun eval(expression: ScanExpr): Value
fun eval(expression: SubstExpr): Value
fun eval(expression: LenExpr): Value
fun eval(expression: OffRefExpr): BooleanValue
fun eval(expression: IndicatorExpr): BooleanValue
fun eval(expression: FunctionCall): Value
fun eval(expression: TimeStampExpr): Value
fun eval(expression: EditcExpr): Value
fun eval(expression: DiffExpr): Value
fun eval(expression: DivExpr): Value
fun eval(expression: ExpExpr): Value
fun eval(expression: TrimrExpr): Value
fun eval(expression: TrimlExpr): Value
fun eval(expression: TrimExpr): StringValue
fun eval(expression: FoundExpr): Value
fun eval(expression: EofExpr): Value
fun eval(expression: EqualExpr): Value
fun eval(expression: AbsExpr): Value
fun eval(expression: EditwExpr): Value
fun eval(expression: IntExpr): Value
fun eval(expression: RemExpr): Value
fun eval(expression: QualifiedAccessExpr): Value
fun eval(expression: ReplaceExpr): Value
fun eval(expression: SqrtExpr): Value
fun eval(expression: AssignmentExpr): Value
fun eval(expression: GlobalIndicatorExpr): Value
fun eval(expression: ParmsExpr): Value
}
| 6 | null |
11
| 46 |
9f98557185d859cb85ac3529b157ee89380fc8f6
| 2,742 |
jariko
|
Apache License 2.0
|
ok-marketplace-biz/src/commonMain/kotlin/stubs/StubSearchSuccess.kt
|
otuskotlin
| 462,372,364 | false | null |
package ru.otus.otuskotlin.marketplace.biz.stubs
import com.crowdproj.kotlin.cor.ICorChainDsl
import com.crowdproj.kotlin.cor.handlers.worker
import ru.otus.otuskotlin.marketplace.common.MkplContext
import ru.otus.otuskotlin.marketplace.common.models.*
import ru.otus.otuskotlin.marketplace.common.stubs.MkplStubs
import ru.otus.otuskotlin.marketplace.stubs.MkplAdStub
fun ICorChainDsl<MkplContext>.stubSearchSuccess(title: String) = worker {
this.title = title
on { stubCase == MkplStubs.SUCCESS && state == MkplState.RUNNING }
handle {
state = MkplState.FINISHING
adsResponse.addAll(MkplAdStub.prepareSearchList(adFilterRequest.searchString, MkplDealSide.DEMAND))
}
}
| 0 |
Kotlin
|
5
| 1 |
f0af66ea368c6d0908dc7dc8cd7a22bf6bb73228
| 704 |
202202-ok-marketplace
|
MIT License
|
api/src/main/kotlin/io/larbin/task/scenario/ScenarioRunnerFactory.kt
|
wadinj
| 127,206,644 | false | null |
package io.larbin.task.scenario
import io.larbin.api.scenario.entities.Scenario
import org.springframework.stereotype.Component
@Component
class ScenarioRunnerFactory {
fun createScenarioRunner(scenario: Scenario) : ScenarioRunner {
return ScenarioRunner(scenario)
}
}
| 0 |
Kotlin
|
0
| 0 |
3d18633b5fbce08f58517845bf2311b8837c0644
| 298 |
Larbin
|
Apache License 2.0
|
android/app/src/main/java/dev/fuwa/pskey/ImagedPickerAdapter.kt
|
ibuki2003
| 670,380,349 | false |
{"TypeScript": 64779, "Kotlin": 28110, "Objective-C": 2283, "JavaScript": 2139, "Ruby": 1476, "Objective-C++": 797}
|
package dev.fuwa.pskey
import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import coil.load
class ImagePickerAdapter(
applicationContext: Context?,
): BaseAdapter() {
private var context: Context? = applicationContext
var items: List<ImagePickerItem> = listOf()
set(value) {
field = value
notifyDataSetChanged()
}
private var inflater: LayoutInflater
init {
inflater = LayoutInflater.from(applicationContext)
}
var color: Int? = null
set(value) {
field = value
notifyDataSetChanged()
}
var backgroundColor: Int? = null
set(value) {
field = value
notifyDataSetChanged()
}
override fun getCount(): Int { return items.size }
override fun getItem(i: Int): Any? { return null }
override fun getItemId(i: Int): Long { return 0 }
override fun getView(i: Int, convertView: View?, parent: ViewGroup): View? {
val view = convertView ?: inflater.inflate(R.layout.imaged_spinner_item, parent, false)
view.setBackgroundColor(backgroundColor ?: Color.TRANSPARENT)
val icon = view.findViewById<View>(R.id.imageView) as ImageView
val names = view.findViewById<View>(R.id.textView) as TextView
if (color != null) names.setTextColor(color!!)
icon.load(this.items[i].imageUrl)
names.text = this.items[i].text
return view
}
}
class ImagePickerItem(
public final val text: String,
public final val imageUrl: String,
)
| 12 |
TypeScript
|
0
| 20 |
f34aab2d55c84d9ed7f3368fb4ceefddfe57d280
| 1,628 |
pskey
|
MIT License
|
android/src/main/java/com/trackierexposdk/TrackierUtil.kt
|
trackier
| 845,972,050 | false |
{"Kotlin": 12044, "TypeScript": 11674, "Swift": 6771, "Objective-C++": 3623, "Ruby": 3224, "Objective-C": 2480, "JavaScript": 1380, "C": 103}
|
package com.trackierexposdk
import android.util.Log
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.bridge.ReadableMap
import com.facebook.react.bridge.ReadableType
object TrackierUtil {
fun toMap(readableMap: ReadableMap?): Map<String, Any>? {
if (readableMap == null) {
return null
}
val iterator = readableMap.keySetIterator()
if (!iterator.hasNextKey()) {
return null
}
val result = mutableMapOf<String, Any>()
try {
while (iterator.hasNextKey()) {
val key = iterator.nextKey()
val value = toObject(readableMap, key) ?: continue
result[key] = value.toString()
}
} catch (e: Exception) {
Log.e("trackiersdk", "Error converting ReadableMap to Map: ${e.message}", e)
return result
}
return result
}
private fun toObject(readableMap: ReadableMap?, key: String): Any? {
if (readableMap == null) {
return null
}
val readableType = readableMap.getType(key)
return when (readableType) {
ReadableType.Null -> null
ReadableType.Boolean -> readableMap.getBoolean(key)
ReadableType.Number -> {
val tmp = readableMap.getDouble(key)
if (tmp == tmp.toInt().toDouble()) {
tmp.toInt()
} else {
tmp
}
}
ReadableType.String -> readableMap.getString(key)
ReadableType.Map -> toMap(readableMap.getMap(key))
ReadableType.Array -> toList(readableMap.getArray(key))
else -> null
}
}
private fun toList(readableArray: ReadableArray?): List<Any>? {
if (readableArray == null) {
return null
}
val result = mutableListOf<Any>()
for (i in 0 until readableArray.size()) {
val item = readableArray.getDynamic(i)
result.add(item)
}
return result
}
}
| 0 |
Kotlin
|
0
| 0 |
290335a9288a05561253cbd7a5aece8276ba7cee
| 1,837 |
trackier-expo-sdk
|
MIT License
|
app/src/main/java/com/nativeboys/password/manager/ui/adapters/categories/CategoriesViewHolder.kt
|
EvangelosBoudis
| 347,924,640 | false | null |
package com.nativeboys.password.manager.ui.adapters.categories
import android.graphics.Color
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatDelegate
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.nativeboys.password.manager.R
import com.nativeboys.password.manager.data.CategoryData
import com.nativeboys.password.manager.util.intoMaterialIcon
import com.nativeboys.password.manager.util.intoView
import com.nativeboys.password.manager.util.materialIconCodeToDrawable
import com.nativeboys.uikit.rv.RecyclerViewHolder
import com.nativeboys.uikit.swipeRevealLayout.SwipeRevealLayout
import com.nativeboys.uikit.swipeRevealLayout.ViewBinderHelper
import net.steamcrafted.materialiconlib.MaterialIconView
class CategoriesViewHolder(
itemView: View,
private val binder: ViewBinderHelper
) : RecyclerViewHolder<CategoryData>(itemView) {
private val container: SwipeRevealLayout = itemView.findViewById(R.id.container)
private val visibleView: ConstraintLayout = itemView.findViewById(R.id.visible_view)
private val moreBtn: ImageView = itemView.findViewById(R.id.more_btn)
private val deleteBtn: ImageView = itemView.findViewById(R.id.delete_btn)
private val thumbnailBackgroundHolder = itemView.findViewById<View>(R.id.thumbnail_background_holder)
private val thumbnailHolder = itemView.findViewById<MaterialIconView>(R.id.thumbnail_holder)
private val nameField = itemView.findViewById<TextView>(R.id.name_field)
init {
moreBtn.setOnClickListener(this)
visibleView.setOnClickListener(this)
deleteBtn.setOnClickListener(this)
}
override fun bind(model: CategoryData) {
binder.bind(container, model.id)
container.setLockDrag(true)
Glide.with(itemView.context)
.load(R.drawable.cell_shape)
.intoView(visibleView)
nameField.text = model.name
Glide
.with(itemView.context)
.load(ContextCompat.getDrawable(itemView.context, R.drawable.stroke_shape))
.intoView(thumbnailBackgroundHolder)
val draw = materialIconCodeToDrawable(
itemView.context,
model.thumbnailCode,
if (AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES) Color.WHITE else Color.BLACK
)
if (draw != null) {
Glide.with(itemView.context)
.load(draw)
.transition(DrawableTransitionOptions().crossFade())
.intoMaterialIcon(thumbnailHolder)
} else {
thumbnailHolder.setImageDrawable(null)
}
Glide.with(itemView.context)
.load(R.drawable.menu_icon)
.into(moreBtn)
Glide.with(itemView.context)
.load(R.drawable.ic_baseline_delete_24)
.into(deleteBtn)
moreBtn.visibility = if (model.defaultCategory) View.GONE else View.VISIBLE
}
override fun onClick(v: View) {
when (v.id) {
R.id.more_btn -> {
if (container.isOpened) container.close(true)
else container.open(true)
}
R.id.visible_view -> {
if (container.isOpened) container.close(true)
else super.onClick(v)
}
else -> {
super.onClick(v)
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b392cf151d1967b6dc5d56fef6f5f0bfaaa7fb07
| 3,609 |
digital-bit-security
|
Apache License 2.0
|
implementation/src/main/kotlin/io/github/tomplum/aoc/bus/BusScheduler.kt
|
TomPlum
| 317,142,882 | false | null |
package io.github.tomplum.aoc.bus
/**
* A scheduler for the shuttle bus service.
*
* Bus schedules are defined based on a timestamp that measures the number of minutes since some fixed reference point
* in the past. At timestamp 0, every bus simultaneously departed from the sea port. After that, each bus travels to
* the airport, then various other locations, and finally returns to the sea port to repeat its journey forever.
*
* @param timetable A table of bus departure times
*/
class BusScheduler(private val timetable: BusTimetable) {
/**
* Finds the [Bus] which departs the shortest time after the [timetable] arrival time.
* @return The product of the [Bus] ID and the waiting time.
*/
fun getEarliestBus(): Int {
val buses = timetable.getWorkingBuses()
val firstAvailableTimes = buses.associateWith { bus -> bus.getID().getLastArrivalTime() + bus.getID() }
val waitingTimes = firstAvailableTimes.map { (id, time) -> id to time - timetable.arrivalTime }.toMap()
val best = waitingTimes.minByOrNull { (_, waitingTime) -> waitingTime }!!
return best.key.getID() * best.value
}
/**
* Finds the timestamp in which all the buses depart at their given offsets as defined in the [timetable].
* @see [BusTimetable.getBusesWithOffsets].
*
* For each bus, the timestamp (t) should satisfy: t + offset % id == 0
* Once the timestamp has been found for a bus, the step ratio can be increased by a factory of the previous id.
* This means each of the previous equations will be satisfied and skip lots of unnecessary processing.
*
* @return The timestamp that satisfies all departures at their offsets.
*/
fun getOffsetDepartureTime(): Long {
val buses = timetable.getBusesWithOffsets()
var step = buses.first().second.toLong()
var time = 0L
buses.drop(1).forEach { (offset, id) ->
while ((time + offset) % id != 0L) {
time += step
}
step *= id
}
return time
}
private fun Int.getLastArrivalTime() = timetable.arrivalTime - (timetable.arrivalTime % this)
}
| 1 |
Kotlin
|
0
| 0 |
e455d35213832bbd6b72277c0f9e5c0331fd732f
| 2,191 |
advent-of-code-2020
|
Apache License 2.0
|
hibernate-reactive/src/test/kotlin/com/linecorp/kotlinjdsl/test/reactive/integration/querydsl/groupby/HibernateCriteriaQueryDslGroupByIntegrationTest.kt
|
line
| 442,633,985 | false | null |
package com.linecorp.kotlinjdsl.test.reactive.integration.querydsl.groupby
import com.linecorp.kotlinjdsl.test.reactive.HibernateCriteriaIntegrationTest
import com.linecorp.kotlinjdsl.test.reactive.querydsl.groupby.AbstractCriteriaQueryDslGroupByIntegrationTest
import org.hibernate.reactive.mutiny.Mutiny
import javax.persistence.EntityManagerFactory
internal class HibernateCriteriaQueryDslGroupByIntegrationTest : HibernateCriteriaIntegrationTest,
AbstractCriteriaQueryDslGroupByIntegrationTest<Mutiny.SessionFactory>() {
override lateinit var factory: Mutiny.SessionFactory
override lateinit var entityManagerFactory: EntityManagerFactory
}
| 26 |
Kotlin
|
60
| 504 |
f28908bf432cf52f73a9573b1ac2be5eb4b2b7dc
| 659 |
kotlin-jdsl
|
Apache License 2.0
|
commons/src/main/java/com/anp/commons/data/database/DataBaseManager.kt
|
antocara
| 113,018,839 | false | null |
package com.anp.commons.data.database
import android.content.Context
import io.realm.Realm
import io.realm.RealmConfiguration
object DataBaseManager {
val DATABASE_NAME = "iptv_management"
fun initialize(context: Context) {
Realm.init(context)
configRealm()
}
private fun configRealm() {
// var config = RealmConfiguration.Builder()
// .name("myrealm.realm")
// .schemaVersion(1)
// .modules(MySchemaModule())
// .migration(MyMigration())
// .build()
// val config = RealmConfiguration.Builder()
// .name(DATABASE_NAME)
// .schemaVersion(1)
// .build()
//FIXME only development
val config = RealmConfiguration.Builder().deleteRealmIfMigrationNeeded().build()
Realm.setDefaultConfiguration(config)
}
}
| 1 |
Kotlin
|
24
| 31 |
58e6dc4bc9c55302f3beafa2cc187f47394f1184
| 801 |
iptvManagement
|
The Unlicense
|
credentials/credentials/src/androidTest/java/androidx/credentials/webauthn/PublicKeyCredentialRequestOptionsTest.kt
|
androidx
| 256,589,781 | false | null |
/*
* Copyright 2023 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.credentials.webauthn
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class PublicKeyCredentialRequestOptionsTest {
@Test
fun constructor() {
val rawId = byteArrayOf(1)
val json =
"""
{
"challenge": "AQ",
"rpId": "rp id",
"timeout": 10,
"userVerification": "enabled"
}
"""
var options = PublicKeyCredentialRequestOptions(json)
assertThat(options.challenge).isEqualTo(rawId)
assertThat(options.rpId).isEqualTo("rp id")
assertThat(options.timeout).isEqualTo(10)
assertThat(options.userVerification).isEqualTo("enabled")
}
@Test
fun constructor_optionalTimeout() {
val rawId = byteArrayOf(1)
val json =
"""
{
"challenge": "AQ",
"rpId": "rp id",
"userVerification": "enabled"
}
"""
var options = PublicKeyCredentialRequestOptions(json)
assertThat(options.challenge).isEqualTo(rawId)
assertThat(options.rpId).isEqualTo("rp id")
assertThat(options.timeout).isEqualTo(0)
assertThat(options.userVerification).isEqualTo("enabled")
}
@Test
fun constructor_optionalRpId() {
val rawId = byteArrayOf(1)
val json =
"""
{
"challenge": "AQ",
"timeout": 10,
"userVerification": "enabled"
}
"""
var options = PublicKeyCredentialRequestOptions(json)
assertThat(options.challenge).isEqualTo(rawId)
assertThat(options.rpId).isEqualTo("")
assertThat(options.timeout).isEqualTo(10)
assertThat(options.userVerification).isEqualTo("enabled")
}
@Test
fun constructor_optionalUserVerification() {
val rawId = byteArrayOf(1)
val json =
"""
{
"challenge": "AQ",
"rpId": "rp id",
"timeout": 10
}
"""
var options = PublicKeyCredentialRequestOptions(json)
assertThat(options.challenge).isEqualTo(rawId)
assertThat(options.rpId).isEqualTo("rp id")
assertThat(options.timeout).isEqualTo(10)
assertThat(options.userVerification).isEqualTo("preferred")
}
}
| 29 | null |
945
| 5,321 |
98b929d303f34d569e9fd8a529f022d398d1024b
| 3,237 |
androidx
|
Apache License 2.0
|
app/src/main/java/com/autosec/pie/services/ProcessManagerService.kt
|
cryptrr
| 850,497,911 | false |
{"Kotlin": 334195, "Shell": 1942}
|
package com.autosec.pie.services
import android.app.Application
import android.app.Service.STOP_FOREGROUND_REMOVE
import android.content.Context
import androidx.lifecycle.viewModelScope
import com.autosec.pie.data.AutoPieConstants
import com.autosec.pie.data.AutoPieStrings
import com.autosec.pie.domain.ViewModelEvent
import com.autosec.pie.viewModels.MainViewModel
import com.jaredrummler.ktsh.Shell
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.koin.java.KoinJavaComponent.inject
import timber.log.Timber
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
class ProcessManagerService {
companion object {
val main: MainViewModel by inject(MainViewModel::class.java)
private val activity: Application by inject(Context::class.java)
private var shell : Shell? = null
init {
main.viewModelScope.launch {
main.eventFlow.collect{
when(it){
is ViewModelEvent.CancelProcess -> {
}
else -> {}
}
}
}
}
private fun initShell(){
val shellPath = File(activity.filesDir, "sh").absolutePath
shell = Shell(
shellPath,
)
Timber.d(". ." + activity.filesDir.absolutePath + "/env.sh " + activity.filesDir.absolutePath)
val setEnvResult =
shell?.run(". .${activity.filesDir.absolutePath}/env.sh ${activity.filesDir.absolutePath} ${activity.packageName}")
Timber.d(setEnvResult?.output())
}
fun checkShell(): Boolean {
try{
val shellPath = File(activity.filesDir, "sh").absolutePath
val shell = Shell(
shellPath,
)
val result = shell.run(". .${activity.filesDir.absolutePath}/env.sh ${activity.filesDir.absolutePath}")
shell.shutdown()
return result.isSuccess
}catch (e: Exception){
return false
}
}
fun runCommand4(exec: String, command: String, cwd: String, usePython: Boolean = true) : Boolean {
try {
if(shell?.isAlive() != true) initShell()
val checkEnvResult = shell?.run("cd ${cwd}")
Timber.d(checkEnvResult?.output())
val fullCommand = if(usePython) "python3.9 $exec $command" else "sh $exec $command"
Timber.d(fullCommand)
val result = shell!!.run(fullCommand)
val output = result.output()
Timber.d(output)
return result.isSuccess
} catch (e: Exception) {
Timber.e(e.toString())
}
return false
}
fun runCommandForShare(exec: String, command: String, cwd: String, usePython: Boolean = true): Boolean {
try {
if(shell?.isAlive() != true) initShell()
shell!!.run("cd ${cwd}")
val fullCommand = if(usePython) "python3.9 $exec $command" else "sh $exec $command"
Timber.d(fullCommand)
val result = shell!!.run(fullCommand)
Timber.d("Exit Code ${result.exitCode}")
val output = result.output()
Timber.d(output)
//shell?.shutdown()
return result.isSuccess
} catch (e: Exception) {
Timber.e(e.toString())
}
return false
}
fun createAutoPieShell(): Shell? {
try {
val shellPath = File(activity.filesDir, "sh").absolutePath
val shell = Shell(
shellPath,
)
Timber.d(". ." + activity.filesDir.absolutePath + "/env.sh " + activity.filesDir.absolutePath)
shell.run(". .${activity.filesDir.absolutePath}/env.sh ${activity.filesDir.absolutePath} ${activity.packageName}")
shell.run("cd ${activity.filesDir.absolutePath}")
return shell
} catch (e: Exception) {
Timber.e(e.toString())
return null
}
}
fun downloadFileWithPython(url: String, fullFilePath: String): Boolean {
Timber.d("Downloading file with python")
try {
if(shell?.isAlive() != true) initShell()
val command = "python3.9 -c \"import urllib.request; url = '${url}'; output_file = '${fullFilePath}'; urllib.request.urlretrieve(url, output_file); print(f'Downloaded {url} to {output_file}')\""
Timber.d(command)
val result = shell!!.run(command)
Timber.d(shell!!.isRunning().toString())
Timber.d(result.output())
return result.isSuccess
} catch (e: Exception) {
Timber.e(e.toString())
return false
}
}
fun deleteFile(filePath: String) {
CoroutineScope(Dispatchers.IO).launch {
delay(20000L)
try {
if(shell?.isAlive() != true) initShell()
Timber.d("Deleting file at $filePath")
val result = shell!!.run("rm '$filePath'")
Timber.d(result.output())
} catch (e: Exception) {
Timber.e(e.toString())
}
}
}
fun clearPackagesCache() {
val folderPath = activity.filesDir.absolutePath + "/.shiv"
Timber.d(folderPath)
CoroutineScope(Dispatchers.IO).launch {
try {
val directory = File(folderPath)
directory.deleteRecursively()
} catch (e: Exception) {
Timber.e(e.toString())
}
}
}
fun makeBinariesFolderExecutable(){
Timber.d("Making python binary files executable")
val shellPath = File(activity.filesDir, "sh").absolutePath
val binLocation = File(activity.filesDir, "build/usr/bin")
val shell = Shell(
shellPath,
)
shell.run("chmod +x ${binLocation.absolutePath}/*")
}
}
}
| 2 |
Kotlin
|
0
| 2 |
5dc9ce2a1a0950e2e6db0c85a0927b2b5e9e16f0
| 6,629 |
AutoPie
|
Apache License 2.0
|
zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/fragment/TableDsl.kt
|
Hexworks
| 94,116,947 | false |
{"Kotlin": 1792092, "Java": 121457, "Shell": 152}
|
package org.hexworks.zircon.api.dsl.fragment
import org.hexworks.zircon.api.Beta
import org.hexworks.zircon.api.builder.fragment.TableBuilder
import org.hexworks.zircon.api.builder.fragment.TableColumnBuilder
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
import org.hexworks.zircon.api.dsl.AnyContainerBuilder
import org.hexworks.zircon.api.dsl.component.buildFragmentFor
import org.hexworks.zircon.api.fragment.Table
import org.hexworks.zircon.api.fragment.TableColumn
/**
* Creates a new [Table] using the fragment builder DSL and returns it.
*/
@Beta
fun <T : Any> buildTable(
init: TableBuilder<T>.() -> Unit
): Table<T> = TableBuilder.newBuilder<T>().apply(init).build()
/**
* Creates a new [Table] using the fragment builder DSL, adds it to the
* receiver [BaseContainerBuilder] it and returns the [Table].
*/
@Beta
fun <T : Any> AnyContainerBuilder.table(
init: TableBuilder<T>.() -> Unit
): Table<T> = buildFragmentFor(this, TableBuilder.newBuilder(), init)
| 42 |
Kotlin
|
138
| 735 |
9eeabb2b30e493189c9931f40d48bae877cf3554
| 1,062 |
zircon
|
Apache License 2.0
|
app/src/main/java/org/stepic/droid/storage/dao/CourseDaoImpl.kt
|
Ujjawal-Anand
| 142,415,269 | false | null |
package org.stepic.droid.storage.dao
import android.content.ContentValues
import android.database.Cursor
import org.stepic.droid.mappers.toDbUrl
import org.stepic.droid.mappers.toVideoUrls
import org.stepic.droid.model.*
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepic.droid.storage.structure.DbStructureCachedVideo
import org.stepic.droid.storage.structure.DbStructureEnrolledAndFeaturedCourses
import org.stepic.droid.storage.structure.DbStructureVideoUrl
import org.stepic.droid.util.*
import org.stepik.android.model.Course
import org.stepik.android.model.Video
import org.stepik.android.model.VideoUrl
import javax.inject.Inject
class CourseDaoImpl
@Inject
constructor(
databaseOperations: DatabaseOperations,
private val cachedVideoDao: IDao<CachedVideo>,
private val externalVideoUrlIDao: IDao<DbVideoUrl>,
private val tableName: String
) : DaoBase<Course>(databaseOperations) {
public override fun parsePersistentObject(cursor: Cursor): Course {
val isActive = try {
cursor.getInt(DbStructureEnrolledAndFeaturedCourses.Column.IS_ACTIVE) > 0
} catch (exception: Exception) {
//it can be null before migration --> default active
true
}
return Course(
id = cursor.getLong(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_ID),
title = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.TITLE),
cover = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.COVER_LINK),
lastStepId = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.LAST_STEP_ID),
certificate = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.CERTIFICATE),
workload = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.WORKLOAD),
courseFormat = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_FORMAT),
targetAudience = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.TARGET_AUDIENCE),
summary = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.SUMMARY),
intro = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_LINK_VIMEO),
language = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.LANGUAGE),
lastDeadline = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.LAST_DEADLINE),
description = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.DESCRIPTION),
instructors = DbParseHelper.parseStringToLongArray(cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.INSTRUCTORS)),
requirements = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.REQUIREMENTS),
enrollment = cursor.getInt(DbStructureEnrolledAndFeaturedCourses.Column.ENROLLMENT),
sections = DbParseHelper.parseStringToLongArray(cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.SECTIONS)),
introVideoId = cursor.getLong(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_VIDEO_ID),
slug = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.SLUG),
scheduleLink = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LINK),
scheduleLongLink = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LONG_LINK),
beginDate = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.BEGIN_DATE),
endDate = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.END_DATE),
learnersCount = cursor.getLong(DbStructureEnrolledAndFeaturedCourses.Column.LEARNERS_COUNT),
progress = cursor.getString(DbStructureEnrolledAndFeaturedCourses.Column.PROGRESS),
rating = cursor.getDouble(DbStructureEnrolledAndFeaturedCourses.Column.AVERAGE_RATING),
reviewSummary = cursor.getInt(DbStructureEnrolledAndFeaturedCourses.Column.REVIEW_SUMMARY),
isActive = isActive
)
}
public override fun getContentValues(course: Course): ContentValues {
val values = ContentValues()
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LAST_STEP_ID, course.lastStepId)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_ID, course.id)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SUMMARY, course.summary)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.COVER_LINK, course.cover)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_LINK_VIMEO, course.intro)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.TITLE, course.title)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LANGUAGE, course.language)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LAST_DEADLINE, course.lastDeadline)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.DESCRIPTION, course.description)
val instructorsParsed = DbParseHelper.parseLongArrayToString(course.instructors)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.INSTRUCTORS, instructorsParsed)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.REQUIREMENTS, course.requirements)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.ENROLLMENT, course.enrollment)
val sectionsParsed = DbParseHelper.parseLongArrayToString(course.sections)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SECTIONS, sectionsParsed)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.WORKLOAD, course.workload)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.COURSE_FORMAT, course.courseFormat)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.TARGET_AUDIENCE, course.targetAudience)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.CERTIFICATE, course.certificate)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SLUG, course.slug)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LINK, course.scheduleLink)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.SCHEDULE_LONG_LINK, course.scheduleLongLink)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.BEGIN_DATE, course.beginDate)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.END_DATE, course.endDate)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.IS_ACTIVE, course.isActive)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.LEARNERS_COUNT, course.learnersCount)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.PROGRESS, course.progress)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.AVERAGE_RATING, course.rating)
values.put(DbStructureEnrolledAndFeaturedCourses.Column.REVIEW_SUMMARY, course.reviewSummary)
val video = course.introVideo
if (video != null) {
values.put(DbStructureEnrolledAndFeaturedCourses.Column.INTRO_VIDEO_ID, video.id)
}
return values
}
public override fun getDbName() = tableName
public override fun getDefaultPrimaryColumn() = DbStructureEnrolledAndFeaturedCourses.Column.COURSE_ID
public override fun getDefaultPrimaryValue(persistentObject: Course) = persistentObject.id.toString()
override fun get(whereColumnName: String, whereValue: String): Course? {
val course = super.get(whereColumnName, whereValue)
addInnerObjects(course)
return course
}
override fun getAllWithQuery(query: String, whereArgs: Array<String>?): List<Course> {
val courseList = super.getAllWithQuery(query, whereArgs)
for (course in courseList) {
addInnerObjects(course)
}
return courseList
}
private fun addInnerObjects(course: Course?) {
if (course == null) return
val video = cachedVideoDao.get(DbStructureCachedVideo.Column.VIDEO_ID, course.introVideoId.toString())
if (video != null) {
val dbVideoUrls = externalVideoUrlIDao
.getAll(DbStructureVideoUrl.Column.videoId, course.introVideoId.toString())
val videoUrls = dbVideoUrls.toVideoUrls()
course.introVideo = transformCachedVideoToRealVideo(video, videoUrls)
}
}
override fun insertOrUpdate(persistentObject: Course?) {
super.insertOrUpdate(persistentObject)
val video = persistentObject?.introVideo ?: return
val cachedVideo = video.transformToCachedVideo() //it is cached, but not stored video.
cachedVideoDao.insertOrUpdate(cachedVideo)
//add all urls for video
val videoUrlList = video.urls
if (videoUrlList?.isNotEmpty() == true) {
externalVideoUrlIDao.remove(DbStructureVideoUrl.Column.videoId, video.id.toString())
videoUrlList.forEach { videoUrl ->
externalVideoUrlIDao.insertOrUpdate(videoUrl.toDbUrl(video.id))
}
}
}
//// FIXME: 17.02.16 refactor this hack
private fun transformCachedVideoToRealVideo(cachedVideo: CachedVideo?, videoUrls: List<VideoUrl>?): Video? {
var realVideo: Video? = null
if (cachedVideo != null) {
val resultUrls = if (videoUrls?.isNotEmpty() == true) {
videoUrls
} else {
listOf(VideoUrl(cachedVideo.url, cachedVideo.quality))
}
realVideo = Video(id = cachedVideo.videoId, thumbnail = cachedVideo.thumbnail, urls = resultUrls)
}
return realVideo
}
}
| 0 | null |
0
| 1 |
256a90051eefe8db83f7053914004905bbb1f8d0
| 9,818 |
stepik-android
|
Apache License 2.0
|
src/main/kotlin/me/camdenorrb/kportals/KPortals.kt
|
camdenorrb
| 85,821,749 | false | null |
package me.camdenorrb.kportals
import com.google.common.io.ByteStreams
import com.sxtanna.korm.Korm
import me.camdenorrb.kportals.cache.SelectionCache
import me.camdenorrb.kportals.commands.PortalCmd
import me.camdenorrb.kportals.commands.sub.*
import me.camdenorrb.kportals.ext.readJson
import me.camdenorrb.kportals.listeners.PlayerListener
import me.camdenorrb.kportals.portal.LegacyPortal
import me.camdenorrb.kportals.portal.Portal
import me.camdenorrb.minibus.MiniBus
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemFlag
import org.bukkit.inventory.ItemStack
import org.bukkit.plugin.java.JavaPlugin
import java.io.File
/**
* Created by camdenorrb on 3/20/17.
*/
// TODO: Link portals
class KPortals : JavaPlugin() {
val korm = Korm()
val miniBus: MiniBus = MiniBus()
val selectionCache = SelectionCache(this)
val subCmds = mutableSetOf(CreatePortalCmd(), RemovePortalCmd(), ListPortalCmd(), SetArgsCmd(), SetTypeCmd(), SelectCmd(), TypeCmd(), ArgsCmd())
lateinit var portals: MutableSet<Portal>
private set
val portalsFile by lazy {
File(dataFolder, "portals.korm")
}
val selectionItem = ItemStack(Material.DIAMOND_AXE).apply {
itemMeta = itemMeta?.apply {
setDisplayName("${ChatColor.AQUA}Portal Selection Item")
lore = listOf("KPortals")
addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_UNBREAKABLE)
isUnbreakable = true // To allow us to use .equals since it checks durability
}
}
override fun onLoad() {
instance = this
}
override fun onEnable() {
/*
korm.pushWith<Location> { writer, data ->
data ?: return@pushWith
writer.writeName("worldUUID")
writer.writeData(data.world.uid)
writer.writeName("vector")
writer.writeData(data.toVector())
if (data.yaw != 0.0F) {
writer.writeName("yaw")
writer.writeData(data.yaw)
}
if (data.pitch != 0.0F) {
writer.writeName("pitch")
writer.writeData(data.pitch)
}
}
korm.pullWith<Location> { reader, types ->
val worldUUID = types.find { it.key.data == "worldUUID" }?.let { reader.mapData<UUID>(it.asBase()?.data) } ?: return@pullWith null
val vector = types.find { it.key.data == "vector" }?.let { reader.mapData<Vector>(it.asBase()?.data) } ?: return@pullWith null
val yaw = types.find { it.key.data == "yaw" }?.let { reader.mapData<Float>(it.asBase()?.data) } ?: 0.0F
val pitch = types.find { it.key.data == "pitch" }?.let { reader.mapData<Float>(it.asBase()?.data) } ?: 0.0F
val world = server.getWorld(worldUUID) ?: return@pullWith null
vector.toLocation(world, yaw, pitch)
}
*/
// Load legacy data, needs to be done onEnable
val legacyPortalFile = File(dataFolder, "portals.json")
if (!portalsFile.exists() && legacyPortalFile.exists()) {
println("Loading legacy data")
portals = legacyPortalFile.readJson(LegacyPortal.Portals()).portals.mapNotNull { legacyPortal ->
val modernPortal = legacyPortal.modernize()
if (modernPortal == null) {
println("Could not modernize ${legacyPortal.name}!")
}
modernPortal
}.toMutableSet()
korm.push(portals, portalsFile)
println("Done loading legacy data")
}
else if (portalsFile.exists()) {
portals = korm.pull(portalsFile).toList<Portal>().mapTo(mutableSetOf()) {
it.copy() // Copy so delegates don't get fucked up
}
}
else {
portals = mutableSetOf()
}
// Register the main command.
getCommand("portal")!!.setExecutor(PortalCmd(this))
// Register PlayerListener
val playerListener = PlayerListener(this)
miniBus.register(playerListener)
server.pluginManager.registerEvents(playerListener, this)
// Enable BungeeCord plugin channel.
server.messenger.registerOutgoingPluginChannel(this, "BungeeCord")
// Enable modules
selectionCache.enable()
}
override fun onDisable() {
// Clean up
portals.clear()
subCmds.clear()
miniBus.cleanUp()
// Disable modules
selectionCache.disable()
}
fun sendPlayerToServer(player: Player, toServer: String) {
val out = ByteStreams.newDataOutput().apply {
writeUTF("Connect")
writeUTF(toServer)
}
player.sendPluginMessage(instance, "BungeeCord", out.toByteArray())
}
companion object {
lateinit var instance: KPortals
private set
}
}
| 0 |
Kotlin
|
0
| 2 |
d2d7312596758972bfbe89c120a0d176359e322a
| 4,303 |
KPortals
|
MIT License
|
winanalytics-annotations/src/main/java/com/winfooz/Value.kt
|
Winfooz
| 151,945,865 | false | null |
package com.winfooz
/**
* Project: MyApplication6 Created: November 15, 2018
*
* @author Mohamed Hamdan
*/
@Retention(AnnotationRetention.SOURCE)
@Target
@MustBeDocumented
annotation class Value(
val value: String
)
| 3 | null |
1
| 24 |
723fad6458dd117bb6f1fd5b7bded3891deedd29
| 225 |
WinAnalytics
|
MIT License
|
protocol/sign/src/main/kotlin/com/walletconnect/sign/json_rpc/model/JsonRpcMapper.kt
|
WalletConnect
| 435,951,419 | false | null |
@file:JvmSynthetic
package com.walletconnect.sign.json_rpc.model
import com.walletconnect.android.internal.common.json_rpc.model.JsonRpcHistoryRecord
import com.walletconnect.android.internal.common.model.Expiry
import com.walletconnect.foundation.common.model.Topic
import com.walletconnect.sign.common.model.Request
import com.walletconnect.sign.common.model.vo.clientsync.session.SignRpc
import com.walletconnect.sign.common.model.vo.clientsync.session.params.SignParams
@JvmSynthetic
internal fun SignRpc.SessionRequest.toRequest(entry: JsonRpcHistoryRecord): Request<String> =
Request(
entry.id,
Topic(entry.topic),
params.request.method,
params.chainId,
params.request.params,
if (params.request.expiryTimestamp != null) Expiry(params.request.expiryTimestamp) else null,
transportType = entry.transportType
)
@JvmSynthetic
internal fun JsonRpcHistoryRecord.toRequest(params: SignParams.SessionRequestParams): Request<SignParams.SessionRequestParams> =
Request(
id,
Topic(topic),
method,
params.chainId,
params,
transportType = transportType
)
@JvmSynthetic
internal fun JsonRpcHistoryRecord.toRequest(params: SignParams.SessionAuthenticateParams): Request<SignParams.SessionAuthenticateParams> =
Request(
id,
Topic(topic),
method,
null,
params,
Expiry(params.expiryTimestamp),
transportType = transportType
)
@JvmSynthetic
internal fun SignRpc.SessionAuthenticate.toRequest(entry: JsonRpcHistoryRecord): Request<SignParams.SessionAuthenticateParams> =
Request(
entry.id,
Topic(entry.topic),
entry.method,
null,
params,
Expiry(params.expiryTimestamp),
transportType = entry.transportType
)
| 78 | null |
71
| 199 |
e373c535d7cefb2f932368c79622ac05763b411a
| 1,848 |
WalletConnectKotlinV2
|
Apache License 2.0
|
jvm/src/main/kotlin/com/github/lagiilein/playground/jvm/MagicSquare.kt
|
Lagiilein
| 388,163,657 | false | null |
package com.github.lagiilein.playground.jvm
object MagicSquare {
/**
* Check if a two-dimensional list is a magic square.
*
* @param square two-dimensional list, which will be checked.
* @return true if provided parameter square is a magic square.
*/
fun isSquareMagic(square: List<List<Int>>): Boolean {
require(square.isNotEmpty())
val n = square.size
// check numbers
if (!checkNumbers(square)) return false
// check row's sizes
for (row in square) {
if (row.size != n) {
return false
}
}
var magicConstant: Int? = null
// check if rows sum up to magic constant
for (row in square) {
val sum = row.sum()
if (magicConstant == null) {
magicConstant = sum
} else if (sum != magicConstant) {
return false
}
}
check(magicConstant != null)
// check if columns sum up to magic constant
for (i in 0 until n) {
val sum = square.sumOf { it[i] }
if (sum != magicConstant) {
return false
}
}
// check left to right diagonal
fun leftToRightDiagonalCheck(): Boolean {
var columnCursor = 0
val sum = square.sumOf {
val pos = columnCursor
columnCursor++
return@sumOf it[pos]
}
if (sum != magicConstant) {
return false
}
return true
}
// check right to left diagonal
fun rightToLeftDiagonalCheck(): Boolean {
var columnCursor = n - 1
val sum = square.sumOf {
val pos = columnCursor
columnCursor--
return@sumOf it[pos]
}
if (sum != magicConstant) {
return false
}
return true
}
return leftToRightDiagonalCheck() && rightToLeftDiagonalCheck()
}
private fun checkNumbers(square: List<List<Int>>): Boolean {
val n = square.size
val numbers = hashSetOf<Int>()
for (i in 0 until n) {
val item = square[i / n][i % n]
if (item <= 0) return false
if (item > n * n) return false
if (numbers.contains(item)) return false
numbers += item
}
return true
}
}
| 0 |
Kotlin
|
0
| 0 |
a1bf2620f657994fb8193fd54c3a0ddfc95caeb7
| 2,518 |
playground.kt
|
MIT License
|
mobile/src/main/java/com/aptopayments/mobile/repository/verification/remote/entities/request/FinishVerificationRequest.kt
|
ShiftFinancial
| 130,093,227 | false |
{"Kotlin": 696648}
|
package com.aptopayments.mobile.repository.verification.remote.entities.request
import com.google.gson.annotations.SerializedName
import java.io.Serializable
internal data class FinishVerificationRequest(
@SerializedName("secret")
val secret: String
) : Serializable
| 0 |
Kotlin
|
0
| 5 |
f79b3c532ae2dfec8e571b315401ef03d8e507f9
| 279 |
shift-sdk-android
|
MIT License
|
library/src/commonMain/kotlin/com/lightningkite/kiteui/locale/LocalTimeRender.kt
|
lightningkite
| 778,386,343 | false |
{"Kotlin": 2224994, "Swift": 7449, "Ruby": 4925, "CSS": 4562, "HTML": 4084, "HCL": 880, "JavaScript": 302, "Objective-C": 142, "C": 104, "Shell": 49}
|
package com.lightningkite.kiteui.locale
import kotlinx.datetime.*
enum class RenderSize { Numerical, Abbreviation, Full }
expect fun LocalDate.renderToString(size: RenderSize = RenderSize.Full, includeWeekday: Boolean = false, includeYear: Boolean = true, includeEra: Boolean = false): String
expect fun LocalTime.renderToString(size: RenderSize = RenderSize.Full): String
expect fun LocalDateTime.renderToString(size: RenderSize = RenderSize.Full, includeWeekday: Boolean = false, includeYear: Boolean = true, includeEra: Boolean = false): String
fun Instant.renderToString(size: RenderSize = RenderSize.Full, zone: TimeZone = TimeZone.currentSystemDefault(), includeWeekday: Boolean = false, includeYear: Boolean = true, includeEra: Boolean = false): String
= toLocalDateTime(zone).renderToString(size, includeWeekday = includeWeekday, includeYear = includeYear, includeEra = includeEra)
fun Instant.renderDateToString(size: RenderSize = RenderSize.Full, zone: TimeZone = TimeZone.currentSystemDefault(), includeWeekday: Boolean = false, includeYear: Boolean = true, includeEra: Boolean = false): String
= toLocalDateTime(zone).date.renderToString(size, includeWeekday = includeWeekday, includeYear = includeYear, includeEra = includeEra)
fun Instant.renderTimeToString(size: RenderSize = RenderSize.Full, zone: TimeZone = TimeZone.currentSystemDefault()): String
= toLocalDateTime(zone).time.renderToString(size)
expect fun TimeZone.renderToString(size: RenderSize = RenderSize.Full): String
expect fun DayOfWeek.renderToString(size: RenderSize = RenderSize.Full): String
| 3 |
Kotlin
|
0
| 2 |
58ee76ab3e8e7cab71e65a18c302367c6a641da5
| 1,592 |
kiteui
|
Apache License 2.0
|
api/src/main/java/io/realworld/api/models/requests/UserUpdateRequest.kt
|
coding-blocks-archives
| 320,795,559 | false |
{"Kotlin": 40116}
|
package io.realworld.api.models.requests
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import io.realworld.api.models.entities.UserUpdateData
@JsonClass(generateAdapter = true)
data class UserUpdateRequest(
@Json(name = "user")
val user: UserUpdateData
)
| 5 |
Kotlin
|
22
| 48 |
0e8c86804623445f895ac048a53b10d4f720f778
| 285 |
Conduit_Android_Kotlin
|
MIT License
|
sdk/src/jsMain/kotlin/lib/module/Media.kt
|
zimoyin
| 675,280,596 | false |
{"Kotlin": 306501, "JavaScript": 18388, "HTML": 15259}
|
package lib.module
@JsName("media")
external object Media {
/**
* 扫描文件以添加到媒体库中
* @param path 文件路径
*/
fun scanFile(path: String): Unit
/**
* 播放音乐
* @param path 音乐文件路径
* @param volume 音量 (可选)
* @param looping 是否循环播放 (可选)
*/
fun playMusic(path: String, volume: Double? = definedExternally, looping: Boolean? = definedExternally): Unit
/**
* 跳转到音乐的指定位置
* @param msec 毫秒位置
*/
fun musicSeekTo(msec: Int): Unit
/**
* 暂停音乐
*/
fun pauseMusic(): Unit
/**
* 恢复音乐播放
*/
fun resumeMusic(): Unit
/**
* 停止音乐
*/
fun stopMusic(): Unit
/**
* 检查音乐是否正在播放
* @return 是否正在播放
*/
fun isMusicPlaying(): Boolean
/**
* 获取音乐总时长
* @return 音乐时长(毫秒)
*/
fun getMusicDuration(): Int
/**
* 获取音乐当前播放位置
* @return 当前播放位置(毫秒)
*/
fun getMusicCurrentPosition(): Int
}
| 0 |
Kotlin
|
5
| 10 |
aa85a176280ce3a17a59454fbbe6bddd56044335
| 939 |
Autojsx.WIFI
|
Apache License 2.0
|
data-store/src/main/java/dev/pablodiste/datastore/StoreRequest.kt
|
pablodiste
| 426,741,932 | false | null |
package dev.pablodiste.datastore
data class StoreRequest<K>(
/**
* This key identifies a request to the fetcher. Same fetcher calls should have the same key.
* The key should implement toString, hashCode and equals methods.
*/
val key: K,
/**
* When true, the store requests a fetch to update the source of truth.
*/
val refresh: Boolean = true,
/**
* When true, if no data is found on the source of truth, a fetch is requested.
*/
val fetchWhenNoDataFound: Boolean = true,
/**
* When true, the fetcher ignores any rule that limit calls and perform the fetch anyways.
*/
val forceFetch: Boolean = false,
/**
* When true, the store will emit NoData states, caused by rate limiters and other scenarios
*/
val emitNoDataStates: Boolean = false,
/**
* When true, the store will emit Loading when executing a fetcher call
*/
val emitLoadingStates: Boolean = false
)
| 0 |
Kotlin
|
0
| 2 |
723c7d22c421e36447b7dbf4499f2137bf7b4f6a
| 979 |
data-store
|
MIT License
|
sdk/src/main/java/com/apphud/sdk/ApphudUserProperty.kt
|
apphud
| 295,467,889 | false | null |
package com.apphud.sdk
internal const val JSON_NAME_NAME = "name"
internal const val JSON_NAME_VALUE = "value"
internal const val JSON_NAME_SET_ONCE = "set_once"
internal const val JSON_NAME_KIND = "kind"
internal const val JSON_NAME_INCREMENT = "increment"
internal data class ApphudUserProperty(
val key: String,
val value: Any?,
val increment: Boolean = false,
val setOnce: Boolean = false,
val type: String = ""
) {
fun toJSON(): MutableMap<String, Any?>? {
if (increment && value == null) {
return null
}
val jsonParamsString: MutableMap<String, Any?> = mutableMapOf(
JSON_NAME_NAME to key,
JSON_NAME_VALUE to if (value !is Float || value !is Double) value else value as Double,
JSON_NAME_SET_ONCE to setOnce
)
if (value != null) {
jsonParamsString[JSON_NAME_KIND] = type
}
if (increment) {
jsonParamsString[JSON_NAME_INCREMENT] = increment
}
return jsonParamsString
}
}
| 3 |
Kotlin
|
2
| 3 |
b4b8e77e77558c13a63ccd79ed2cb0eb5baee5d1
| 1,053 |
ApphudSDK-Android
|
MIT License
|
presentation/src/main/java/com/grekov/translate/presentation/core/view/activity/BaseActivity.kt
|
sgrekov
| 111,900,693 | false | null |
package com.grekov.translate.presentation.core.view.activity
import android.content.Intent
import android.os.Bundle
import android.support.annotation.CallSuper
import android.support.annotation.LayoutRes
import android.support.v7.app.AppCompatActivity
import butterknife.ButterKnife
import com.grekov.translate.presentation.TranslateApp
import com.grekov.translate.presentation.core.di.component.AppComponent
import timber.log.Timber
abstract class BaseActivity : AppCompatActivity() {
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
setupComponent((application as TranslateApp).component())
super.onCreate(savedInstanceState)
if (layoutId != -1) {
setContentView(layoutId)
}
ButterKnife.bind(this)
}
@get:LayoutRes
protected abstract val layoutId: Int
@CallSuper
override fun onRestart() {
super.onRestart()
Timber.d("onRestart: ")
}
@CallSuper
public override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
Timber.d("onSaveInstanceState: ")
}
@CallSuper
override fun onStop() {
super.onStop()
Timber.d("onStop: ")
}
@CallSuper
override fun onDestroy() {
super.onDestroy()
Timber.d("onDestroy: ")
}
/**
* setup dagger component with AppComponent and object specific module (called source onCreate)
*
* @param appComponent
*/
protected abstract fun setupComponent(appComponent: AppComponent)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
Timber.d("onActivityResult: ")
super.onActivityResult(requestCode, resultCode, data)
}
@CallSuper
override fun onPause() {
super.onPause()
Timber.d("onPause: ")
}
@CallSuper
override fun onResume() {
super.onResume()
Timber.d("onResume: ")
}
@CallSuper
override fun onStart() {
super.onStart()
Timber.d("onStart: ")
}
}
| 0 | null |
4
| 22 |
24a1a1955ca901d4bf5ff08ff2f8e3eb2719c825
| 2,080 |
Translater
|
Apache License 2.0
|
compose/src/main/java/androidx/ui/material/studies/rally/AccountsScreen.kt
|
shriharshs
| 254,141,570 | true |
{"Kotlin": 497110, "Shell": 5712, "HTML": 1266}
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.ui.material.studies.rally
import androidx.compose.Composable
import androidx.ui.foundation.Text
import androidx.ui.foundation.VerticalScroller
import androidx.ui.graphics.Color
import androidx.ui.layout.Column
import androidx.ui.layout.LayoutGravity
import androidx.ui.layout.LayoutHeight
import androidx.ui.layout.LayoutPadding
import androidx.ui.layout.LayoutWidth
import androidx.ui.layout.Spacer
import androidx.ui.layout.Stack
import androidx.ui.material.MaterialTheme
import androidx.ui.material.Card
import androidx.ui.unit.dp
/**
* The Accounts screen.
*/
@Composable
fun AccountsBody() {
VerticalScroller {
Column {
Stack(LayoutPadding(16.dp)) {
val accountsProportion = listOf(0.595f, 0.045f, 0.095f, 0.195f, 0.045f)
val colors = listOf(0xFF1EB980, 0xFF005D57, 0xFF04B97F, 0xFF37EFBA, 0xFFFAFFBF)
.map { Color(it) }
AnimatedCircle(
LayoutHeight(300.dp) + LayoutGravity.Center + LayoutWidth.Fill,
accountsProportion,
colors
)
Column(modifier = LayoutGravity.Center) {
Text(
text = "Total",
style = MaterialTheme.typography.body1,
modifier = LayoutGravity.Center
)
Text(
text = "$12,132.49",
style = MaterialTheme.typography.h2,
modifier = LayoutGravity.Center
)
}
}
Spacer(LayoutHeight(10.dp))
Card {
Column(modifier = LayoutPadding(12.dp)) {
UserData.accounts.forEach { account ->
AccountRow(
name = account.name,
number = account.number,
amount = account.balance,
color = account.color
)
}
}
}
}
}
}
| 0 | null |
0
| 0 |
cb5768a667248fd7d2ce1dc3beea55bd624cf3d7
| 2,765 |
compose-playground
|
MIT License
|
app/src/main/java/com/weatherxm/data/network/interceptor/AuthTokenAuthenticator.kt
|
WeatherXM
| 728,657,649 | false |
{"Kotlin": 1138662}
|
package com.weatherxm.data.network.interceptor
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import arrow.core.Either
import arrow.core.flatMap
import com.weatherxm.R
import com.weatherxm.data.Failure
import com.weatherxm.data.datasource.CacheAuthDataSource
import com.weatherxm.data.datasource.DatabaseExplorerDataSource
import com.weatherxm.data.map
import com.weatherxm.data.network.AccessTokenBody
import com.weatherxm.data.network.AuthService
import com.weatherxm.data.network.AuthToken
import com.weatherxm.data.network.RefreshBody
import com.weatherxm.data.network.interceptor.ApiRequestInterceptor.Companion.AUTH_HEADER
import com.weatherxm.data.path
import com.weatherxm.data.services.CacheService
import com.weatherxm.ui.Navigator
import com.weatherxm.ui.common.Contracts
import com.weatherxm.util.WidgetHelper
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import timber.log.Timber
@Suppress("LongParameterList")
class AuthTokenAuthenticator(
private val authService: AuthService,
private val cacheAuthDataSource: CacheAuthDataSource,
private val databaseExplorerDataSource: DatabaseExplorerDataSource,
private val cacheService: CacheService,
private val navigator: Navigator,
private val context: Context,
private val widgetHelper: WidgetHelper
) : Authenticator {
private lateinit var refreshJob: Deferred<AuthToken?>
override fun authenticate(route: Route?, response: Response): Request? {
// The original request
val request = response.request
Timber.d("[${request.path()}] Status: ${response.code}. Invoking authenticator.")
return runBlocking {
if (!this@AuthTokenAuthenticator::refreshJob.isInitialized || !refreshJob.isActive) {
refreshJob = async {
refresh(request)
.onLeft {
Timber.w("[${request.path()}] Failed to authenticate. Forced Logout.")
runBlocking {
cacheService.getAuthToken().onRight {
authService.logout(AccessTokenBody(it.access))
}
databaseExplorerDataSource.deleteAll()
cacheService.clearAll()
widgetHelper.getWidgetIds().onRight {
val intent = Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
val ids = it.map { id ->
id.toInt()
}
intent.putExtra(
AppWidgetManager.EXTRA_APPWIDGET_IDS,
ids.toIntArray()
)
intent.putExtra(Contracts.ARG_IS_CUSTOM_APPWIDGET_UPDATE, true)
intent.putExtra(Contracts.ARG_WIDGET_SHOULD_LOGIN, true)
context.sendBroadcast(intent)
}
navigator.showLogin(
context,
true,
context.getString(R.string.session_expired)
)
}
}
.getOrNull()
}
}
val newAuthToken = refreshJob.await()
newAuthToken?.let {
retryWithAccessToken(request, it.access)
}
}
}
private fun getAuthToken(): Either<Failure, AuthToken> = runBlocking {
cacheAuthDataSource.getAuthToken()
.flatMap { authToken ->
if (!authToken.isRefreshTokenValid()) {
Either.Left(Failure.InvalidRefreshTokenError)
} else {
Either.Right(authToken)
}
}
}
private fun refresh(request: Request): Either<Failure, AuthToken> {
Timber.d("[${request.path()}] Trying refresh & retry.")
return getAuthToken()
.onLeft {
Timber.d("[${request.path()}] Invalid refresh token. Cannot refresh.")
}
.flatMap { authToken ->
Timber.d("[${request.path()}] Trying to refresh token.")
runBlocking {
authService.refresh(RefreshBody(authToken.refresh)).map()
.onLeft {
Timber.d("[${request.path()}] Token refresh failed.")
}
.onRight {
Timber.d("[${request.path()}] Token refresh success.")
}
}
}
}
private fun retryWithAccessToken(request: Request, accessToken: String): Request {
Timber.d("[${request.path()}] Retrying with new access token.")
return request.newBuilder()
.header(AUTH_HEADER, "Bearer $accessToken")
.build()
}
}
| 3 |
Kotlin
|
2
| 9 |
fa770fab768969ced5aed1d8e8a2985977a7391f
| 5,390 |
wxm-android
|
Apache License 2.0
|
app/src/main/java/github/alexzhirkevich/studentbsuby/dao/NewsDao.kt
|
geugenm
| 689,629,461 | false | null |
package github.alexzhirkevich.studentbsuby.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy.Companion.REPLACE
import androidx.room.Query
import github.alexzhirkevich.studentbsuby.data.models.News
import github.alexzhirkevich.studentbsuby.data.models.NewsContent
@Dao
interface NewsDao {
@Insert(onConflict = REPLACE)
suspend fun insert(news: News)
@Insert(onConflict = REPLACE)
suspend fun insertContent(content: NewsContent)
@Query("SELECT * FROM News ORDER BY id DESC")
suspend fun getAll() : List<News>
@Query("SELECT * FROM NewsContent WHERE id = :id LIMIT 1")
suspend fun getContent(id : Int) : NewsContent
@Query("DELETE FROM NewsContent WHERE id = :id")
suspend fun clearContent(id : Int)
@Query("DELETE FROM NEWS")
suspend fun clear()
}
| 3 | null |
0
| 6 |
a89ff407beb83aa9a6fb5c21c319e6bf84e75e2a
| 848 |
student-bsu-by
|
MIT License
|
src/main/kotlin/com/odenizturker/event/model/EnrollmentRequestModel.kt
|
gather-me
| 675,288,438 | false | null |
package com.odenizturker.event.model
import com.odenizturker.event.model.response.EventModel
import java.time.Instant
data class EnrollmentRequestModel(
val event: EventModel,
val users: List<UserModel>
)
data class InvitationModel(
val id: Long,
val event: EventModel,
val user: UserModel,
val date: Instant
)
| 0 |
Kotlin
|
0
| 0 |
ff1c65a78dd2f74eb45a976510153a030fc68906
| 338 |
service-event
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/Brightness5Sharp.kt
|
JetBrains
| 93,250,841 | false | null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/Brightness5Sharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val Brightness5Sharp: SvgIconComponent
| 12 |
Kotlin
|
5
| 983 |
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
| 214 |
kotlin-wrappers
|
Apache License 2.0
|
Jetchat/app/src/main/java/com/example/compose/jetchat/components/AnimatingFabContent.kt
|
markgray
| 872,334,021 | false |
{"Kotlin": 1267101}
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("UnusedImport")
package com.example.compose.jetchat.components
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.Transition
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.outlined.Chat
import androidx.compose.material.icons.outlined.Create
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Measurable
import androidx.compose.ui.layout.MeasureScope
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.util.lerp
import com.example.compose.jetchat.R
import com.example.compose.jetchat.profile.ProfileFab
import com.example.compose.jetchat.profile.ProfileScreen
import kotlin.math.roundToInt
/**
* A layout that shows an icon and a text element used as the content for a FAB that extends with
* an animation. We start by initializing our [ExpandableFabStates] variable `val currentState` to
* [ExpandableFabStates.Extended] if our [Boolean] parameter [extended] is `true` or to
* [ExpandableFabStates.Collapsed] if it is `false`. We initialize our [Transition] of
* [ExpandableFabStates] variable `val transition` by using the [updateTransition] method to set up
* a [Transition], with `currentState` the `targetState` that it uses to be updated. When
* `currentState` changes, [Transition] will run all of its child animations towards their target
* values specified for the new `targetState`. We initialize our [Float] variable `val textOpacity`
* by using the [Transition.animateFloat] method of `transition` to Create a Float animation as a
* part of `transition` (This means the states of this animation will be managed by the [Transition]).
* Its `transitionSpec` argument is a lambda that uses different [tween] instances depending on
* whether the `targetState` of `transition` is [ExpandableFabStates.Collapsed] with different
* `delayMillis` but the same `durationMillis`. The `targetValueByState` lambda argument of the
* [Transition.animateFloat] uses 0f as its value for the `targetState` [ExpandableFabStates.Collapsed]
* and 1f as its value for the `targetState` [ExpandableFabStates.Extended].
*
* We initialize our [Float] variable `val fabWidthFactor` by using the [Transition.animateFloat]
* method of `transition` to Create a Float animation as a part of `transition`. Its `transitionSpec`
* argument is a lambda that uses identical [tween] instances whether the `targetState` of `transition`
* is [ExpandableFabStates.Collapsed] or [ExpandableFabStates.Extended]. The `targetValueByState`
* lambda argument of the [Transition.animateFloat] uses 0f as its value for the `targetState`
* [ExpandableFabStates.Collapsed] and 1f as its value for the `targetState` [ExpandableFabStates.Extended].
*
* Finally our root Composable is an [IconAndTextRow] whose `icon` argument is our [icon] parameter,
* whose `text` argument is our [text] parameter, whose `opacityProgress` argument is a lambda whose
* value is our [Transition] animated variable `textOpacity`, whose `widthProgress` argument is a
* lambda whose value is our [Transition] animated variable `fabWidthFactor`, and whose `modifier`
* argument is our [modifier] parameter.
*
* @param icon we use this as the `icon` argument of our [IconAndTextRow]. Our caller [ProfileFab]
* calls us with an [Icon] whose `imageVector` is either [Icons.Outlined.Create] if the "user is me"
* or [Icons.AutoMirrored.Outlined.Chat] if it is not.
* @param text we use this as the `text` argument of our [IconAndTextRow]. Our caller [ProfileFab]
* calls us with a [Text] that displays the [String] with resource ID [R.string.edit_profile]
* ("Edit Profile") if the "user is me" or the [String] with resource ID [R.string.message]
* ("Message") if it is not.
* @param modifier a [Modifier] instance that our caller can use to modify our appearance and/or
* behavior. Our caller [ProfileFab] does not pass one so is the empty, default, or starter
* [Modifier] that contains no elements is used instead.
* @param extended a [Boolean] flag that indicates whether our [ExpandableFabStates] `currentState`
* is [ExpandableFabStates.Extended] (`true`) or [ExpandableFabStates.Collapsed] (`false`). We use
* this to animate the `fabWidthFactor` that we pass in a lambda as the `widthProgress` argument of
* our [IconAndTextRow]. It uses it to linearly interpret between the `initialWidth`, and the
* `expandedWidth` to determine the `width` it uses when using [layout] to place the [Icon] and
* [Text] it renders. Our caller [ProfileFab] passes us its `extended` parameter, which its caller
* [ProfileScreen] passes it, which is a [derivedStateOf] the [ScrollState] it uses to make its
* [Column] able to `verticalScroll`, with a [ScrollState.value] of 0 as `true`.
*/
@Composable
fun AnimatingFabContent(
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
modifier: Modifier = Modifier,
extended: Boolean = true
) {
val currentState = if (extended) ExpandableFabStates.Extended else ExpandableFabStates.Collapsed
val transition: Transition<ExpandableFabStates> = updateTransition(
targetState = currentState,
label = "fab_transition"
)
val textOpacity: Float by transition.animateFloat(
transitionSpec = {
if (targetState == ExpandableFabStates.Collapsed) {
tween(
easing = LinearEasing,
durationMillis = (transitionDuration / 12f * 5).roundToInt() // 5 / 12 frames
)
} else {
tween(
easing = LinearEasing,
delayMillis = (transitionDuration / 3f).roundToInt(), // 4 / 12 frames
durationMillis = (transitionDuration / 12f * 5).roundToInt() // 5 / 12 frames
)
}
},
label = "fab_text_opacity"
) { state: ExpandableFabStates ->
if (state == ExpandableFabStates.Collapsed) {
0f
} else {
1f
}
}
val fabWidthFactor: Float by transition.animateFloat(
transitionSpec = {
if (targetState == ExpandableFabStates.Collapsed) {
tween(
easing = FastOutSlowInEasing,
durationMillis = transitionDuration
)
} else {
tween(
easing = FastOutSlowInEasing,
durationMillis = transitionDuration
)
}
},
label = "fab_width_factor"
) { state ->
if (state == ExpandableFabStates.Collapsed) {
0f
} else {
1f
}
}
// Deferring reads using lambdas instead of Floats here can improve performance,
// preventing recompositions.
IconAndTextRow(
icon = icon,
text = text,
opacityProgress = { textOpacity },
widthProgress = { fabWidthFactor },
modifier = modifier
)
}
/**
* This is the animated Composable content that [AnimatingFabContent] animates for [ProfileFab] to
* supply to [ProfileScreen] (the buck stops here). Our root Composable is a [Layout] which it used
* to measure and position one [layout] child. Its `modifier` argument is our [Modifier] parameter
* [modifier], and its `content` argument (chidren to be composed) are our Composable lambda parameter
* [icon], and a [Box] whose `modifier` argument is a [Modifier.graphicsLayer] that uses the [Float]
* value returned by our [opacityProgress] lambda parameter to animate the `alpha` of its `content`
* which is our [text] Composable lambda. In the [MeasureScope] block we use the entry at index 0 in
* the `measurables` [List] of [Measurable]'s passed the block to call its [Measurable.measure]
* method with the `constraints` [Constraints] passed the block to initialize our [Placeable]
* variable `val iconPlaceable` (the first child of the `content` argument of the [Layout]), and we
* use the entry at index 1 in the `measurables` [List] of [Measurable]'s passed the block to call
* its [Measurable.measure] method with the `constraints` [Constraints] passed the block to initialize
* our [Placeable] variable `val textPlaceable` (the second child of the `content` argument of the
* [Layout]). We initialize our [Int] variable `val height` to the [Constraints.maxHeight] property
* of the `constraints` passed the block, and our [Float] variable `val initialWidth` to the [Float]
* version of `height`. We initialize our [Float] variable `val iconPadding` to one half the quantity
* `initialWidth` minus the [Placeable.width] property of `iconPlaceable`. We initialize our [Float]
* variable `val expandedWidth` to the [Placeable.width] property of of `iconPlaceable` plus the
* [Placeable.width] property of `textPlaceable` plus 3 times `iconPadding` (this is the full width
* when the [IconAndTextRow] is expanded). We initialize our [Float] variable `val width` using the
* [lerp] method to linearly interpret between `initialWidth` and `expandedWidth` with the fraction
* the value returned by our lambda parameter [widthProgress] between them.
*
* Finally we call [layout] with its `width` argument our `width` variable rounded to [Int], and its
* `height` argument our `height` variable, and in its `placementBlock` we call the `place` method
* of `iconPlaceable` to place it at `x` argument `iconPlaceable` rounded to [Int] and at `y`
* argument one half the [Constraints.maxHeight] property of `constraints` plus one half the
* [Placeable.height] property of `iconPlaceable`, then we call the `place` method of `textPlaceable`
* to place it at `x` argument the [Placeable.width] property of `iconPlaceable` plus 2 times
* `iconPadding` with the quantity rounded to [Int] and at `y` argument one half the
* [Constraints.maxHeight] property of `constraints` plus one half the [Placeable.height] property
* of `textPlaceable`.
*
* @param icon a Composable lambda that displays the [Icon] that [ProfileFab] wants to be displayed
* in its [FloatingActionButton].
* @param text a Composable lambda that displays a [Text] that [ProfileFab] wants to be displayed in
* its [FloatingActionButton].
* @param opacityProgress a lambda that produces an animated [Float] value that we should use as the
* `alpha` value for the [Modifier.graphicsLayer] that we use as the `modifier` of the [Box] holding
* our [text] Composable lambda parameter. [AnimatingFabContent] uses a [Transition] of the current
* [ExpandableFabStates] to animate this between 0f for [ExpandableFabStates.Collapsed] and 1f for
* [ExpandableFabStates.Extended]. The value is passed using a lambda to prevent recompositions.
* @param widthProgress a lambda that produces an animated [Float] value that we should use when
* calculating the `width` argument we use in the call to [layout] which places our [Icon] and
* [Text]. [AnimatingFabContent] uses a [Transition] of the current [ExpandableFabStates] to animate
* this between 0f for [ExpandableFabStates.Collapsed] and 1f for [ExpandableFabStates.Extended].
* The value is passed using a lambda to prevent recompositions.
* @param modifier a [Modifier] instance that our caller can use to modify our appearance and/or
* behavior. Our caller [AnimatingFabContent] calls us with its `modifier` parameter, but since its
* caller [ProfileFab] does not pass it one the empty, default, or starter [Modifier] that contains
* no elements is used instead.
*/
@Composable
private fun IconAndTextRow(
icon: @Composable () -> Unit,
text: @Composable () -> Unit,
opacityProgress: () -> Float, // Lambdas instead of Floats, to defer read
widthProgress: () -> Float,
modifier: Modifier
) {
Layout(
modifier = modifier,
content = {
icon()
Box(
modifier = Modifier.graphicsLayer { alpha = opacityProgress() }
) {
text()
}
}
) { measurables: List<Measurable>, constraints: Constraints ->
val iconPlaceable: Placeable = measurables[0].measure(constraints = constraints)
val textPlaceable: Placeable = measurables[1].measure(constraints = constraints)
val height: Int = constraints.maxHeight
// FAB has an aspect ratio of 1 so the initial width is the height
val initialWidth: Float = height.toFloat()
// Use it to get the padding
val iconPadding: Float = (initialWidth - iconPlaceable.width) / 2f
// The full width will be : padding + icon + padding + text + padding
val expandedWidth: Float = iconPlaceable.width + textPlaceable.width + iconPadding * 3
// Apply the animation factor to go from initialWidth to fullWidth
val width: Float = lerp(start = initialWidth, stop = expandedWidth, fraction = widthProgress())
layout(width = width.roundToInt(), height = height) {
iconPlaceable.place(
x = iconPadding.roundToInt(),
y = constraints.maxHeight / 2 - iconPlaceable.height / 2
)
textPlaceable.place(
x = (iconPlaceable.width + iconPadding * 2).roundToInt(),
y = constraints.maxHeight / 2 - textPlaceable.height / 2
)
}
}
}
/**
* enum which specifies whether the [IconAndTextRow] is Collapsed, oe Extended
*/
private enum class ExpandableFabStates { Collapsed, Extended }
/**
* The duration in milliseconds of the `transitionSpec` used when animating the [Transition] between
* the two [ExpandableFabStates].
*/
private const val transitionDuration = 200
| 0 |
Kotlin
|
0
| 0 |
3785a061995619134a67cce64352bb34a9868b14
| 15,115 |
Compose-Overflow
|
Apache License 2.0
|
app/src/main/java/me/inassar/onboardingfreebi/extensions.kt
|
ranger163
| 169,182,383 | false | null |
package me.inassar.onboardingfreebi
import android.content.Context
import android.os.Handler
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
fun View.show() {
visibility = View.VISIBLE
}
fun View.hide() {
visibility = View.GONE
}
fun postDelayed(delayMillis: Long, task: () -> Unit) {
Handler().postDelayed(task, delayMillis)
}
fun AppCompatActivity.toolbar(toolbar: Toolbar, titleStr: String = "") {
setSupportActionBar(toolbar)
supportActionBar?.title = titleStr
toolbar.apply {
setNavigationIcon(R.drawable.ic_arrow_back_grey_24dp)
setNavigationOnClickListener { finish() }
}
}
| 0 |
Kotlin
|
14
| 44 |
73e1038e22e10ca8b99260739056977ec2578947
| 824 |
OnboardingFreebi
|
MIT License
|
customview/src/main/java/com/iamkamrul/input/EditText.kt
|
kamrul3288
| 592,197,452 | false | null |
package com.iamkamrul.input
import android.annotation.SuppressLint
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.ColorInt
import androidx.annotation.Dimension
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import com.iamkamrul.R
import com.iamkamrul.utils.FontsOverride
import com.iamkamrul.utils.Shape
class EditText : AppCompatEditText{
constructor(context: Context) : super(context){
applyCustomFont()
}
constructor(context: Context, attrs: AttributeSet) : super(context,attrs){
applyAttributes(attrs,context)
applyCustomFont()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr:Int) : super(context,attrs,defStyleAttr){
applyCustomFont()
}
@SuppressLint("CustomViewStyleable")
private fun applyAttributes(attrs: AttributeSet, context: Context){
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.EditText,0,0)
val backgroundColor = typedArray.getColor(R.styleable.EditText_et_background_color, Color.TRANSPARENT)
val backgroundBorderRadius = typedArray.getDimension(R.styleable.EditText_et_border_radius,0f)
val backgroundShapeType = Shape.values()[typedArray.getInt(R.styleable.EditText_et_background_shape,1)]
val strokeColor = typedArray.getColor(R.styleable.EditText_et_stroke_color, Color.TRANSPARENT)
val strokeWithSize = typedArray.getDimension(R.styleable.EditText_et_stroke_width,0f)
val backgroundDisableColor = typedArray.getColor(R.styleable.EditText_et_disable_color, Color.GRAY)
typedArray.recycle()
if (backgroundColor != Color.TRANSPARENT || strokeColor != Color.TRANSPARENT){
setShape(
backgroundColor = backgroundColor,
backgroundBorderRadius = backgroundBorderRadius,
backgroundShapeType = backgroundShapeType,
strokeColor = strokeColor,
strokeWithSize = strokeWithSize,
backgroundDisableColor = backgroundDisableColor,
)
}
}
fun setShape(
@ColorInt backgroundColor:Int = Color.TRANSPARENT,
@Dimension backgroundBorderRadius:Float = 0f,
backgroundShapeType: Shape = Shape.Rectangle,
@ColorInt strokeColor:Int = Color.TRANSPARENT,
@Dimension strokeWithSize:Float = 0f,
@ColorInt backgroundDisableColor:Int = Color.GRAY,
){
val drawableBuilder = GradientDrawable()
val contentColor = ColorStateList(
arrayOf(
intArrayOf(android.R.attr.state_activated),
intArrayOf(android.R.attr.state_enabled),
intArrayOf(-android.R.attr.state_enabled)
),
intArrayOf(
backgroundColor,
backgroundColor,
backgroundDisableColor
)
)
drawableBuilder.color = contentColor
when (backgroundShapeType) {
// stroke
Shape.Stroke -> {
drawableBuilder.shape = GradientDrawable.RECTANGLE
drawableBuilder.setStroke(strokeWithSize.toInt(),strokeColor)
drawableBuilder.cornerRadius = backgroundBorderRadius
}
// rectangle
Shape.Rectangle ->{
drawableBuilder.shape = GradientDrawable.RECTANGLE
drawableBuilder.cornerRadius = backgroundBorderRadius
}
// oval
Shape.Oval -> drawableBuilder.shape = GradientDrawable.OVAL
// stroke Circle
Shape.StrokeCircle -> {
drawableBuilder.shape = GradientDrawable.OVAL
drawableBuilder.setStroke(strokeWithSize.toInt(),strokeColor)
}
}
drawableBuilder.invalidateSelf()
this.background = drawableBuilder
}
private fun applyCustomFont() {
if (FontsOverride.regularFontTypeFace != null){
typeface = FontsOverride.regularFontTypeFace
}
}
}
| 0 |
Kotlin
|
0
| 0 |
895e7fa1e5b36bf4e5c787fb5a520bdf7fd82d84
| 4,329 |
customview-android
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/application/Oidc.kt
|
navikt
| 147,519,013 | false |
{"Kotlin": 548334, "Dockerfile": 277}
|
package no.nav.syfo.application
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import io.ktor.client.HttpClient
import io.ktor.client.HttpClientConfig
import io.ktor.client.call.body
import io.ktor.client.engine.apache.Apache
import io.ktor.client.engine.apache.ApacheEngineConfig
import io.ktor.client.request.get
import kotlinx.coroutines.runBlocking
import no.nav.syfo.util.handleResponseException
import no.nav.syfo.util.setupJacksonSerialization
import no.nav.syfo.util.setupRetry
val config: HttpClientConfig<ApacheEngineConfig>.() -> Unit = {
setupJacksonSerialization()
handleResponseException()
setupRetry()
}
fun getWellKnownTokenX(wellKnownUrl: String) = runBlocking {
HttpClient(Apache, config).get(wellKnownUrl).body<WellKnownTokenX>()
}
@JsonIgnoreProperties(ignoreUnknown = true)
data class WellKnownTokenX(
val token_endpoint: String,
val jwks_uri: String,
val issuer: String,
)
| 3 |
Kotlin
|
3
| 0 |
9572799c04fd6c3b5fca59968d30c6b2b26f21e3
| 941 |
syfosmregister
|
MIT License
|
support-refs_heads_androidx-master-dev-ui.tar/ui-material/integration-tests/material-studies/src/main/java/androidx/ui/material/studies/rally/RallyActivity.kt
|
cpinan
| 215,833,397 | false | null |
/*
* 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.ui.material.studies.rally
import android.app.Activity
import android.os.Bundle
import androidx.compose.Composable
import androidx.compose.state
import androidx.compose.unaryPlus
import androidx.ui.core.dp
import androidx.ui.core.setContent
import androidx.ui.foundation.VerticalScroller
import androidx.ui.layout.Column
import androidx.ui.layout.HeightSpacer
import androidx.ui.layout.LayoutSize
import androidx.ui.layout.Spacing
import androidx.ui.material.Tab
import androidx.ui.material.TabRow
import androidx.ui.material.studies.Scaffold
/**
* This Activity recreates the Rally Material Study from
* https://material.io/design/material-studies/rally.html
*/
class RallyActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
RallyApp()
}
}
@Composable
fun RallyApp() {
RallyTheme {
val allScreens = RallyScreenState.values().toList()
var currentScreen by +state { RallyScreenState.Overview }
Scaffold(appBar = {
TabRow(allScreens, selectedIndex = currentScreen.ordinal) { i, screen ->
Tab(text = screen.name, selected = currentScreen.ordinal == i) {
currentScreen = screen
}
}
}) {
currentScreen.body()
}
}
}
}
@Composable
fun RallyBody() {
VerticalScroller {
Column(modifier = Spacing(16.dp), mainAxisSize = LayoutSize.Expand) {
RallyAlertCard()
HeightSpacer(height = 10.dp)
RallyAccountsOverviewCard()
HeightSpacer(height = 10.dp)
RallyBillsOverviewCard()
}
}
}
private enum class RallyScreenState {
Overview, Accounts, Bills
}
@Composable
private fun RallyScreenState.body() = when (this) {
RallyScreenState.Overview -> RallyBody()
RallyScreenState.Accounts -> RallyAccountsCard()
RallyScreenState.Bills -> RallyBillsCard()
}
| 1 | null |
1
| 3 |
a4298de63f0cb4848269a9fe5b6a5ab59d68a4e5
| 2,689 |
Android-Jetpack-Composer
|
Apache License 2.0
|
domain/src/main/java/com/thekorovay/myportfolio/domain/entities/SearchHistoryState.kt
|
thekorovay
| 339,721,482 | false | null |
package com.thekorovay.myportfolio.domain.entities
enum class SearchHistoryState {
IDLE, BUSY, ERROR
}
| 0 |
Kotlin
|
0
| 0 |
b436895f2fc6f6e7d13377708b2a9f069ff66a4b
| 107 |
my_portfolio
|
MIT License
|
static-random/src/test/kotlin/io/github/eaglesakura/static_random/RandomTest.kt
|
eaglesakura
| 337,716,917 | false | null |
package io.github.eaglesakura.static_random
import org.junit.Test
class RandomTest {
@Test
fun dummySuccess() {
}
}
| 0 |
Kotlin
|
0
| 0 |
6311ca2963ddb6b567389f96f2300c4809c8e7df
| 130 |
static-random
|
MIT License
|
Kotlin/src/main/kotlin/reference/coroutines/context/Context10.kt
|
totemtec
| 370,664,275 | false |
{"Kotlin": 61525, "Java": 388}
|
package reference.coroutines.context
import kotlinx.coroutines.*
fun main() = runBlocking<Unit> {
val activity = Activity()
activity.doSomething() // 运行测试函数
println("Launched coroutines")
delay(500L) // 延迟半秒钟
println("Destroying activity!")
activity.destroy() // 取消所有的协程
delay(1000) // 为了在视觉上确认它们没有工作
}
| 0 |
Kotlin
|
0
| 0 |
f1dc261c88777dcfe1b22ba53134f009964798a0
| 332 |
kotlin
|
Apache License 2.0
|
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
|
androidports
| 115,100,208 | false | null |
/*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.builtInWebServer
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.DirectoryIndex
import com.intellij.openapi.roots.impl.ModuleLibraryOrderEntryImpl
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.JarFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.project.rootManager
import com.intellij.util.PlatformUtils
import com.intellij.util.containers.computeOrNull
internal data class SuitableRoot(val file: VirtualFile, val moduleQualifier: String?)
private class DefaultWebServerRootsProvider : WebServerRootsProvider() {
override fun resolve(path: String, project: Project, pathQuery: PathQuery): PathInfo? {
val pathToFileManager = WebServerPathToFileManager.getInstance(project)
var effectivePath = path
if (PlatformUtils.isIntelliJ()) {
val index = effectivePath.indexOf('/')
if (index > 0 && !effectivePath.regionMatches(0, project.name, 0, index, !SystemInfo.isFileSystemCaseSensitive)) {
val moduleName = effectivePath.substring(0, index)
val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) }
if (module != null && !module.isDisposed) {
effectivePath = effectivePath.substring(index + 1)
val resolver = pathToFileManager.getResolver(effectivePath)
val result = RootProvider.values().computeOrNull { findByRelativePath(effectivePath, it.getRoots(module.rootManager), resolver, moduleName, pathQuery) }
?: findInModuleLibraries(effectivePath, module, resolver, pathQuery)
if (result != null) {
return result
}
}
}
}
val resolver = pathToFileManager.getResolver(effectivePath)
val modules = runReadAction { ModuleManager.getInstance(project).modules }
if (pathQuery.useVfs) {
var oldestParent = path.indexOf("/").let { if (it > 0) path.substring(0, it) else null }
if (oldestParent == null && !path.isEmpty() && !path.contains('.')) {
// maybe it is top level directory? (in case of dart projects - web)
oldestParent = path
}
if (oldestParent != null) {
for (root in pathToFileManager.parentToSuitableRoot.get(oldestParent)) {
root.file.findFileByRelativePath(path)?.let {
return PathInfo(null, it, root.file, root.moduleQualifier)
}
}
}
}
else {
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
findByRelativePath(path, rootProvider.getRoots(module.rootManager), resolver, null, pathQuery)?.let {
it.moduleName = getModuleNameQualifier(project, module)
return it
}
}
}
}
if (!pathQuery.searchInLibs) {
// yes, if !searchInLibs, config.json is also not checked
return null
}
fun findByConfigJson(): PathInfo? {
// https://youtrack.jetbrains.com/issue/WEB-24283
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
for (root in rootProvider.getRoots(module.rootManager)) {
if (resolver.resolve("config.json", root, pathQuery = pathQuery) != null) {
resolver.resolve("index.html", root, pathQuery = pathQuery)?.let {
it.moduleName = getModuleNameQualifier(project, module)
return it
}
}
}
}
}
return null
}
val exists = pathToFileManager.pathToExistShortTermCache.getIfPresent("config.json")
if (exists == null || exists) {
val result = findByConfigJson()
pathToFileManager.pathToExistShortTermCache.put("config.json", result != null)
if (result != null) {
return result
}
}
return findInLibraries(project, effectivePath, resolver, pathQuery)
}
override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? {
return runReadAction {
val directoryIndex = DirectoryIndex.getInstance(project)
val info = directoryIndex.getInfoForFile(file)
// we serve excluded files
if (!info.isExcluded && !info.isInProject) {
// javadoc jars is "not under project", but actually is, so, let's check library or SDK
if (file.fileSystem == JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null
}
else {
var root = info.sourceRoot
val isRootNameOptionalInPath: Boolean
val isLibrary: Boolean
if (root == null) {
isRootNameOptionalInPath = false
root = info.contentRoot
if (root == null) {
root = info.libraryClassRoot
isLibrary = true
assert(root != null) { file.presentableUrl }
}
else {
isLibrary = false
}
}
else {
isLibrary = info.isInLibrarySource
isRootNameOptionalInPath = !isLibrary
}
var module = info.module
if (isLibrary && module == null) {
for (entry in directoryIndex.getOrderEntries(info)) {
if (entry is ModuleLibraryOrderEntryImpl) {
module = entry.ownerModule
break
}
}
}
PathInfo(null, file, root!!, getModuleNameQualifier(project, module), isLibrary, isRootNameOptionalInPath = isRootNameOptionalInPath)
}
}
}
}
internal enum class RootProvider {
SOURCE {
override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.sourceRoots
},
CONTENT {
override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.contentRoots
},
EXCLUDED {
override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.excludeRoots
};
abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile>
}
private val ORDER_ROOT_TYPES by lazy {
val javaDocRootType = getJavadocOrderRootType()
if (javaDocRootType == null)
arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES)
else
arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES)
}
private fun getJavadocOrderRootType(): OrderRootType? {
try {
return JavadocOrderRootType.getInstance()
}
catch (e: Throwable) {
return null
}
}
private fun findInModuleLibraries(path: String, module: Module, resolver: FileResolver, pathQuery: PathQuery): PathInfo? {
val index = path.indexOf('/')
if (index <= 0) {
return null
}
val libraryFileName = path.substring(0, index)
val relativePath = path.substring(index + 1)
return ORDER_ROOT_TYPES.computeOrNull {
findInModuleLevelLibraries(module, it) { root, module ->
if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null
}
}
}
private fun findInLibraries(project: Project, path: String, resolver: FileResolver, pathQuery: PathQuery): PathInfo? {
val index = path.indexOf('/')
if (index < 0) {
return null
}
val libraryFileName = path.substring(0, index)
val relativePath = path.substring(index + 1)
return findInLibrariesAndSdk(project, ORDER_ROOT_TYPES) { root, module ->
if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null
}
}
private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? {
val javaDocRootType = getJavadocOrderRootType() ?: return null
return findInLibrariesAndSdk(project, arrayOf(javaDocRootType)) { root, module ->
if (VfsUtilCore.isAncestor(root, file, false)) PathInfo(null, file, root, getModuleNameQualifier(project, module), true) else null
}
}
internal fun getModuleNameQualifier(project: Project, module: Module?): String? {
if (module != null && PlatformUtils.isIntelliJ() && !(module.name.equals(project.name, ignoreCase = true) || compareNameAndProjectBasePath(module.name, project))) {
return module.name
}
return null
}
private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: FileResolver, moduleName: String?, pathQuery: PathQuery) = roots.computeOrNull { resolver.resolve(path, it, moduleName, pathQuery = pathQuery) }
private fun findInLibrariesAndSdk(project: Project, rootTypes: Array<OrderRootType>, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? {
fun findInLibraryTable(table: LibraryTable, rootType: OrderRootType) = table.libraryIterator.computeOrNull { it.getFiles(rootType).computeOrNull { fileProcessor(it, null) } }
fun findInProjectSdkOrInAll(rootType: OrderRootType): PathInfo? {
val inSdkFinder = { sdk: Sdk -> sdk.rootProvider.getFiles(rootType).computeOrNull { fileProcessor(it, null) } }
val projectSdk = ProjectRootManager.getInstance(project).projectSdk
return projectSdk?.let(inSdkFinder) ?: ProjectJdkTable.getInstance().allJdks.computeOrNull { if (it === projectSdk) null else inSdkFinder(it) }
}
return rootTypes.computeOrNull { rootType ->
runReadAction {
findInLibraryTable(LibraryTablesRegistrar.getInstance().getLibraryTable(project), rootType)
?: findInProjectSdkOrInAll(rootType)
?: ModuleManager.getInstance(project).modules.computeOrNull { if (it.isDisposed) null else findInModuleLevelLibraries(it, rootType, fileProcessor) }
?: findInLibraryTable(LibraryTablesRegistrar.getInstance().libraryTable, rootType)
}
}
}
private fun findInModuleLevelLibraries(module: Module, rootType: OrderRootType, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? {
return module.rootManager.orderEntries.computeOrNull {
if (it is LibraryOrderEntry && it.isModuleLevel) it.getFiles(rootType).computeOrNull { fileProcessor(it, module) } else null
}
}
| 6 | null |
1
| 4 |
6e4f7135c5843ed93c15a9782f29e4400df8b068
| 11,248 |
intellij-community
|
Apache License 2.0
|
app/src/main/java/com/waryozh/simplestepcounter/App.kt
|
Waryozh
| 202,525,623 | false | null |
package com.waryozh.simplestepcounter
import android.app.Application
import com.waryozh.simplestepcounter.injection.AppComponent
import com.waryozh.simplestepcounter.injection.AppModule
import com.waryozh.simplestepcounter.injection.DaggerAppComponent
class App : Application() {
lateinit var appComponent: AppComponent
override fun onCreate() {
super.onCreate()
appComponent = DaggerAppComponent.builder()
.appModule(AppModule(this))
.build()
appComponent.inject(this)
}
}
| 0 |
Kotlin
|
0
| 0 |
9c1d619d51c2fcdc5f041ea3a84a6ed36771a4d1
| 538 |
simple-step-counter
|
MIT License
|
app/src/main/java/com/example/admin_bookmarket/EditProfileActivity.kt
|
tanpmclk14uit
| 505,665,052 | false |
{"Kotlin": 103596, "Java": 185}
|
package com.example.admin_bookmarket
import android.app.DatePickerDialog
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.DatePicker
import android.widget.Toast
import androidx.activity.viewModels
import com.example.admin_bookmarket.ViewModel.UserViewModel
import com.example.admin_bookmarket.data.common.AppUtil
import com.example.admin_bookmarket.data.model.Information
import com.example.admin_bookmarket.databinding.ActivityEditProfileBinding
import com.google.firebase.firestore.FieldValue
import com.google.firebase.firestore.FirebaseFirestore
import dagger.hilt.android.AndroidEntryPoint
import java.util.*
import java.util.regex.Pattern
@AndroidEntryPoint
class EditProfileActivity : AppCompatActivity() {
val viewModel: UserViewModel by viewModels()
lateinit var binding: ActivityEditProfileBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEditProfileBinding.inflate(layoutInflater)
setContentView(binding.root)
setData()
setSaveButtonCommand()
setBackButton()
}
private fun setBackButton() {
binding.imgBack.setOnClickListener {
finish()
}
}
private fun setSaveButtonCommand() {
binding.btnSaveProfile.setOnClickListener {
if (isValidName() && isValidPhoneNumber() && !isEmptyInformation()) {
val information =
Information(
fullName = binding.edtName.text.toString(),
introduction = binding.edtIntroduction.text.toString(),
address = binding.edtAddress.text.toString(),
phoneNumber = binding.edtPhoneNumber.text.toString(),
webSite = binding.edtWebsite.text.toString(),
)
viewModel.updateUserInfo(information)
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show()
startActivity(Intent(baseContext, MainActivity::class.java))
finish()
}else{
Toast.makeText(this, "Thông tin không hợp lệ!", Toast.LENGTH_SHORT).show()
}
}
}
private fun isEmptyInformation(): Boolean {
return binding.edtName.text.isNullOrBlank() &&
binding.edtIntroduction.text.isNullOrBlank() &&
binding.edtAddress.text.isNullOrBlank() &&
binding.edtPhoneNumber.text.isNullOrBlank() &&
binding.edtWebsite.text.isNullOrBlank()
}
private fun isValidName(): Boolean {
return if (binding.edtName.text.isEmpty()) {
binding.edtName.error = "Name can not empty"
false
} else {
return if (isNameContainNumberOrSpecialCharacter(binding.edtName.text.toString())) {
binding.edtName.error = "Name can not contain number of special character"
false
} else {
binding.edtName.error = null
true
}
}
}
private fun isNameContainNumberOrSpecialCharacter(name: String): Boolean {
var hasNumber: Boolean = Pattern.compile(
"[0-9]"
).matcher(name).find()
var hasSpecialCharacter: Boolean = Pattern.compile(
"[!@#$%&.,\"':;?*()_+=|<>?{}\\[\\]~-]"
).matcher(name).find()
return hasNumber || hasSpecialCharacter
}
private fun isValidPhoneNumber(): Boolean {
var result = false
if (binding.edtPhoneNumber.text.isNotEmpty()) {
result = Pattern.compile(
"^[+]?[0-9]{10,13}\$"
).matcher(binding.edtPhoneNumber.text).find()
if (!result) {
binding.edtPhoneNumber.error = "Please enter right phone number!"
}
}
return result
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
private fun setData() {
val information = viewModel.getUserInfo()
binding.edtName.setText(information.fullName)
binding.edtWebsite.setText(information.webSite)
binding.edtAddress.setText(information.address)
binding.edtPhoneNumber.setText(information.phoneNumber)
binding.edtIntroduction.setText(information.introduction)
}
}
| 0 |
Kotlin
|
0
| 0 |
6c0d28eb3c2e375807d89e001fb94f565ef871e3
| 4,473 |
admin-Clone-CTSV
|
Apache License 2.0
|
app/src/main/java/com/kvl/cyclotrack/data/HeartRateMeasurementDao.kt
|
kevinvanleer
| 311,970,003 | false | null |
package com.kvl.cyclotrack.data
import androidx.lifecycle.LiveData
import androidx.room.*
@Dao
interface HeartRateMeasurementDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun save(measurements: HeartRateMeasurement): Long
@Update
fun update(measurements: HeartRateMeasurement)
@Query("SELECT * FROM HeartRateMeasurement WHERE tripId = :tripId ORDER BY timestamp ASC")
suspend fun load(tripId: Long): Array<HeartRateMeasurement>
@Query("SELECT * FROM HeartRateMeasurement WHERE tripId = :tripId ORDER BY timestamp ASC")
fun subscribe(tripId: Long): LiveData<Array<HeartRateMeasurement>>
@Query("UPDATE HeartRateMeasurement SET tripId = :newTripId WHERE tripId = :tripId")
suspend fun changeTrip(tripId: Long, newTripId: Long)
}
| 0 |
Kotlin
|
0
| 7 |
e62bbb39eec10d2f3c327c024f1462e3a6736987
| 790 |
cyclotrack
|
The Unlicense
|
app/src/main/java/com/example/loadmorerecyclerview/StaggeredRecyclerView/Items_StaggeredRVAdapter.kt
|
achmadqomarudin
| 372,497,545 | false | null |
package com.example.loadmorerecyclerview.StaggeredRecyclerView
import android.graphics.BlendMode
import android.graphics.BlendModeColorFilter
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Build
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.example.loadmorerecyclerview.Constant
import com.example.loadmorerecyclerview.R
import com.example.loadmorerecyclerview.databinding.ProgressLoadingBinding
import com.example.loadmorerecyclerview.databinding.StaggeredItemRowBinding
class Items_StaggeredRVAdapter(private var itemsCells: ArrayList<StaggeredModel?>) :
RecyclerView.Adapter<RecyclerView.ViewHolder>() {
class ItemViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
class LoadingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
fun addData(dataViews: ArrayList<StaggeredModel?>) {
this.itemsCells.addAll(dataViews)
notifyDataSetChanged()
}
fun getItemAtPosition(position: Int): StaggeredModel? {
return itemsCells[position]
}
fun addLoadingView() {
//add loading item
Handler().post {
itemsCells.add(null)
notifyItemInserted(itemsCells.size - 1)
}
}
fun removeLoadingView() {
//remove loading item
if (itemsCells.size != 0) {
itemsCells.removeAt(itemsCells.size - 1)
notifyItemRemoved(itemsCells.size)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return if (viewType == Constant.VIEW_TYPE_ITEM) {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.staggered_item_row, parent, false)
ItemViewHolder(view)
} else {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.progress_loading, parent, false)
val binding = ProgressLoadingBinding.bind(view)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
binding.progressbar.indeterminateDrawable.colorFilter =
BlendModeColorFilter(Color.WHITE, BlendMode.SRC_ATOP)
} else {
binding.progressbar.indeterminateDrawable.setColorFilter(
Color.WHITE,
PorterDuff.Mode.MULTIPLY
)
}
LoadingViewHolder(view)
}
}
override fun getItemCount(): Int {
return itemsCells.size
}
override fun getItemViewType(position: Int): Int {
return if (itemsCells[position] == null) {
Constant.VIEW_TYPE_LOADING
} else {
Constant.VIEW_TYPE_ITEM
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder.itemViewType == Constant.VIEW_TYPE_ITEM) {
val binding = StaggeredItemRowBinding.bind(holder.itemView)
binding.staggeredItemImageview.setAspectRatio(itemsCells[position]!!.aspectRatio)
binding.staggeredItemImageview.setBackgroundColor(itemsCells[position]!!.color)
} else {
val layoutParams =
holder.itemView.layoutParams as StaggeredGridLayoutManager.LayoutParams
layoutParams.isFullSpan = true
}
}
}
| 1 |
Kotlin
|
3
| 6 |
bb5609e723511fa2e3838ce6f95d20cd9fe698d7
| 3,517 |
LoadMoreRecyclerview
|
Apache License 2.0
|
app/src/main/java/com/mrkaz/tokoin/data/repository/INewsRepository.kt
|
mrkazansky
| 348,208,334 | false | null |
package com.mrkaz.tokoin.data.repository
import com.mrkaz.tokoin.data.models.news.NewsResponse
interface INewsRepository {
suspend fun fetchTopHeadlines(page: Int, query: String?, country: String?): NewsResponse
}
| 1 | null |
1
| 1 |
4b4df194cbf375ec057d61f57516b5a45f27c1b1
| 221 |
mvvm-template
|
Apache License 2.0
|
src/main/kotlin/no/nav/security/mock/oauth2/token/OAuth2TokenCallback.kt
|
kjellkongsvik
| 331,589,857 | true |
{"Kotlin": 161356, "FreeMarker": 7900, "CSS": 1771}
|
package no.nav.security.mock.oauth2.token
import com.nimbusds.oauth2.sdk.GrantType
import com.nimbusds.oauth2.sdk.TokenRequest
import com.nimbusds.openid.connect.sdk.OIDCScopeValue
import java.util.UUID
import no.nav.security.mock.oauth2.extensions.clientIdAsString
import no.nav.security.mock.oauth2.extensions.grantType
import no.nav.security.mock.oauth2.grant.TokenExchangeGrant
interface OAuth2TokenCallback {
fun issuerId(): String
fun subject(tokenRequest: TokenRequest): String
fun audience(tokenRequest: TokenRequest): List<String>
fun addClaims(tokenRequest: TokenRequest): Map<String, Any>
fun tokenExpiry(): Long
}
// TODO: for JwtBearerGrant and TokenExchange should be able to ovverride sub, make sub nullable and return some default
open class DefaultOAuth2TokenCallback(
private val issuerId: String = "default",
private val subject: String = UUID.randomUUID().toString(),
// needs to be nullable in order to know if a list has explicitly been set, empty list should be a allowable value
private val audience: List<String>? = null,
private val claims: Map<String, Any> = emptyMap(),
private val expiry: Long = 3600
) : OAuth2TokenCallback {
override fun issuerId(): String = issuerId
override fun subject(tokenRequest: TokenRequest): String {
return when (GrantType.CLIENT_CREDENTIALS) {
tokenRequest.grantType() -> tokenRequest.clientIdAsString()
else -> subject
}
}
override fun audience(tokenRequest: TokenRequest): List<String> {
val oidcScopeList = OIDCScopeValue.values().map { it.toString() }
return audience
?: (tokenRequest.authorizationGrant as? TokenExchangeGrant)?.audience
?: let {
tokenRequest.scope?.toStringList()
?.filterNot { oidcScopeList.contains(it) }
} ?: listOf("default")
}
override fun addClaims(tokenRequest: TokenRequest): Map<String, Any> =
claims.toMutableMap().apply {
putAll(
mapOf(
"azp" to tokenRequest.clientIdAsString(),
"tid" to issuerId
)
)
}
override fun tokenExpiry(): Long = expiry
}
| 0 | null |
0
| 0 |
1aca90edc923a59aabfdd8c65254ee27696ce329
| 2,259 |
mock-oauth2-server
|
MIT License
|
app/src/main/java/com/bikcode/rickandmortycompose/presentation/screens/home/HomeTopBar.kt
|
Bikcodeh
| 412,662,765 | false |
{"Kotlin": 120155}
|
package com.bikcode.rickandmortycompose.presentation.screens.home
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.bikcode.rickandmortycompose.R
import com.bikcode.rickandmortycompose.ui.theme.topAppBarBackgroundColor
import com.bikcode.rickandmortycompose.ui.theme.topAppBarContentColor
@Composable
fun HomeTopBar(homeViewModel: HomeViewModel = hiltViewModel()) {
var showMenu by remember { mutableStateOf(false) }
TopAppBar(
title = {
Text(
text = stringResource(id = R.string.title_app),
color = MaterialTheme.colors.topAppBarContentColor
)
},
backgroundColor = MaterialTheme.colors.topAppBarBackgroundColor,
actions = {
IconButton(onClick = { showMenu = !showMenu }) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_filter),
contentDescription = stringResource(id = R.string.search_icon)
)
}
DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
DropdownMenuItem(onClick = {
homeViewModel.filterCharacters(status = "all")
showMenu = false
}) {
Text(text = stringResource(id = R.string.all_label))
}
DropdownMenuItem(onClick = {
homeViewModel.filterCharacters(status = "Alive")
showMenu = false
}) {
Canvas(modifier = Modifier.size(30.dp)) {
drawCircle(
color = Color.Green,
radius = size.minDimension / 4
)
}
Text(
text = stringResource(id = R.string.alive_label),
modifier = Modifier.fillMaxWidth()
)
}
DropdownMenuItem(onClick = {
homeViewModel.filterCharacters(status = "Dead")
showMenu = false
}) {
Canvas(modifier = Modifier.size(30.dp)) {
drawCircle(
color = Color.Red,
radius = size.minDimension / 4
)
}
Text(
text = stringResource(id = R.string.dead_label),
modifier = Modifier.fillMaxWidth()
)
}
}
}
)
}
@Composable
fun Circle() {
Row {
Canvas(modifier = Modifier.size(30.dp)) {
drawCircle(
color = Color.Green,
radius = size.minDimension / 4
)
}
}
}
@Preview
@Composable
fun CirclePreview() {
Circle()
}
@Composable
@Preview
fun HomeTopBarPreview() {
HomeTopBar()
}
| 0 |
Kotlin
|
1
| 0 |
65f77b49df3ed70b7469dc69deaed8bc56fdef9a
| 3,567 |
RickAndMortyCompose
|
MIT License
|
core_navigation/src/main/java/com/githukudenis/core_navigation/FeatureTasksNavGraph.kt
|
DenisGithuku
| 575,040,332 | false |
{"Kotlin": 163866}
|
package com.githukudenis.core_navigation
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.material3.SnackbarHostState
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import com.githukudenis.tasks.ui.add_task.AddTaskScreen
import com.githukudenis.tasks.ui.task_detail.TaskDetailScreen
import com.githukudenis.tasks.ui.task_list.TaskListScreen
const val FeatureTasksNavGraphRouteId = "tasks_graph"
@RequiresApi(Build.VERSION_CODES.O)
fun NavGraphBuilder.featureTasksNavGraph(
snackbarHostState: SnackbarHostState,
navHostController: NavHostController
) {
navigation(
startDestination = MiAssistScreenDestination.TaskListDestination.routeId,
route = FeatureTasksNavGraphRouteId
) {
composable(route = MiAssistScreenDestination.TaskListDestination.routeId) {
TaskListScreen(
snackbarHostState = snackbarHostState,
onNewTask = {
navHostController.navigate(route = MiAssistScreenDestination.AddTaskDestination.routeId) {
launchSingleTop = true
popUpTo(MiAssistScreenDestination.AddTaskDestination.routeId) {
inclusive = true
}
}
},
onOpenTodoDetails = { taskId ->
navHostController.navigate(MiAssistScreenDestination.TaskDetailDestination.routeId + "/$taskId") {
launchSingleTop = true
popUpTo(MiAssistScreenDestination.TaskDetailDestination.routeId) {
inclusive = true
}
}
}
)
}
composable(route = MiAssistScreenDestination.TaskDetailDestination.routeId + "/{taskId}") {
TaskDetailScreen(
snackbarHostState = snackbarHostState,
onUpdateTask = {
navHostController.popBackStack()
},
onNavigateUp = { navHostController.navigateUp() }
)
}
composable(route = MiAssistScreenDestination.AddTaskDestination.routeId) {
AddTaskScreen(
snackbarHostState = snackbarHostState,
onSaveTask = {
navHostController.popBackStack()
},
onNavigateUp = { navHostController.navigateUp() }
)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
945e77e83aba39d435047587b7776be4fb7ed411
| 2,616 |
MiAssist
|
MIT License
|
app/src/main/java/tech/soit/quiet/repository/setting/LocalScannerSettingRepository.kt
|
boyan01
| 114,945,726 | false | null |
package tech.soit.quiet.repository.setting
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import tech.soit.quiet.ui.item.SettingScannerFolderFilter
import tech.soit.quiet.utils.component.persistence.KeyValue
import tech.soit.quiet.utils.component.persistence.get
/**
* repository for LocalScannerSetting
*/
object LocalScannerSettingRepository {
private const val KEY_IS_FILTER_BY_DURATION = "scanner_filter_by_duration"
private const val KEY_FILE_FILTER = "_local_setting_scanner_filter_folder"
private val isFilterByDuration = MutableLiveData<Boolean>()
private val folderFilterData = MutableLiveData<List<SettingScannerFolderFilter>>()
init {
//初始化读取数据
GlobalScope.launch {
isFilterByDuration.postValue(KeyValue.get(KEY_IS_FILTER_BY_DURATION) ?: true)
folderFilterData.postValue(KeyValue.get(KEY_FILE_FILTER, object : TypeToken<List<SettingScannerFolderFilter>>() {}.type))
}
}
fun isFilterByDuration(): LiveData<Boolean> {
return isFilterByDuration
}
fun setFilterByDuration(b: Boolean) {
isFilterByDuration.postValue(b)
GlobalScope.launch {
KeyValue.put(KEY_IS_FILTER_BY_DURATION, b)
}
}
fun getFolderFilterData(): LiveData<List<SettingScannerFolderFilter>> {
return folderFilterData
}
/**
* edit filter folder
* [FilterEditorScope] contains put and remove operation to edit filter folders
*/
fun editFilterData(editor: FilterEditorScope.() -> Unit) {
val scope = FilterEditorScope()
scope.editor()
folderFilterData.postValue(scope.list)
GlobalScope.launch {
KeyValue.put(KEY_FILE_FILTER, scope.list)
}
}
class FilterEditorScope {
val list = ArrayList(folderFilterData.value ?: emptyList())
fun put(filter: SettingScannerFolderFilter) {
val index = list.indexOfFirst { it.path == filter.path }
if (index == -1) {
list.add(filter)
return
}
list[index] = filter
}
fun remove(filter: SettingScannerFolderFilter) {
list.removeAll { it.path == filter.path }
}
}
}
| 0 |
Kotlin
|
3
| 27 |
0ba7211c39bf6d144dcda8f79a0d10f4e57b2208
| 2,392 |
MusicPlayer
|
Apache License 2.0
|
ui/src/main/kotlin/io/github/gmvalentino8/github/sample/ui/utils/ToastExt.kt
|
wasabi-muffin
| 462,369,263 | false |
{"Kotlin": 2712155, "Mustache": 4796, "Ruby": 1144, "Shell": 812}
|
package io.github.gmvalentino8.github.sample.ui.utils
import android.content.Context
import android.widget.Toast
import io.github.gmvalentino8.github.sample.ui.R
fun notImplemented(context: Context) {
Toast.makeText(context, context.getString(R.string.error_not_implemented), Toast.LENGTH_SHORT).show()
}
| 0 |
Kotlin
|
0
| 1 |
2194a2504bde08427ad461d92586497c7187fb40
| 311 |
github-sample-project
|
Apache License 2.0
|
src/main/kotlin/com/money/transfer/controller/AccountController.kt
|
NklTsl
| 516,325,027 | false |
{"Kotlin": 25911}
|
package com.money.transfer.controller
import com.money.transfer.api.AccountServiceApi
import com.money.transfer.service.IAccountService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import java.math.BigDecimal
@RestController
class AccountController : AccountServiceApi {
@Autowired lateinit var accountService : IAccountService
override fun get(id: Long) = accountService.get(id)
override fun create() = accountService.create()
override fun addMoney(id: Long, amount: BigDecimal) = accountService.add(id, amount)
override fun withdrawMoney(id: Long, amount: BigDecimal) = accountService.withdraw(id, amount)
override fun transferMoney(from: Long, to: Long, amount: BigDecimal) = accountService.transfer(from, to, amount)
}
| 0 |
Kotlin
|
1
| 1 |
4d0a5086537861f17f8e1661f7647da8617829c0
| 821 |
MoneyTransfer
|
Apache License 2.0
|
idea/testData/debugger/tinyApp/src/evaluate/singleBreakpoint/createExpression/createExpressionSimple.kt
|
JakeWharton
| 99,388,807 | false | null |
package createExpressionSimple
class MyClass: Base() {
val i = 1
}
open class Base {
val baseI = 2
}
fun main(args: Array<String>) {
val myClass: Base = MyClass()
val myBase = Base()
//Breakpoint!
val a = 1
}
// PRINT_FRAME
// DESCRIPTOR_VIEW_OPTIONS: NAME_EXPRESSION
| 0 | null |
28
| 83 |
4383335168338df9bbbe2a63cb213a68d0858104
| 296 |
kotlin
|
Apache License 2.0
|
src/main/kotlin/fwcd/miniml/graph/UnaryElementwise.kt
|
fwcd
| 171,545,453 | false | null |
package fwcd.miniml.graph
import fwcd.miniml.math.NDArray
import fwcd.miniml.math.ShapeMismatchException
import fwcd.miniml.utils.loggerFor
private val LOG = loggerFor<UnaryElementwise>()
/**
* A single-input, elementwise function.
*/
open class UnaryElementwise(
value: ValueNode,
private val functionName: String,
private val function: (Double) -> Double,
private val derivative: (Double) -> Double
) : ValueNode {
override val operands: List<ValueNode> = listOf(value)
override fun forward() = operands[0].forward().map(function)
override fun backward(gradient: NDArray) {
LOG.debug("Backpropagating through {}: {}", functionName, this)
val value = operands[0].cachedForward() ?: throw MissingCachedInputArrayException(functionName)
if (!value.shape.contentEquals(gradient.shape)) {
throw ShapeMismatchException("Gradient of $functionName", value.shape, gradient.shape)
}
operands[0].backward(value.map(derivative) * gradient)
}
override fun toString(): String = "$functionName(${operands[0]})"
}
| 0 |
Kotlin
|
0
| 4 |
483f4cc7c5ee209f16016ec4c82637b58c06bcd3
| 1,039 |
mini-ml
|
MIT License
|
kpoet/src/main/java/com/grosner/kpoet/TypeNameExtensions.kt
|
agrosner
| 86,388,470 | false | null |
package com.grosner.kpoet
import com.squareup.javapoet.ParameterizedTypeName
import com.squareup.javapoet.TypeName
import javax.lang.model.type.TypeMirror
import kotlin.reflect.KClass
val <T : Any> KClass<T>.typeName
get() = TypeName.get(this.java)
val TypeMirror.typeName
get() = TypeName.get(this)
inline fun <reified T : Any> parameterized(kClass: KClass<*>) = ParameterizedTypeName.get(kClass.java, T::class.java)!!
inline fun <reified T1 : Any, reified T2 : Any> parameterized2(kClass: KClass<*>)
= ParameterizedTypeName.get(kClass.java, T1::class.java, T2::class.java)!!
inline fun <reified T1 : Any, reified T2 : Any, reified T3 : Any> parameterized3(kClass: KClass<*>)
= ParameterizedTypeName.get(kClass.java, T1::class.java, T2::class.java, T3::class.java)!!
| 3 |
Kotlin
|
4
| 63 |
ad513413078c1af7d0770ce150a1ba1196ee43ac
| 799 |
KPoet
|
MIT License
|
compiler/testData/codegen/bytecodeListing/inline/inlineOnly.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
// WITH_STDLIB
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
@kotlin.internal.InlineOnly
inline fun foo() { }
class Foo {
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
@kotlin.internal.InlineOnly
inline fun foo() { }
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 247 |
kotlin
|
Apache License 2.0
|
app/src/main/java/code_setup/ui_/home/apapter_/CabsListAdapter.kt
|
himalayanDev
| 293,483,735 | false | null |
package code_setup.ui_.home.apapter_
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import code_setup.app_models.other_.CabsDataModel
import code_setup.app_util.callback_iface.OnItemClickListener
import code_setup.ui_.home.models.PriceListResponseModel
import com.electrovese.setup.R
import kotlinx.android.synthetic.main.cabs_adapter_view.view.*
class CabsListAdapter(
internal var activity: androidx.fragment.app.FragmentActivity,
val dataList: ArrayList<PriceListResponseModel.ResponseObj>,
internal var listener: OnItemClickListener<Any>
) : androidx.recyclerview.widget.RecyclerView.Adapter<CabsListAdapter.OptionViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): OptionViewHolder {
return OptionViewHolder(
LayoutInflater.from(activity).inflate(
R.layout.cabs_adapter_view,
p0,
false
)
)
}
override fun onBindViewHolder(holder: OptionViewHolder, position: Int) {
(holder).bind(dataList[position], position, listener)
}
override fun getItemCount(): Int {
return dataList.size
}
fun updateAll(posts: List<PriceListResponseModel.ResponseObj>) {
this.dataList.clear();
this.dataList.addAll(posts);
notifyDataSetChanged();
}
fun addItem(posts: Object) {
// this.slotsList.add(0, posts);
// notifyDataSetChanged();
}
inner class OptionViewHolder
(view: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(view) {
fun bind(
part: PriceListResponseModel.ResponseObj,
posit: Int,
listener: OnItemClickListener<Any>
) = with(itemView) {
if (part.name.equals("sedan")) {
cabImageVw.setImageResource(R.mipmap.ic_muv)
} else {
cabImageVw.setImageResource(R.mipmap.ic_hatchback)
}
seatsText.setText(part.capacity + " Person")
cabPriceTxt.setText(activity.getString(R.string.str_rupeee_symbol) + "" + part.total_price)
cabTypeTxt.setText(part.name)
if (part.isSelected) {
cabsDataHolderView.setBackgroundColor(resources.getColor(R.color.colorCabSelectionBg))
} else {
cabsDataHolderView.setBackgroundColor(resources.getColor(R.color.colorWhite))
}
itemView.setOnClickListener {
if (part.isSelected) {
listener.onItemClick(itemView, posit, 0, Any())
}
onrefreshSelection(posit)
}
}
}
private fun onrefreshSelection(posit: Int) {
for (i in 0 until dataList.size) {
if (posit == i) {
dataList.get(i).isSelected = true
} else {
dataList.get(i).isSelected = false
}
}
notifyDataSetChanged()
}
fun getPositionData(position: Int): PriceListResponseModel.ResponseObj {
return dataList.get(position)
}
fun getSelectedCabData(): String {
for (i in 0 until dataList.size) {
if (dataList.get(i).isSelected) {
return dataList.get(i).category_id
}
}
return ""
}
}
| 1 |
Kotlin
|
1
| 1 |
5c318e92bf68e39ea6b4310f2a84b601f0e4199d
| 3,369 |
Template
|
Apache License 2.0
|
android/app/src/main/java/com/mattermost/helpers/database_extension/Preference.kt
|
mattermost
| 70,265,724 | false | null |
package com.mattermost.helpers.database_extension
import com.facebook.react.bridge.Arguments
import com.mattermost.helpers.mapCursor
import com.nozbe.watermelondb.WMDatabase
fun getTeammateDisplayNameSetting(db: WMDatabase): String {
val configSetting = queryConfigDisplayNameSetting(db)
if (configSetting != null) {
return configSetting
}
try {
db.rawQuery(
"SELECT value FROM Preference where category = ? AND name = ? limit 1",
arrayOf("display_settings", "name_format")
).use { cursor ->
if (cursor.count <= 0) {
return "username"
}
val resultMap = Arguments.createMap()
cursor.moveToFirst()
resultMap.mapCursor(cursor)
return resultMap?.getString("value") ?: "username"
}
} catch (e: Exception) {
return "username"
}
}
| 124 | null |
1334
| 2,208 |
4a19e07ed9a38468395f4df917600dcfeba03665
| 911 |
mattermost-mobile
|
Apache License 2.0
|
encoder/src/main/java/com/pedro/encoder/input/video/facedetector/Face.kt
|
pedroSG94
| 79,667,969 | false | null |
package com.pedro.encoder.input.video.facedetector
import android.graphics.Point
import android.graphics.Rect
/**
* Created by pedro on 10/10/23.
*/
data class Face(
val id: Int?, //depend if device support it, if not supported the value could be -1
val leftEye: Point?, //depend if device support it
val rightEye: Point?, //depend if device support it
val mouth: Point?, //depend if device support it
val rect: Rect,
val score: Int //range 1 to 100
)
| 233 | null |
733
| 2,196 |
03f4405dbf9d2b64be9ae2af61da213f718fc790
| 468 |
RootEncoder
|
Apache License 2.0
|
src/main/kotlin/snyk/iac/IacScanService.kt
|
snyk
| 117,852,067 | false | null |
package snyk.iac
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import io.snyk.plugin.services.CliAdapter
import snyk.common.RelativePathHelper
import snyk.common.SnykError
/**
* Wrap work with Snyk CLI for IaC (`iac test` command).
*/
@Service(Service.Level.PROJECT)
class IacScanService(project: Project) : CliAdapter<IacIssuesForFile, IacResult>(project) {
fun scan(): IacResult = execute(listOf("iac", "test"))
override fun getProductResult(cliIssues: List<IacIssuesForFile>?, snykErrors: List<SnykError>): IacResult =
IacResult(cliIssues, snykErrors)
override fun sanitizeCliIssues(cliIssues: IacIssuesForFile): IacIssuesForFile {
// .copy() will check nullability of fields
// determine relative path for each issue at scan time
val helper = RelativePathHelper()
val virtualFile = LocalFileSystem.getInstance().findFileByPath(cliIssues.targetFilePath)
val relativePath = virtualFile?.let { helper.getRelativePath(virtualFile, project) }
val sanitized = cliIssues.copy(
virtualFile = virtualFile,
project = project,
relativePath = relativePath,
infrastructureAsCodeIssues = cliIssues.infrastructureAsCodeIssues
.map {
if (it.lineStartOffset > 0 || virtualFile == null || !virtualFile.isValid) {
return@map it.copy()
}
val lineStartOffset = determineLineStartOffset(it, virtualFile)
return@map it.copy(lineStartOffset = lineStartOffset)
}
)
return sanitized
}
private fun determineLineStartOffset(it: IacIssue, virtualFile: VirtualFile): Int {
var lineStartOffset = it.lineStartOffset
ApplicationManager.getApplication().runReadAction {
val document = FileDocumentManager.getInstance().getDocument(virtualFile)
if (document != null) {
val candidate = it.lineNumber - 1 // to 1-based count used in the editor
val lineNumber = if (0 <= candidate && candidate < document.lineCount) candidate else 0
lineStartOffset = document.getLineStartOffset(lineNumber)
}
}
return lineStartOffset
}
override fun getCliIIssuesClass(): Class<IacIssuesForFile> = IacIssuesForFile::class.java
override fun isSuccessCliJsonString(jsonStr: String): Boolean =
jsonStr.contains("\"infrastructureAsCodeIssues\":")
override fun buildExtraOptions(): List<String> = listOf("--json")
}
| 6 | null |
34
| 54 |
7ee680baff7ccf3b4440e7414b021efda8c58416
| 2,845 |
snyk-intellij-plugin
|
Apache License 2.0
|
app/src/main/java/com/rogertalk/roger/android/handlers/DelayedActionListener.kt
|
rogertalk
| 207,123,525 | false |
{"C": 1446968, "Kotlin": 1051662, "C++": 79853, "Objective-C": 32032, "Java": 22252, "Makefile": 1047}
|
package com.rogertalk.roger.android.handlers
interface DelayedActionListener {
/**
* @param actionCode Numeric value used to distinguish callback from different simultaneous delayed actions
*/
fun delayedAction(actionCode: Int)
}
| 0 |
C
|
0
| 1 |
55c9922947311d9d8a1e930463b9ac2a1332e006
| 249 |
roger-android
|
MIT License
|
Project/宠物咖啡-Watermelon02/app/src/main/java/com/example/petscoffee/customview/behavior/RefreshBehavior.kt
|
xitu
| 472,318,720 | false | null |
package com.example.petscoffee.customview.behavior
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.LinearLayout
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import com.example.petscoffee.R
import com.example.petscoffee.customview.viewGroup.MyRefreshLayout
/**
* description : 在coordinatorLayout中让rv能随着appBarLayout的位置变化而改变自己的位置
* author : Watermelon02
* email : [email protected]
* date : 2022/2/11 16:17
*/
class RefreshBehavior(context: Context, attrs: AttributeSet) :
CoordinatorLayout.Behavior<MyRefreshLayout>(context, attrs) {
private var headerHeight: Int = 0
override fun onLayoutChild(
parent: CoordinatorLayout,
child: MyRefreshLayout,
layoutDirection: Int
): Boolean {
parent.onLayoutChild(child, layoutDirection)
headerHeight = parent.findViewById<LinearLayout>(R.id.activity_message_appBarLayout).height
child.offsetTopAndBottom(headerHeight)
return true
}
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: MyRefreshLayout,
directTargetChild: View,
target: View,
axes: Int,
type: Int
): Boolean {
return (axes and ViewCompat.SCROLL_AXIS_VERTICAL) != 0
}
override fun onNestedPreScroll(
coordinatorLayout: CoordinatorLayout,
child: MyRefreshLayout,
target: View,
dx: Int,
dy: Int,
consumed: IntArray,
type: Int
) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type)
if (dy > 0) {//手指向上滑动
val newTranslation = child.translationY - dy
if (newTranslation >= -headerHeight) {
consumed[1] = dy
child.translationY = newTranslation
} else {
consumed[1] = (headerHeight + child.translationY).toInt()
child.translationY = -headerHeight.toFloat()
}
}
}
override fun onNestedScroll(
coordinatorLayout: CoordinatorLayout,
child: MyRefreshLayout,
target: View,
dxConsumed: Int,
dyConsumed: Int,
dxUnconsumed: Int,
dyUnconsumed: Int,
type: Int,
consumed: IntArray
) {
super.onNestedScroll(
coordinatorLayout,
child,
target,
dxConsumed,
dyConsumed,
dxUnconsumed,
dyUnconsumed,
type,
consumed
)
if (dyUnconsumed < 0) {
child.isEnabled = child.translationY.toInt() == 0
val newTranslation = child.translationY - dyUnconsumed
if (newTranslation <= 0 && newTranslation > -headerHeight) {
child.translationY = newTranslation
} else {
child.translationY = 0f
}
}
}
}
| 1 |
JavaScript
|
54
| 25 |
90e3a7367452ea1d15902d2d3bfe229bbbe1e1c1
| 3,005 |
game-garden
|
MIT License
|
src/publicproperty/Person.kt
|
hanks-zyh
| 45,084,033 | false |
{"Text": 1, "Ignore List": 1, "Markdown": 1, "Kotlin": 23, "Java": 2}
|
package publicproperty
/**
* Created by hanks on 16/3/20.
*/
class Person {
@JvmField var name: String ? = null;
fun getAge():Int{
return 12;
}
}
| 1 | null |
1
| 1 |
04dc4c824887135836fa519f0bc5fb1feacae527
| 172 |
KotlinExample
|
Apache License 2.0
|
compiler/testData/codegen/bytecodeText/constants/byte.kt
|
erokhins
| 10,382,997 | true |
{"Java": 15969828, "Kotlin": 11078102, "JavaScript": 176060, "Protocol Buffer": 42992, "HTML": 26117, "Lex": 16668, "ANTLR": 9689, "CSS": 9358, "Groovy": 5204, "Shell": 4638, "Batchfile": 3703, "IDL": 3251}
|
val a: Byte = 1 + 1
// 1 I2B
| 0 |
Java
|
0
| 1 |
ff00bde607d605c4eba2d98fbc9e99af932accb6
| 29 |
kotlin
|
Apache License 2.0
|
src/functionalTest/kotlin/com/cognifide/gradle/sling/pkg/PackageSyncPluginTest.kt
|
Cognifide
| 138,027,523 | false | null |
package com.cognifide.gradle.sling.pkg
import com.cognifide.gradle.sling.test.SlingBuildTest
import org.junit.jupiter.api.Test
class PackageSyncPluginTest : SlingBuildTest() {
@Test
fun `should apply plugin correctly`() {
val projectDir = prepareProject("package-sync-minimal") {
settingsGradle("")
buildGradle("""
plugins {
id("com.cognifide.sling.package.sync")
}
""")
}
runBuild(projectDir, "tasks", "-Poffline") {
assertTask(":tasks")
}
}
}
| 0 |
Kotlin
|
2
| 15 |
b3e7244f887b24dece21571a5a63ae79ef0c7597
| 597 |
gradle-sling-plugin
|
Apache License 2.0
|
src/main/kotlin/org/rust/lang/RustLanguage.kt
|
sakamaki
| 51,411,522 | true |
{"Git Config": 1, "Gradle": 2, "Markdown": 7, "INI": 2, "Shell": 1, "Text": 35, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Java Properties": 1, "TOML": 2, "Rust": 140, "XML": 13, "RenderScript": 1, "HTML": 5, "Kotlin": 171, "Java": 2, "JFlex": 2}
|
package org.rust.lang
import com.intellij.lang.Language
object RustLanguage : Language("RUST") {
override fun isCaseSensitive() = true
}
| 0 |
Kotlin
|
0
| 0 |
8fe36228e121aa894caefeb037b1e59bc38df656
| 144 |
intellij-rust
|
MIT License
|
presentation/src/main/java/com/duccnv/cleanmoviedb/model/OwnerItem.kt
|
ahmedalkhashab
| 260,399,969 | true |
{"Kotlin": 135715, "Java": 2977}
|
package com.duccnv.cleanmoviedb.model
import android.os.Parcelable
import com.duccnv.cleanmoviedb.base.ItemMapper
import com.duccnv.cleanmoviedb.base.ModelItem
import com.duccnv.cleanmoviedb.domain.model.Owner
import kotlinx.android.parcel.Parcelize
import javax.inject.Inject
@Parcelize
data class OwnerItem(val id: Int, val login: String?, val avatar: String?) : ModelItem(), Parcelable
class OwnerItemMapper @Inject constructor() : ItemMapper<Owner, OwnerItem> {
override fun mapToPresentation(model: Owner) = OwnerItem(
model.id, model.login, model.avatar
)
override fun mapToDomain(modelItem: OwnerItem) = Owner(
modelItem.id, modelItem.login, modelItem.avatar
)
}
| 1 | null |
1
| 1 |
d157e2f275b20c8601766ce36c8a91841c133faa
| 705 |
clean_movie_db
|
Apache License 2.0
|
src/main/kotlin/co/nums/intellij/aem/htl/psi/search/HtlJavaSearch.kt
|
paweltarkowski
| 81,607,562 | false |
{"Gradle": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Markdown": 1, "Java Properties": 1, "Java": 1, "XML": 4, "JSON": 6, "SVG": 16, "Kotlin": 78, "JFlex": 1}
|
package co.nums.intellij.aem.htl.psi.search
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiModifier
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.AnnotatedElementsSearch
import com.intellij.psi.search.searches.ClassInheritorsSearch
object HtlJavaSearch {
private val USE_INTERFACES = arrayOf("io.sightly.java.api.Use", "org.apache.sling.scripting.sightly.pojo.Use")
private val SLING_MODEL_ANNOTATION = "org.apache.sling.models.annotations.Model"
fun useApiImplementers(project: Project): Collection<PsiClass> {
return USE_INTERFACES
.map { it.toPsiClass(project) }
.filterNotNull()
.flatMap { project.findImplementers(it) }
.filterNot { it.hasModifierProperty(PsiModifier.ABSTRACT) }
.orEmpty()
}
fun slingModels(project: Project): Collection<PsiClass> {
return SLING_MODEL_ANNOTATION
.toPsiClass(project)
?.let { project.findAnnotatedClasses(it) }
.orEmpty()
}
private fun String.toPsiClass(project: Project) = JavaPsiFacade.getInstance(project).findClass(this, GlobalSearchScope.allScope(project))
private fun Project.findImplementers(implementedInterface: PsiClass): Collection<PsiClass> =
ClassInheritorsSearch.search(implementedInterface, GlobalSearchScope.allScope(this), true).findAll()
private fun Project.findAnnotatedClasses(annotation: PsiClass): Collection<PsiClass> =
AnnotatedElementsSearch.searchPsiClasses(annotation, GlobalSearchScope.allScope(this)).findAll()
}
| 1 | null |
1
| 1 |
14991f7bba6bcddfa40353a7848f3541cb9a28de
| 1,732 |
aem-intellij-plugin
|
MIT License
|
Android-Movie/app/src/main/java/com/app/movie/activity/MovieDetailActivity.kt
|
Alan-Ou
| 345,287,879 | false |
{"Text": 2, "Markdown": 1, "Python": 10, "HTML": 8, "SVG": 8, "CSS": 13, "SCSS": 1, "JavaScript": 17, "INI": 1, "Mako": 1, "XML": 50, "Ignore List": 4, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Proguard": 1, "JSON": 1, "Kotlin": 37, "Java": 3}
|
package com.app.movie.activity
import android.annotation.SuppressLint
import android.content.Intent
import android.view.View
import com.app.movie.utils.GlideImageLoader
import com.app.movie.base.BaseActivity
import com.app.movie.bean.MovieDetailBean
import com.app.movie.bean.UserInfoBean
import com.app.movie.databinding.ActivityMovieDetailBinding
import com.google.gson.Gson
import com.rxjava.rxlife.RxLife
import rxhttp.wrapper.param.RxHttp
import com.app.movie.utils.SPUtils
class MovieDetailActivity : BaseActivity() {
private lateinit var binding: ActivityMovieDetailBinding
private var movieId: Int = 0
private var movieDetailBean: MovieDetailBean? = null
companion object {
const val url = "https://m.maoyan.com/ajax/detailmovie"
}
override fun setLayoutResId() {
binding = ActivityMovieDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
}
override fun setListener() {
binding.toolbar.setNavigationOnClickListener {
finish()
}
}
@SuppressLint("SetTextI18n")
override fun initDatas() {
movieId = intent.getIntExtra("id", 0)
RxHttp.get(url).add("movieId", movieId)
.addHeader(
"Cookie",
"from=; from=; uuid_n_v=v1; iuuid=D3CB9CA0860F11EBBF9F81492E2902A6F5879D1B0EEE48F2A72EA9925E74C610; webp=; ci=; ci=10%2C%E4%B8%8A%E6%B5%B7"
)
.asString()
.to(RxLife.toMain(this))
.subscribe({
movieDetailBean = Gson().fromJson(it, MovieDetailBean::class.java)
movieDetailBean?.detailMovie?.apply {
binding.movieName.text = nm
binding.enm.text = enm
binding.cat.text = cat
binding.src.text = src + "/${dur}分钟"
binding.pubDesc.text = pubDesc
binding.dra.text = dra
//头像
val subUrl = img.substring(img.indexOf(".h") + 2, img.length)
GlideImageLoader.displayImage("https://p0.meituan.net/${subUrl}", binding.img)
}
}, {
})
}
/**
* 购票
*/
fun booking(view: View) {
if (SPUtils.getObject(this, "userInfo", UserInfoBean::class.java) != null) {
val intent = Intent(this, BookingActivity::class.java)
intent.putExtra("movie", movieDetailBean?.detailMovie)
startActivity(intent)
} else {
startActivity(Intent(this, LoginActivity::class.java))
}
}
}
| 1 | null |
1
| 1 |
1a914f1c68b076e2304844a641f49fabd8f285f9
| 2,620 |
Java-based-movie-ticket-booking-system
|
MIT License
|
bbfgradle/tmp/arrays/JavaAndKotlin/javaAndKotlin368.kt
|
DaniilStepanov
| 346,008,310 | false | null |
// FILE: BoxFunKt.java
import kotlin.Metadata;
import org.jetbrains.annotations.NotNull;
class BoxFunKt {
@NotNull
public static final String box() {
String x = "OK";
(new StringBuilder()).append(x);
return x;
}
}
// FILE: capturedLocalLateinit.kt
fun runNoInline(f: () -> Unit) = f()
| 1 | null |
1
| 1 |
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
| 317 |
kotlinWithFuzzer
|
Apache License 2.0
|
plugins/uast-common/src/org/jetbrains/uast/internal/internalUastUtils.kt
|
AlexeyTsvetkov
| 17,321,988 | true |
{"Java": 22837096, "Kotlin": 18913890, "JavaScript": 180163, "HTML": 47571, "Protocol Buffer": 46162, "Lex": 18051, "Groovy": 13300, "ANTLR": 9729, "CSS": 9358, "IDL": 6426, "Shell": 4704, "Batchfile": 3703}
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import com.intellij.psi.PsiType
internal val ERROR_NAME = "<error>"
internal val LINE_SEPARATOR = System.getProperty("line.separator") ?: "\n"
val String.withMargin: String
get() = lines().joinToString(LINE_SEPARATOR) { " " + it }
internal operator fun String.times(n: Int) = this.repeat(n)
internal fun List<UElement>.asLogString() = joinToString(LINE_SEPARATOR) { it.asLogString().withMargin }
internal fun StringBuilder.appendWithSpace(s: String) {
if (s.isNotEmpty()) {
append(s)
append(' ')
}
}
internal tailrec fun UExpression.unwrapParenthesis(): UExpression = when (this) {
is UParenthesizedExpression -> expression.unwrapParenthesis()
else -> this
}
internal fun <T> lz(f: () -> T) = lazy(LazyThreadSafetyMode.NONE, f)
internal val PsiType.name: String
get() = getCanonicalText(false)
| 1 |
Java
|
0
| 2 |
72a84083fbe50d3d12226925b94ed0fe86c9d794
| 1,474 |
kotlin
|
Apache License 2.0
|
app/src/main/java/dev/eakin/blob/ui/main/BlobCollective.kt
|
GregEakin
| 230,686,423 | false |
{"Gradle": 4, "Java Properties": 2, "Prolog": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 23, "Java": 2, "XML": 23}
|
/*
* Copyright 2019 Greg Eakin
*
* 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.eakin.blob.ui.main
import android.graphics.Canvas
import org.koin.core.KoinComponent
import org.koin.core.inject
import org.koin.core.parameter.parametersOf
import kotlin.math.sqrt
import kotlin.random.Random
interface BlobCollective {
val numActive: Int
fun split()
fun join()
fun findLargest(exclude: Blob?): Blob?
fun findSmallest(exclude: Blob?): Blob?
fun findClosest(neighbor: Blob): Blob?
fun findClosest(x: Float, y: Float, radius: Float): Blob?
fun move(dt: Float)
fun sc(env: Environment)
fun setForce(value: Vector)
fun addForce(force: Vector)
fun draw(canvas: Canvas)
}
class BlobCollectiveImpl(val maxBlobs: Int) : BlobCollective, KoinComponent {
init {
if (maxBlobs < 1)
throw Exception("Need to allow at least one blob in the collective.")
}
private val blobs: MutableList<Blob> by inject()
override val numActive: Int
get() = blobs.size
override fun split() {
if (numActive >= maxBlobs)
return
val motherBlob = findLargest(null) ?: return
motherBlob.scale(0.75f)
val newBlob : Blob by inject{ parametersOf(motherBlob) }
for (blob in blobs) {
blob.linkBlob(newBlob)
newBlob.linkBlob(blob)
}
blobs.add(newBlob)
//Log.d("BlobAndroid", "New blob ${blobs.size}")
//newBlob
}
override fun join() {
if (numActive <= 1)
return
val smallest = findSmallest(null) ?: return
val closest = findClosest(smallest) ?: return
val r1 = smallest.radius.toDouble()
val r2 = closest.radius.toDouble()
val length = sqrt(r1 * r1 + r2 * r2)
val factor = 0.945 * length / closest.radius
closest.scale(factor.toFloat())
blobs.remove(smallest)
for (blob in blobs)
blob.unlinkBlob(smallest)
//Log.d("BlobAndroid", "Delete blob ${blobs.size}")
//xsmallest
}
override fun findLargest(exclude: Blob?): Blob? {
var maxRadius = Float.MIN_VALUE
var largest: Blob? = null
for (blob in blobs) {
if (blob === exclude)
continue
if (blob.radius <= maxRadius)
continue
maxRadius = blob.radius
largest = blob
}
return largest
}
override fun findSmallest(exclude: Blob?): Blob? {
var minRadius = Float.MAX_VALUE
var smallest: Blob? = null
for (blob in blobs) {
if (blob === exclude)
continue
if (blob.radius >= minRadius)
continue
minRadius = blob.radius
smallest = blob
}
return smallest
}
override fun findClosest(neighbor: Blob): Blob? {
var minDistance = Float.MAX_VALUE
var closest: Blob? = null
for (blob in blobs) {
if (blob === neighbor)
continue
val aXbX = neighbor.x - blob.x
val aYbY = neighbor.y - blob.y
val distance = aXbX * aXbX + aYbY * aYbY
if (distance >= minDistance)
continue
minDistance = distance
closest = blob
}
return closest
}
override fun findClosest(x: Float, y: Float, radius: Float): Blob? {
var minDistance = Float.MAX_VALUE
var closest: Blob? = null
for (blob in blobs) {
val aXbX = x - blob.x
val aYbY = y - blob.y
val distance = aXbX * aXbX + aYbY * aYbY
if (distance >= minDistance)
continue
val hit = blob.radius + radius
if (distance > hit * hit)
continue
minDistance = distance
closest = blob
}
return closest
}
override fun move(dt: Float) {
for (blob in blobs)
blob.move(dt)
}
override fun sc(env: Environment) {
for (blob in blobs)
blob.sc(env)
}
override fun setForce(value: Vector) {
for (blob in blobs) {
val force = if (blob.selected?.blob === blob) Vector(0.0f, 0.0f) else value
blob.setForce(force)
}
}
override fun addForce(force: Vector) {
for (blob in blobs) {
if (blob.selected?.blob === blob)
continue
val x = force.x * (Random.nextFloat() * 0.75f + 0.25f)
val y = force.y * (Random.nextFloat() * 0.75f + 0.25f)
val newForce = Vector(x, y)
blob.addForce(newForce)
}
}
override fun draw(canvas: Canvas) {
for (blob in blobs)
blob.draw(canvas)
}
}
| 0 |
Kotlin
|
0
| 0 |
c669f4be594fe885d7094f7e8182da97eb17f7dc
| 5,377 |
BlobSallad.Android
|
Apache License 2.0
|
letsrebug/app/src/main/java/com/gitclonepeace/letsrebug/mfragment/ChatsFragment.kt
|
asv0018
| 293,206,641 | false | null |
package com.gitclonepeace.letsrebug.mfragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener
import com.google.firebase.iid.FirebaseInstanceId
import com.teamvpn.devhub.AdapterClasses.UserAdapter
import com.teamvpn.devhub.ModelClass.Chatlist
import com.teamvpn.devhub.ModelClass.Users
import com.teamvpn.devhub.Notifications.Token
import com.teamvpn.devhub.R
class ChatsFragment : Fragment() {
private var userAdapter: UserAdapter? = null
private var mUsers: List<Users>? = null
private var userChatlist: List<Chatlist>? = null
lateinit var recycler_view_chatlist: RecyclerView
private var firebaseUser: FirebaseUser? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_chats, container, false)
recycler_view_chatlist = view.findViewById(R.id.recycler_view_chatlist)
recycler_view_chatlist.setHasFixedSize(true)
recycler_view_chatlist.layoutManager = LinearLayoutManager(context)
firebaseUser = FirebaseAuth.getInstance().currentUser
userChatlist = ArrayList()
val ref = FirebaseDatabase.getInstance().reference.child("ChatList").child(firebaseUser!!.uid)
ref!!.addValueEventListener(object: ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
(userChatlist as ArrayList).clear()
for(dataSnapshot in p0.children)
{
val chatlist = dataSnapshot.getValue(Chatlist::class.java)
(userChatlist as ArrayList).add(chatlist!!)
}
retrieveChatList()
}
override fun onCancelled(error: DatabaseError) {
}
})
updateToken(FirebaseInstanceId.getInstance().token)
return view
}
private fun updateToken(token: String?) {
val ref = FirebaseDatabase.getInstance().reference.child("Tokens")
val token1 = Token(token!!)
ref.child(firebaseUser!!.uid).setValue(token1)
}
private fun retrieveChatList()
{
mUsers = ArrayList()
val ref = FirebaseDatabase.getInstance().reference.child("ChatUsersDB")
ref!!.addValueEventListener(object: ValueEventListener{
override fun onDataChange(p0: DataSnapshot) {
(mUsers as ArrayList).clear()
for(dataSnapshot in p0.children)
{
val user = dataSnapshot.getValue(Users::class.java)
for(eachChatList in userChatlist!!)
{
if(user!!.getUID().equals(eachChatList.getId()))
{
(mUsers as ArrayList).add(user!!)
}
}
}
//userAdapter = UserAdapter(context!!, (mUsers as ArrayList<Users>), true)
userAdapter = UserAdapter(context, (mUsers as ArrayList<Users>), true)
recycler_view_chatlist.adapter = userAdapter
}
override fun onCancelled(error: DatabaseError) {
}
})
}
}
| 0 |
Kotlin
|
0
| 0 |
19104b25c35b3dde3123d031838a43d3e869a2cb
| 3,816 |
HACK-GUJARAT-SUBMISSION
|
Boost Software License 1.0
|
utils/src/main/kotlin/com/mirage/utils/messaging/streams/impls/ServerMessageOutputStream.kt
|
ardenit
| 159,560,530 | false |
{"Gradle": 12, "Markdown": 5, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Kotlin": 148, "Proguard": 1, "XML": 9, "Java Properties": 1, "Lua": 17, "JSON": 27, "Java": 2}
|
package com.mirage.utils.messaging.streams.impls
import com.mirage.utils.OUTER_DLMTR
import com.mirage.utils.messaging.ServerMessage
import com.mirage.utils.messaging.serializeServerMessage
import com.mirage.utils.messaging.streams.ServerMessageWriter
import java.io.BufferedWriter
import java.io.OutputStream
import java.io.OutputStreamWriter
class ServerMessageOutputStream(outputStream: OutputStream) : ServerMessageWriter {
private val out = BufferedWriter(OutputStreamWriter(outputStream))
override fun write(msg: ServerMessage) {
out.write(serializeServerMessage(msg))
out.write(OUTER_DLMTR.toString())
}
override fun flush() = out.flush()
}
| 0 |
Kotlin
|
0
| 0 |
f94f8bee518f70f5942aacf66afb5887bbb04988
| 685 |
shattered-world
|
Apache License 2.0
|
SimpleLogin/app/src/main/java/io/simplelogin/android/module/settings/view/SenderAddressFormatCardView.kt
|
simple-login
| 244,631,377 | false |
{"Kotlin": 341987}
|
package io.simplelogin.android.module.settings.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import com.google.android.material.card.MaterialCardView
import io.simplelogin.android.databinding.LayoutSenderAddressFormatCardViewBinding
import io.simplelogin.android.databinding.SpinnerRowTextOnlyBinding
import io.simplelogin.android.utils.enums.SenderFormat
import io.simplelogin.android.utils.enums.SenderFormat.*
class SenderAddressFormatCardView : RelativeLayout {
// Initializer
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)
private val binding = LayoutSenderAddressFormatCardViewBinding.inflate(LayoutInflater.from(context), this, true)
init {
background = ContextCompat.getDrawable(context, android.R.color.transparent)
}
private val senderFormats = listOf(A, AT)
// Functions
fun bind(senderFormat: SenderFormat) {
binding.senderAddressFormatSpinner.adapter = SenderAddressFormatSpinnerAdapter(context, senderFormats)
binding.senderAddressFormatSpinner.setSelection(senderFormats.indexOfFirst { it == senderFormat })
}
fun setSenderAddressFormatSpinnerSelectionListener(listener: (SenderFormat) -> Unit) {
val senderAddressFormatSpinnerAdapter = binding.senderAddressFormatSpinner.adapter ?: return
binding.senderAddressFormatSpinner.onItemSelectedListener =
object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(p0: AdapterView<*>?) = Unit
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedSenderFormat = senderAddressFormatSpinnerAdapter.getItem(position) as SenderFormat
listener(selectedSenderFormat)
}
}
}
}
class SenderAddressFormatSpinnerAdapter(
private val context: Context,
private val senderFormats: List<SenderFormat>
) : BaseAdapter() {
override fun getCount() = senderFormats.size
override fun getItem(position: Int) = senderFormats[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view: View
val binding: SpinnerRowTextOnlyBinding
if (convertView == null) {
binding = SpinnerRowTextOnlyBinding.inflate(LayoutInflater.from(context), parent, false)
view = binding.root
view.tag = binding
} else {
view = convertView
binding = convertView.tag as SpinnerRowTextOnlyBinding
}
binding.textView.text = getItem(position).description
return view
}
}
| 23 |
Kotlin
|
39
| 312 |
46a0b7a7d9c560d7f230b11788d9c52ab74d50d5
| 3,148 |
Simple-Login-Android
|
Apache License 2.0
|
src/main/kotlin/com/beside/daldal/domain/review/dto/ReviewUpdateDTO.kt
|
daldal-nimble
| 618,776,701 | false | null |
package com.beside.daldal.domain.review.dto
import com.beside.daldal.domain.review.entity.Review
import com.beside.daldal.domain.review.entity.ReviewFeature
import kotlin.contracts.contract
class ReviewUpdateDTO(
val content: String,
val features: List<ReviewFeature>
) {
fun toEntity(entity: Review, imageUrl: String): Review {
return Review(
id = entity.id,
content = content,
features = features,
courseId = entity.courseId,
memberId = entity.memberId,
favorite = entity.favorite,
imageUrl = imageUrl,
comments = entity.comments
)
}
}
| 0 |
Kotlin
|
0
| 3 |
b4bc82556bc3309e2136bca31c521ee28d5f6839
| 668 |
Nimble
|
Apache License 2.0
|
src/main/kotlin/net/megavex/redikt/protocol/types/SimpleString.kt
|
MegavexNetwork
| 666,473,616 | false | null |
package net.megavex.redikt.protocol.types
@JvmInline
public value class SimpleString(public val value: String) : RedisType<String> {
override fun unwrap(): String {
return value
}
}
| 0 |
Kotlin
|
0
| 0 |
6ead1e80dfe9e4d248cdadeb6e14a4f160a37288
| 199 |
redikt
|
MIT License
|
app/src/main/java/com/cmj/wanandroid/content/ContentRepository.kt
|
mikechenmj
| 590,477,705 | false | null |
package com.cmj.wanandroid.content
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.cmj.wanandroid.network.NetworkEngine
import com.cmj.wanandroid.network.api.ContentApi
import com.cmj.wanandroid.network.bean.Content
import com.cmj.wanandroid.network.bean.PageModule
import com.cmj.wanandroid.network.kt.resultWABodyCall
import kotlinx.coroutines.flow.Flow
import retrofit2.await
object ContentRepository {
private val api = NetworkEngine.createApi(ContentApi::class.java)
suspend fun star(content: Content) = api.collect(content.id).resultWABodyCall().await()
suspend fun unStar(content: Content) = api.unCollectOriginId(content.id).resultWABodyCall().await()
suspend fun banner() = api.banner().resultWABodyCall().await()
fun articleListFlow(pageSize: Int = 20, orderType: Int = 0): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource(-1) { page, size ->
if (page == -1) {
val top = api.articleTop().resultWABodyCall().await().getOrThrow()
top.forEach { it.top = true }
PageModule(-1, 0, false, -1, top.size, top.size, top)
} else {
api.articleList(page, size, orderType).resultWABodyCall().await().getOrThrow()
}
}
}
).flow
}
fun articleListWithIdFlow(cid: Int, pageSize: Int = 20, orderType: Int = 0): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource { page, size ->
api.articleListWithId(page, size, cid, orderType).resultWABodyCall().await().getOrThrow()
}
}
).flow
}
fun askListFlow(pageSize: Int = 20): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource { page, size ->
api.qAList(page, size).resultWABodyCall().await().getOrThrow()
}
}
).flow
}
fun shareListFlow(pageSize: Int = 20): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource { page, size ->
api.userArticleList(page, size).resultWABodyCall().await().getOrThrow()
}
}
).flow
}
suspend fun tree() = api.tree().resultWABodyCall().await()
suspend fun projectTree() = api.projectTree().resultWABodyCall().await()
fun projectListFlow(id: Int, pageSize: Int = 20): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource { page, size ->
api.projectList( page, size, id).resultWABodyCall().await().getOrThrow()
}
}
).flow
}
suspend fun wxOfficial() = api.wxArticleChapters().resultWABodyCall().await()
fun wxArticleListFlow(id: Int, pageSize: Int = 20, k: String? = null): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource { page, size ->
api.wxArticleList(id, page, size, k).resultWABodyCall().await().getOrThrow()
}
}
).flow
}
suspend fun hotKey() = api.hotkey().resultWABodyCall().await()
fun queryArticleListFlow(pageSize: Int = 20, k: String): Flow<PagingData<Content>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = pageSize),
pagingSourceFactory = {
ContentPagingSource { page, size ->
api.queryArticle(page, size, k).resultWABodyCall().await().getOrThrow()
}
}
).flow
}
}
| 0 |
Kotlin
|
0
| 0 |
b6ba391b5925a5ebff3040575a813ce9e140cbd3
| 4,435 |
WanAndroid
|
Apache License 2.0
|
src/test/kotlin/net/littlelite/smartrest/PersonTests.kt
|
guildenstern70
| 234,064,216 | false |
{"Kotlin": 21390, "Mustache": 1817, "Dockerfile": 260}
|
/*
* Project SmartREST
* Copyright (c) <NAME> 2022-23
* This software is licensed under MIT License (see LICENSE)
*/
package net.littlelite.smartrest
import net.littlelite.smartrest.dto.NewPersonDTO
import net.littlelite.smartrest.dto.PhoneDTO
import net.littlelite.smartrest.model.Group
import net.littlelite.smartrest.model.Provider
import net.littlelite.smartrest.service.PersonService
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit.jupiter.SpringExtension
@ExtendWith(SpringExtension::class)
@SpringBootTest
internal class PersonTests
{
@Autowired
private lateinit var personService: PersonService
@Test
fun `Should invoke a working person service`()
{
assertThat(this.personService).isNotNull
}
@Test
fun `Should initially have 4 persons`()
{
val persons = this.personService.getAllPersons()
assertThat(persons.size).isEqualTo(4)
}
@Test
fun `Should create and delete a new person`()
{
val phone1 = PhoneDTO("+39-3494838990", Provider.TIM)
val phone2 = PhoneDTO("+49-3339292991", Provider.VODAFONE)
val newPerson = NewPersonDTO(
"Ugo",
"Tognazzi",
"<EMAIL>",
Group.GUEST
)
val created = this.personService.createPerson(
newPerson,
listOf(phone1, phone2)
)
assertThat(created).isNotNull
assertThat(created!!.id).isGreaterThan(0)
assertThat(created.phones.size).isEqualTo(2)
val retrieved = this.personService.getPerson(created.id)
assertThat(retrieved).isNotNull
assertThat(retrieved!!.email).isEqualTo("<EMAIL>")
assertThat(retrieved.phones[0].number).isEqualTo("+39-3494838990")
this.personService.deletePerson(created.id)
assertThat(this.personService.getAllPersons().size).isEqualTo(4)
}
@Test
fun `Should get a person by name and surname`()
{
val alessioPersons = this.personService.getPersonsByFullName("Alessio", "Saltarin")
assertThat(alessioPersons).isNotNull
assertThat(alessioPersons!!.size).isEqualTo(1)
val alessio = alessioPersons[0]
assertThat(alessio.name).isEqualTo("Alessio")
assertThat(alessio.surname).isEqualTo("Saltarin")
}
}
| 0 |
Kotlin
|
0
| 0 |
4a997a10958af35a951335f27af7b17c7c61d716
| 2,556 |
SmartREST
|
MIT License
|
tgbotapi.api/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/api/chat/forum/ReopenGeneralForumTopic.kt
|
InsanusMokrassar
| 163,152,024 | false |
{"Kotlin": 3243076, "Shell": 373}
|
package dev.inmo.tgbotapi.extensions.api.chat.forum
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.requests.chat.forum.ReopenForumTopic
import dev.inmo.tgbotapi.requests.chat.forum.ReopenGeneralForumTopic
import dev.inmo.tgbotapi.types.ChatIdentifier
import dev.inmo.tgbotapi.types.ForumTopic
import dev.inmo.tgbotapi.types.MessageThreadId
import dev.inmo.tgbotapi.types.chat.Chat
suspend fun TelegramBot.reopenGeneralForumTopic(
chatId: ChatIdentifier
) = execute(
ReopenGeneralForumTopic(chatId)
)
suspend fun TelegramBot.reopenGeneralForumTopic(
chat: Chat
) = reopenGeneralForumTopic(chat.id)
| 18 |
Kotlin
|
29
| 358 |
482c375327b7087699a4cb8bb06cb09869f07630
| 631 |
ktgbotapi
|
Apache License 2.0
|
idea/ide-common/src/org/jetbrains/kotlin/idea/util/ImportsUtils.kt
|
zeesh49
| 67,883,175 | true |
{"Java": 17992465, "Kotlin": 15424948, "JavaScript": 177557, "Protocol Buffer": 44176, "HTML": 38996, "Lex": 17538, "ANTLR": 9689, "CSS": 9358, "Groovy": 7541, "IDL": 5313, "Shell": 4704, "Batchfile": 3703}
|
/*
* Copyright 2010-2016 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.
*/
@file:JvmName("ImportsUtils")
package org.jetbrains.kotlin.idea.imports
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.util.ImportInsertHelper
import org.jetbrains.kotlin.idea.util.getFileResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.renderer.render
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.ImportPath
import org.jetbrains.kotlin.resolve.bindingContextUtil.getReferenceTargets
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.descriptorUtil.getImportableDescriptor
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.types.KotlinType
import java.util.*
object ImportPathComparator : Comparator<ImportPath> {
override fun compare(import1: ImportPath, import2: ImportPath): Int {
// alias imports placed last
if (import1.hasAlias() != import2.hasAlias()) {
return if (import1.hasAlias()) +1 else -1
}
// standard library imports last
val stdlib1 = isJavaOrKotlinStdlibImport(import1)
val stdlib2 = isJavaOrKotlinStdlibImport(import2)
if (stdlib1 != stdlib2) {
return if (stdlib1) +1 else -1
}
return import1.toString().compareTo(import2.toString())
}
private fun isJavaOrKotlinStdlibImport(path: ImportPath): Boolean {
val s = path.pathStr
return s.startsWith("java.") || s.startsWith("javax.")|| s.startsWith("kotlin.")
}
}
val DeclarationDescriptor.importableFqName: FqName?
get() {
if (!canBeReferencedViaImport()) return null
return getImportableDescriptor().fqNameSafe
}
fun DeclarationDescriptor.canBeReferencedViaImport(): Boolean {
if (this is PackageViewDescriptor ||
DescriptorUtils.isTopLevelDeclaration(this) ||
this is CallableDescriptor && DescriptorUtils.isStaticDeclaration(this)) {
return !name.isSpecial
}
val parentClass = containingDeclaration as? ClassDescriptor ?: return false
if (!parentClass.canBeReferencedViaImport()) return false
return when (this) {
is ConstructorDescriptor -> !parentClass.isInner // inner class constructors can't be referenced via import
is ClassDescriptor -> true
else -> parentClass.kind == ClassKind.OBJECT
}
}
fun KotlinType.canBeReferencedViaImport(): Boolean {
val descriptor = constructor.declarationDescriptor
return descriptor != null && descriptor.canBeReferencedViaImport()
}
// for cases when class qualifier refers companion object treats it like reference to class itself
fun KtReferenceExpression.getImportableTargets(bindingContext: BindingContext): Collection<DeclarationDescriptor> {
val targets = bindingContext[BindingContext.SHORT_REFERENCE_TO_COMPANION_OBJECT, this]?.let { listOf(it) }
?: getReferenceTargets(bindingContext)
return targets.map { it.getImportableDescriptor() }.toSet()
}
fun prepareOptimizedImports(
file: KtFile,
descriptorsToImport: Collection<DeclarationDescriptor>,
nameCountToUseStarImport: Int,
nameCountToUseStarImportForMembers: Int,
isInPackagesToUseStarImport: (FqName) -> Boolean
): List<ImportPath>? {
val importInsertHelper = ImportInsertHelper.getInstance(file.project)
val aliasImports = buildAliasImportMap(file)
val importsToGenerate = HashSet<ImportPath>()
val descriptorsByParentFqName = hashMapOf<FqName, MutableSet<DeclarationDescriptor>>()
for (descriptor in descriptorsToImport) {
val fqName = descriptor.importableFqName!!
val container = descriptor.containingDeclaration
val parentFqName = fqName.parent()
val canUseStarImport = when {
parentFqName.isRoot -> false
(container as? ClassDescriptor)?.kind == ClassKind.OBJECT -> false
else -> true
}
if (canUseStarImport) {
val descriptors = descriptorsByParentFqName.getOrPut(parentFqName) { hashSetOf() }
descriptors.add(descriptor)
}
else {
importsToGenerate.add(ImportPath(fqName, false))
}
}
val classNamesToCheck = HashSet<FqName>()
fun isImportedByDefault(fqName: FqName) = importInsertHelper.isImportedWithDefault(ImportPath(fqName, false), file)
for (parentFqName in descriptorsByParentFqName.keys) {
val descriptors = descriptorsByParentFqName[parentFqName]!!
val fqNames = descriptors.map { it.importableFqName!! }.toSet()
val isMember = descriptors.first().containingDeclaration is ClassDescriptor
val nameCountToUseStar = if (isMember)
nameCountToUseStarImportForMembers
else
nameCountToUseStarImport
val explicitImports = fqNames.size < nameCountToUseStar && !isInPackagesToUseStarImport(parentFqName)
if (explicitImports) {
for (fqName in fqNames) {
if (!isImportedByDefault(fqName)) {
importsToGenerate.add(ImportPath(fqName, false))
}
}
}
else {
for (descriptor in descriptors) {
if (descriptor is ClassDescriptor) {
classNamesToCheck.add(descriptor.importableFqName!!)
}
}
if (!fqNames.all(::isImportedByDefault)) {
importsToGenerate.add(ImportPath(parentFqName, true))
}
}
}
// now check that there are no conflicts and all classes are really imported
val fileWithImportsText = buildString {
append("package ").append(file.packageFqName.toUnsafe().render()).append("\n")
importsToGenerate.filter { it.isAllUnder }.map { "import " + it.pathStr }.joinTo(this, "\n")
}
val fileWithImports = KtPsiFactory(file).createAnalyzableFile("Dummy.kt", fileWithImportsText, file)
val scope = fileWithImports.getResolutionFacade().getFileResolutionScope(fileWithImports)
for (fqName in classNamesToCheck) {
if (scope.findClassifier(fqName.shortName(), NoLookupLocation.FROM_IDE)?.importableFqName != fqName) {
// add explicit import if failed to import with * (or from current package)
importsToGenerate.add(ImportPath(fqName, false))
val parentFqName = fqName.parent()
val parentDescriptors = descriptorsByParentFqName[parentFqName]!!
for (descriptor in parentDescriptors.filter { it.importableFqName == fqName }) {
parentDescriptors.remove(descriptor)
}
if (parentDescriptors.isEmpty()) { // star import is not really needed
importsToGenerate.remove(ImportPath(parentFqName, true))
}
}
}
//TODO: drop unused aliases?
aliasImports.mapTo(importsToGenerate) { ImportPath(it.value, false, it.key) }
val sortedImportsToGenerate = importsToGenerate.sortedWith(importInsertHelper.importSortComparator)
// check if no changes to imports required
val oldImports = file.importDirectives
if (oldImports.size == sortedImportsToGenerate.size && oldImports.map { it.importPath } == sortedImportsToGenerate) return null
return sortedImportsToGenerate
}
private fun buildAliasImportMap(file: KtFile): Map<Name, FqName> {
val imports = file.importDirectives
val aliasImports = HashMap<Name, FqName>()
for (import in imports) {
val path = import.importPath ?: continue
val aliasName = path.alias
if (aliasName != null && aliasName != path.fqnPart().shortName() /* we do not keep trivial aliases */) {
aliasImports.put(aliasName, path.fqnPart())
}
}
return aliasImports
}
| 0 |
Java
|
0
| 1 |
261a30029907fedcecbe760aec97021d85a9ba9a
| 8,772 |
kotlin
|
Apache License 2.0
|
cucumber/src/test/kotlin/cucu/StepDefs.kt
|
dickensas
| 215,822,427 | false | null |
package cucu
import io.cucumber.java.en.Then
import io.cucumber.java.en.Given
import io.cucumber.java.en.When
import io.cucumber.core.api.Scenario
import io.cucumber.java8.En
import junit.framework.Assert.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.WebElement
import org.openqa.selenium.support.ui.WebDriverWait
class StepDefs: En {
private lateinit var today: String
private lateinit var actualAnswer: String
lateinit var driver: WebDriver
init {
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir")+"\\driver\\chromedriver.exe")
driver = ChromeDriver()
Given("I am on the Google search page") {
driver.get("https:\\www.google.com")
}
When("I search for {string}") { query: String ->
val element: WebElement = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys(query)
// Now submit the form. WebDriver will find the form for us from the element
element.submit()
}
Then("the page title should start with {string}") { titleStartsWith: String ->
// Google's search is rendered dynamically with JavaScript
// Wait for the page to load timeout after ten seconds
WebDriverWait(driver, 10L).until { d ->
d.title.toLowerCase().startsWith(titleStartsWith)
}
}
After { scenario: Scenario ->
driver.quit()
}
}
}
| 0 |
C
|
14
| 62 |
6938038a68b05691d0c8b11d98b14be1b3c93008
| 1,605 |
kotlin-gradle-templates
|
MIT License
|
backend/src/main/kotlin/dev/dres/data/model/competition/interfaces/SubmissionFilterFactory.kt
|
dres-dev
| 248,713,193 | false | null |
package dev.dres.data.model.competition.interfaces
import dev.dres.run.filter.SubmissionFilter
/**
* A factory for [SubmissionFilter]s.
*
* @author <NAME>
* @version 1.0.0
*/
interface SubmissionFilterFactory {
/**
* Generates and returns a [SubmissionFilter]. Depending on the implementation, the returned instance
* is a new instance or can re-used.
*
* @return [SubmissionFilter]
*/
fun newFilter(): SubmissionFilter
}
| 35 |
Kotlin
|
1
| 8 |
7dcb10ff97c5a8a1453e54004c91ab63d5c20a14
| 462 |
DRES
|
MIT License
|
app/src/main/java/com/example/chatbot/Lauchpage.kt
|
wssongan26
| 843,516,251 | false |
{"Kotlin": 44931}
|
package com.example.chatbot
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
class Lauchpage : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_lauchpage)
}
// Function to handle login button click
fun onLoginButtonClick(view: View) {
val intent = Intent(this, Login::class.java)
startActivity(intent)
}
// Function to handle sign up button click
fun onSignUpButtonClick(view: View) {
val intent = Intent(this, Register::class.java) // Replace SignUp::class.java with your actual sign-up activity class
startActivity(intent)
}
}
| 0 |
Kotlin
|
0
| 0 |
323bfc35465b87a215063defedcc07973143df4d
| 788 |
HealthyChatbotMobileApp
|
MIT License
|
core/src/main/kotlin/imgui/api/contentRegion.kt
|
kotlin-graphics
| 59,469,938 | false |
{"Gradle Kotlin DSL": 7, "INI": 3, "Shell": 1, "Text": 2, "Ignore List": 1, "Batchfile": 1, "YAML": 2, "Markdown": 1, "Kotlin": 224, "Java": 11, "Gradle": 1, "XML": 10}
|
package imgui.api
import glm_.vec2.Vec2
import imgui.ImGui.contentRegionMaxAbs
// Content region
// - Retrieve available space from a given point. GetContentRegionAvail() is frequently useful.
// - Those functions are bound to be redesigned (they are confusing, incomplete and the Min/Max return values are in local window coordinates which increases confusion)
interface contentRegion {
/** == GetContentRegionMax() - GetCursorPos()
*
* ~GetContentRegionAvail */
val contentRegionAvail: Vec2
get() = g.currentWindow!!.run { contentRegionMaxAbs - dc.cursorPos }
/** current content boundaries (typically window boundaries including scrolling, or current column boundaries), in
* windows coordinates
* FIXME: This is in window space (not screen space!). We should try to obsolete all those functions.
* ~GetContentRegionMax */
val contentRegionMax: Vec2
/** ~GetContentRegionMax */
get() {
val window = g.currentWindow!!
val mx = window.contentRegionRect.max - window.pos
if (window.dc.currentColumns != null || g.currentTable != null)
mx.x = window.workRect.max.x - window.pos.x
return mx
}
/** content boundaries min (roughly (0,0)-Scroll), in window coordinates
* ~GetWindowContentRegionMin */
val windowContentRegionMin: Vec2
get() = g.currentWindow!!.run { contentRegionRect.min - pos }
/** content boundaries max (roughly (0,0)+Size-Scroll) where Size can be override with SetNextWindowContentSize(),
* in window coordinates
* ~GetWindowContentRegionMax */
val windowContentRegionMax: Vec2
get() = g.currentWindow!!.run { contentRegionRect.max - pos }
/** ~GetWindowContentRegionWidth */
val windowContentRegionWidth: Float
get() = g.currentWindow!!.contentRegionRect.width
}
| 23 |
Kotlin
|
36
| 589 |
665b1032094c4f342a4306c0d3adcc944d87d0e7
| 1,899 |
imgui
|
MIT License
|
app/src/main/java/google/badparcelableexception/ViewPagerAdapter.kt
|
sictiru
| 125,563,036 | false | null |
package google.badparcelableexception
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import java.util.*
/**
* Created by andrei on 3/16/18.
*/
class ViewPagerAdapter(fm: FragmentManager) : FragmentStatePagerAdapter(fm) {
var fragments: MutableList<Fragment> = ArrayList()
var fragmentTitles: MutableList<String> = ArrayList()
fun addFragment(fragment: Fragment, title: String) {
this.fragments.add(fragment)
fragmentTitles.add(title)
}
override fun getPageTitle(position: Int): CharSequence? = fragmentTitles.get(position)
override fun getItem(position: Int): Fragment = fragments[position]
override fun getCount(): Int = fragments.size
}
| 0 |
Kotlin
|
0
| 0 |
b57ee5187b20eafda1045563535de5475b6ecc79
| 786 |
BadParcelableException
|
Apache License 2.0
|
ontrack-service/src/main/java/net/nemerosa/ontrack/service/labels/MainBuildLinksServiceImpl.kt
|
nemerosa
| 19,351,480 | false | null |
package net.nemerosa.ontrack.service.labels
import net.nemerosa.ontrack.model.labels.MainBuildLinksConfig
import net.nemerosa.ontrack.model.labels.MainBuildLinksProvider
import net.nemerosa.ontrack.model.labels.MainBuildLinksService
import net.nemerosa.ontrack.model.labels.ProvidedMainBuildLinksConfig
import net.nemerosa.ontrack.model.structure.Project
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class MainBuildLinksServiceImpl(
private val mainBuildLinksProviders: List<MainBuildLinksProvider>
) : MainBuildLinksService {
override fun getMainBuildLinksConfig(project: Project): MainBuildLinksConfig {
// List of all provided configurations
return mainBuildLinksProviders.map { provider ->
provider.getMainBuildLinksConfig(project)
}
// Order them by increasing order
.sortedBy { it.order }
// Folding from left to right
.fold(ProvidedMainBuildLinksConfig.empty) { current, new ->
new.mergeInto(current)
}
// As a configuration
.toMainBuildLinksConfig()
}
}
| 57 | null |
27
| 97 |
7c71a3047401e088ba0c6d43aa3a96422024857f
| 1,237 |
ontrack
|
MIT License
|
core/data/src/iosMain/kotlin/in/surajsau/jisho/data/expected/IosDriverFactory.kt
|
surajsau
| 489,927,815 | false | null |
package `in`.surajsau.jisho.data.expected
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.native.NativeSqliteDriver
import `in`.surajsau.jisho.data.db.Jisho
import org.koin.core.scope.Scope
public actual fun Scope.createDriver(databaseName: String): SqlDriver {
return NativeSqliteDriver(Jisho.Schema, databaseName)
}
| 0 |
Kotlin
|
0
| 1 |
83de51c9040d748b06651d8dbeb1a367d98ea362
| 350 |
Multiplatform-Jisho
|
Apache License 2.0
|
Repairs/app/src/main/java/com/rooio/repairs/ChangeLocationSettings.kt
|
roopairs
| 212,211,326 | false |
{"XML": 431086, "Kotlin": 299391, "Java": 26386}
|
package com.rooio.repairs
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.*
import androidx.arch.core.util.Function
import com.android.volley.Request
import org.json.JSONObject
//Displays the current location of the user in Settings
class ChangeLocationSettings : NavigationBar() {
private lateinit var currentLocation: TextView
private lateinit var errorMessage: TextView
private lateinit var changeLocation: Button
private lateinit var spinner: Spinner
private lateinit var loadingPanel: ProgressBar
private val url = "service-locations/$userLocationID/"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_change_location_settings)
onResume()
initializeVariables()
setNavigationBar()
setActionBar()
createNavigationBar(NavigationType.SETTINGS)
onChangeLocation()
setSettingsSpinner()
onPause()
getCurrentLocation(JsonRequest(false, url, null, responseFunc, errorFunc, true))
}
//Handles when the user clicks the change location button
private fun onChangeLocation() {
changeLocation.setOnClickListener{
startActivity(Intent(this, LocationSettings::class.java))
}
}
//Handles clicking on the spinner items
private fun setSettingsSpinner() {
spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
//Something will always be selected
}
override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) {
val selectedItem = parent.getItemAtPosition(position).toString()
if(selectedItem == "Preferred Providers") {
val spinner: Spinner = findViewById(R.id.settings_spinner)
spinner.onItemSelectedListener = this
startActivity(Intent(this@ChangeLocationSettings, PreferredProvidersSettings::class.java))
}
}
}
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter.createFromResource(
this,
R.array.settings_type,
R.layout.spinner_item
).also { adapter ->
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
// Apply the adapter to the spinner
spinner.adapter = adapter
spinner.setSelection(Intent().getIntExtra("UniqueKey", 1))
}
}
//Initializes UI variables
private fun initializeVariables() {
currentLocation = findViewById(R.id.currentLocation)
errorMessage = findViewById(R.id.errorMessage)
changeLocation = findViewById(R.id.changeLocation)
spinner = findViewById(R.id.settings_spinner)
loadingPanel = findViewById(R.id.loadingPanel)
}
//Requests the current location from the API
private fun getCurrentLocation(request: JsonRequest){
loadingPanel.visibility = View.VISIBLE
requestJson(Request.Method.GET, JsonType.OBJECT, request)
}
//If API returns a location, sets the physical address
@JvmField
var responseFunc = Function<Any, Void?> { response: Any ->
loadingPanel.visibility = View.GONE
val responseObj = response as JSONObject
currentLocation.text = responseObj.getString("physical_address")
null
}
//Handles error if user does not have a location set
@JvmField
var errorFunc = Function<String, Void?> { error: String? ->
loadingPanel.visibility = View.GONE
errorMessage.text = error
null
}
//Animation function for navigation bar
override fun animateActivity(boolean: Boolean)
{
//No animation needed
}
}
| 0 |
XML
|
0
| 0 |
e81487aba0a997812769e893dc8e34d21935647f
| 4,090 |
Rooio
|
MIT License
|
core/src/main/kotlin/cn/netdiscovery/command/ExecutionOutputPrinter.kt
|
fengzhizi715
| 183,575,200 | false | null |
package cn.netdiscovery.command
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
/**
*
* @FileName:
* cn.netdiscovery.command.ExecutionOutputPrinter
* @author: <NAME>
* @date: 2020-05-19 17:54
* @since: V1.0 对执行命令内容的打印
*/
class ExecutionOutputPrinter(private val appender: Appender) {
fun getAppender(): Appender = appender
fun handleStdStream(stdInputStream: InputStream, sb:StringBuilder? = null) {
formatStream(stdInputStream, false, sb)
}
fun handleErrStream(errorStream: InputStream) {
formatStream(errorStream, true)
}
fun handleErrMessage(errorMsg: String) {
showOutputLine(errorMsg, true)
}
private fun formatStream(inputStream: InputStream, isError: Boolean, sb:StringBuilder? = null) {
try {
BufferedReader(InputStreamReader(inputStream)).use { br ->
var line: String? = null
while (br.readLine().also { line = it } != null)
showOutputLine(line!!, isError, sb)
}
} catch (e: IOException) {
showOutputLine(e.fillInStackTrace().toString() + CommandExecutor.NEW_LINE, true)
}
}
private fun showOutputLine(line: String, isError: Boolean, sb:StringBuilder? = null) {
if (isError) {
appender.appendErrText(line)
} else {
sb?.let {
it.append(line).append("\r\n")
}
appender.appendStdText(line)
}
}
companion object {
/**
* 默认的 Appender
*/
val DEFAULT_APPENDER = object : Appender {
override fun appendStdText(text: String) {
println(text)
}
override fun appendErrText(text: String) {
System.err.println(text)
}
}
/**
* 默认输出的 Printer
*/
val DEFAULT_OUTPUT_PRINTER = ExecutionOutputPrinter(DEFAULT_APPENDER)
}
}
| 0 |
Kotlin
|
1
| 6 |
992da93f755be23b012d1fdff75e27fc1f962299
| 2,043 |
kcommand
|
Apache License 2.0
|
shared/src/commonMain/kotlin/ui/theme/Type.kt
|
exyte
| 662,910,206 | false | null |
package ui.theme
import androidx.compose.material.Typography
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
//import com.exyte.composesample.R
//private val rubikFontFamily = FontFamily(
// Font()
//// Typeface.makeFromName()
//// Font("nunito_light.ttf")
//// Font(R.font.nunito_regular, FontWeight.Normal),
//// Font(R.font.nunito_bold, FontWeight.Bold),
//// Font(R.font.nunito_black, FontWeight.Black),
//)
//private val abrilFontFamily = FontFamily(
//// Font(R.font.abril_fatface, FontWeight.Bold)
//)
//
//val Typography = Typography(
// defaultFontFamily = rubikFontFamily,
// h4 = TextStyle(
// fontFamily = abrilFontFamily,
// fontWeight = FontWeight.Bold,
// fontSize = 34.sp,
// letterSpacing = 0.25.sp
// ),
// h5 = TextStyle(
// fontFamily = abrilFontFamily,
// fontWeight = FontWeight.Bold,
// fontSize = 24.sp,
// ),
//)
//object Fonts {
// @Composable
// fun rubikFontFamily() = FontFamily(
// font(
// "JetBrains Mono",
// "jetbrainsmono_regular",
// FontWeight.Normal,
// FontStyle.Normal
// ),
// font(
// "JetBrains Mono",
// "jetbrainsmono_italic",
// FontWeight.Normal,
// FontStyle.Italic
// ),
//
// font(
// "JetBrains Mono",
// "jetbrainsmono_bold",
// FontWeight.Bold,
// FontStyle.Normal
// ),
// font(
// "JetBrains Mono",
// "jetbrainsmono_bold_italic",
// FontWeight.Bold,
// FontStyle.Italic
// ),
//
// font(
// "JetBrains Mono",
// "jetbrainsmono_extrabold",
// FontWeight.ExtraBold,
// FontStyle.Normal
// ),
// font(
// "JetBrains Mono",
// "jetbrainsmono_extrabold_italic",
// FontWeight.ExtraBold,
// FontStyle.Italic
// ),
//
// font(
// "JetBrains Mono",
// "jetbrainsmono_medium",
// FontWeight.Medium,
// FontStyle.Normal
// ),
// font(
// "JetBrains Mono",
// "jetbrainsmono_medium_italic",
// FontWeight.Medium,
// FontStyle.Italic
// )
// )
//}
| 0 |
Kotlin
|
5
| 44 |
822d1bdc2149e855db16c65570f2ccc3e650ba1f
| 2,649 |
ComposeMultiplatformDribbbleAudio
|
Apache License 2.0
|
app/src/main/java/com/qiyei/android/common/ui/activity/MainActivity.kt
|
qiyei-android
| 328,588,082 | false |
{"Java": 64638, "Kotlin": 8198}
|
package com.qiyei.android.common.ui.activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.qiyei.android.common.R
import com.qiyei.android.common.databinding.ActivityMainBinding
import com.qiyei.android.common.entity.MainMenu
import com.qiyei.android.common.listener.OnItemClickListener
import com.qiyei.android.common.ui.adapter.MainMenuAdapter
import com.qiyei.android.common.ui.viewmodel.MainMenuViewModel
import com.qiyei.android.common.ui.view.CategoryItemDecoration
import java.util.*
class MainActivity : AppCompatActivity() {
private val mMenuList: MutableList<MainMenu> = ArrayList()
private val names = arrayOf(
"测试1 Xml Demo"
)
private val clazzs = arrayOf<Class<out Activity>>(
XmlDemoActivity::class.java
)
/**
* ViewModel
*/
private lateinit var mMenuViewModel: MainMenuViewModel
private lateinit var mMenuAdapter: MainMenuAdapter
private lateinit var mActivityMainBinding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mActivityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mActivityMainBinding.root)
initView()
initData()
}
private fun initView() {
mActivityMainBinding.recyclerView.layoutManager = LinearLayoutManager(this)
mActivityMainBinding.recyclerView.addItemDecoration(CategoryItemDecoration(getDrawable(R.drawable.recyclerview_decoration)))
//初始化Adapter
mMenuAdapter = MainMenuAdapter(this,mutableListOf<MainMenu>())
mMenuAdapter.mClickListener = MyListener()
//初始化ViewModel 2.2.0 用新方法初始化
mMenuViewModel = ViewModelProvider(this)[MainMenuViewModel::class.java]
mMenuViewModel.liveData.observe(
this,
Observer { mainMenus ->
//update UI
mMenuAdapter.mDatas = mainMenus
})
mActivityMainBinding.recyclerView.adapter = mMenuAdapter
}
private fun initData() {
for (i in names.indices) {
val menu = MainMenu(i + 1, names[i], clazzs[i])
mMenuList.add(menu)
}
//主动更新数据
mMenuViewModel.liveData.value = mMenuList
}
/**
* 跳转到菜单
* @param menu
*/
fun gotoMenuActivity(menu: MainMenu) {
startActivity(Intent(this,menu.clazz))
}
private inner class MyListener : OnItemClickListener<MainMenu> {
override fun click(v: View, item: MainMenu, position: Int) {
gotoMenuActivity(item)
}
}
}
| 1 | null |
1
| 1 |
8c0e88a6e68aaeaca3146b8f4590aa15f3c4e25f
| 2,841 |
lib_common
|
MIT License
|
kotlin/examples/src/main/kotlin/examples/neohookean/simple/tensor/dynamic/Vertices.kt
|
facebookresearch
| 495,505,391 | false | null |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package examples.neohookean.simple.tensor.dynamic
import org.diffkt.*
class Vertices(val x: DTensor, val v: DTensor, val m: DTensor) {
fun preBackwardEulerOptim(h: Float): Vertices = withX(this.x + h * this.v)
fun postBackwardEulerOptim(x: DTensor, h: Float): Vertices = withXV(x, (x - this.x) / h)
fun withX(x: DTensor): Vertices = Vertices(x, v, m)
fun withV(v: DTensor): Vertices = Vertices(x, v, m)
fun withXV(x: DTensor, v: DTensor): Vertices = Vertices(x, v, m)
}
| 62 |
Jupyter Notebook
|
3
| 55 |
710f403719bb89e3bcf00d72e53313f8571d5230
| 683 |
diffkt
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.