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
src/main/kotlin/com/github/jomof/kane/Kane.kt
jomof
320,425,199
false
null
package com.github.jomof.kane import com.github.jomof.kane.csv.CsvRowIoProvider import com.github.jomof.kane.impl.functions.AlgebraicSummaryFunction import com.github.jomof.kane.impl.sheet.Sheet import com.github.jomof.kane.impl.sheet.possibleDataFormats import com.github.jomof.kane.impl.sheet.showExcelColumnTags import com.github.jomof.kane.impl.sheet.showRowAndColumnForSingleCell import java.io.File /** * Global metadata about the Kane system. */ class Kane { companion object { /** * Folder used for caching intermediates. May be safely deleted. */ val userCacheFolder: File get() { val result = File(System.getProperty("user.home")).resolve(".kane") result.mkdirs() return result } /** * List of data formats supported by Kane. */ val dataFormats: Sheet = sheetOf { nameColumn(0, "format") nameColumn(1, "type") val a1 by possibleDataFormats.map { it.toString() } val b1 by possibleDataFormats.map { it.type.simpleName } listOf(a1, b1) }.showExcelColumnTags(false).showRowAndColumnForSingleCell(true) /** * List of statistics functions that take one parameter. */ val unaryStatisticsFunctions = listOf( count, nans, mean, min, percentile25, median, percentile75, max, variance, stdev, skewness, kurtosis, cv, sum ).map { it as AlgebraicSummaryFunction } /** * List of functions that take one parameter. */ val unaryFunctions = listOf( sin, cos, lrelu, lstep, logit, exp, relu, tanh, step, negate ).map { it } /** * Internal metrics. */ val metrics = KaneMetrics() } /** * IO providers. */ val ioProviders = listOf( CsvRowIoProvider() ) } class KaneMetrics( /** * Number of times Sequence<Row> was fully instantiated into a sheet. */ var sheetInstatiations: Int = 0 )
0
Kotlin
0
0
f841b79c6f826713a3e1110498cfe38dc4968e64
2,354
kane
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/psi/psiUtil/jetPsiUtil.kt
staltz
39,123,650
false
{"Markdown": 34, "XML": 688, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18742, "Java": 4339, "Protocol Buffer": 4, "Text": 4184, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 72, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.psi.psiUtil import com.intellij.extapi.psi.StubBasedPsiElementBase import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import com.intellij.psi.PsiParameter import com.intellij.psi.PsiParameterList import com.intellij.psi.PsiWhiteSpace import com.intellij.psi.stubs.StubElement import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.JetNodeTypes import org.jetbrains.kotlin.lexer.JetTokens import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.stubs.KotlinClassOrObjectStub import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall import org.jetbrains.kotlin.resolve.calls.model.ArgumentMatch import org.jetbrains.kotlin.types.expressions.OperatorConventions import java.util.ArrayList import java.util.Collections import kotlin.test.assertTrue // NOTE: in this file we collect only Kotlin-specific methods working with PSI and not modifying it // ----------- Calls and qualified expressions --------------------------------------------------------------------------------------------- public fun JetCallElement.getCallNameExpression(): JetSimpleNameExpression? { val calleeExpression = getCalleeExpression() ?: return null return when (calleeExpression) { is JetSimpleNameExpression -> calleeExpression is JetConstructorCalleeExpression -> calleeExpression.getConstructorReferenceExpression() else -> null } } /** * Returns enclosing qualifying element for given [[JetSimpleNameExpression]] * ([[JetQualifiedExpression]] or [[JetUserType]] or original expression) */ public fun JetSimpleNameExpression.getQualifiedElement(): JetElement { val baseExpression: JetElement = (getParent() as? JetCallExpression) ?: this val parent = baseExpression.getParent() return when (parent) { is JetQualifiedExpression -> if (parent.getSelectorExpression().isAncestor(baseExpression)) parent else baseExpression is JetUserType -> if (parent.getReferenceExpression().isAncestor(baseExpression)) parent else baseExpression else -> baseExpression } } public fun JetSimpleNameExpression.getTopmostParentQualifiedExpressionForSelector(): JetQualifiedExpression? { return sequence<JetExpression>(this) { val parentQualified = it.getParent() as? JetQualifiedExpression if (parentQualified?.getSelectorExpression() == it) parentQualified else null }.last() as? JetQualifiedExpression } /** * Returns rightmost selector of the qualified element (null if there is no such selector) */ public fun JetElement.getQualifiedElementSelector(): JetElement? { return when (this) { is JetSimpleNameExpression -> this is JetCallExpression -> getCalleeExpression() is JetQualifiedExpression -> { val selector = getSelectorExpression() if (selector is JetCallExpression) selector.getCalleeExpression() else selector } is JetUserType -> getReferenceExpression() else -> null } } public fun JetSimpleNameExpression.getReceiverExpression(): JetExpression? { val parent = getParent() when { parent is JetQualifiedExpression && !isImportDirectiveExpression() -> { val receiverExpression = parent.getReceiverExpression() // Name expression can't be receiver for itself if (receiverExpression != this) { return receiverExpression } } parent is JetCallExpression -> { //This is in case `a().b()` val callExpression = parent val grandParent = callExpression.getParent() if (grandParent is JetQualifiedExpression) { val parentsReceiver = grandParent.getReceiverExpression() if (parentsReceiver != callExpression) { return parentsReceiver } } } parent is JetBinaryExpression && parent.getOperationReference() == this -> { return if (parent.getOperationToken() in OperatorConventions.IN_OPERATIONS) parent.getRight() else parent.getLeft() } parent is JetUnaryExpression && parent.getOperationReference() == this -> { return parent.getBaseExpression()!! } parent is JetUserType -> { val qualifier = parent.getQualifier() if (qualifier != null) { return qualifier.getReferenceExpression()!! } } } return null } public fun JetElement.getQualifiedExpressionForSelector(): JetQualifiedExpression? { val parent = getParent() return if (parent is JetQualifiedExpression && parent.getSelectorExpression() == this) parent else null } public fun JetElement.getQualifiedExpressionForSelectorOrThis(): JetElement { return getQualifiedExpressionForSelector() ?: this } public fun JetExpression.isDotReceiver(): Boolean = (getParent() as? JetDotQualifiedExpression)?.getReceiverExpression() == this public fun JetElement.getCalleeHighlightingRange(): TextRange { val annotationEntry: JetAnnotationEntry = PsiTreeUtil.getParentOfType<JetAnnotationEntry>( this, javaClass<JetAnnotationEntry>(), /* strict = */false, javaClass<JetValueArgumentList>() ) ?: return getTextRange() val startOffset = annotationEntry.getAtSymbol()?.getTextRange()?.getStartOffset() ?: annotationEntry.getCalleeExpression()!!.startOffset return TextRange(startOffset, annotationEntry.getCalleeExpression()!!.endOffset) } // ---------- Block expression ------------------------------------------------------------------------------------------------------------- public fun JetElement.blockExpressionsOrSingle(): Sequence<JetElement> = if (this is JetBlockExpression) getStatements().asSequence() else sequenceOf(this) public fun JetExpression.lastBlockStatementOrThis(): JetExpression = (this as? JetBlockExpression)?.getStatements()?.lastOrNull() ?: this public fun JetBlockExpression.contentRange(): PsiChildRange { val first = (getLBrace()?.getNextSibling() ?: getFirstChild()) ?.siblings(withItself = false) ?.firstOrNull { it !is PsiWhiteSpace } val rBrace = getRBrace() if (first == rBrace) return PsiChildRange.EMPTY val last = rBrace!! .siblings(forward = false, withItself = false) .first { it !is PsiWhiteSpace } return PsiChildRange(first, last) } // ----------- Inheritance ----------------------------------------------------------------------------------------------------------------- public fun JetClass.isInheritable(): Boolean { return isInterface() || hasModifier(JetTokens.OPEN_KEYWORD) || hasModifier(JetTokens.ABSTRACT_KEYWORD) } public fun JetDeclaration.isOverridable(): Boolean { val parent = getParent() if (!(parent is JetClassBody || parent is JetParameterList)) return false val klass = parent.getParent() if (!(klass is JetClass && klass.isInheritable())) return false if (hasModifier(JetTokens.FINAL_KEYWORD) || hasModifier(JetTokens.PRIVATE_KEYWORD)) return false return klass.isInterface() || hasModifier(JetTokens.ABSTRACT_KEYWORD) || hasModifier(JetTokens.OPEN_KEYWORD) || hasModifier(JetTokens.OVERRIDE_KEYWORD) } public fun JetClass.isAbstract(): Boolean = isInterface() || hasModifier(JetTokens.ABSTRACT_KEYWORD) /** * Returns the list of unqualified names that are indexed as the superclass names of this class. For the names that might be imported * via an aliased import, includes both the original and the aliased name (reference resolution during inheritor search will sort this out). * * @return the list of possible superclass names */ public fun StubBasedPsiElementBase<out KotlinClassOrObjectStub<out JetClassOrObject>>.getSuperNames(): List<String> { fun addSuperName(result: MutableList<String>, referencedName: String): Unit { result.add(referencedName) val file = getContainingFile() if (file is JetFile) { val directive = file.findImportByAlias(referencedName) if (directive != null) { var reference = directive.getImportedReference() while (reference is JetDotQualifiedExpression) { reference = reference.getSelectorExpression() } if (reference is JetSimpleNameExpression) { result.add(reference.getReferencedName()) } } } } assertTrue(this is JetClassOrObject) val stub = getStub() if (stub != null) { return stub.getSuperNames() } val specifiers = (this as JetClassOrObject).getDelegationSpecifiers() if (specifiers.isEmpty()) return Collections.emptyList<String>() val result = ArrayList<String>() for (specifier in specifiers) { val superType = specifier.getTypeAsUserType() if (superType != null) { val referencedName = superType.getReferencedName() if (referencedName != null) { addSuperName(result, referencedName) } } } return result } // ------------ Annotations ---------------------------------------------------------------------------------------------------------------- // Annotations on labeled expression lies on it's base expression public fun JetExpression.getAnnotationEntries(): List<JetAnnotationEntry> { val parent = getParent() return when (parent) { is JetAnnotatedExpression -> parent.getAnnotationEntries() is JetLabeledExpression -> parent.getAnnotationEntries() else -> emptyList<JetAnnotationEntry>() } } public fun JetAnnotationsContainer.collectAnnotationEntriesFromStubOrPsi(): List<JetAnnotationEntry> { return when (this) { is StubBasedPsiElementBase<*> -> getStub()?.collectAnnotationEntriesFromStubElement() ?: collectAnnotationEntriesFromPsi() else -> collectAnnotationEntriesFromPsi() } } private fun StubElement<*>.collectAnnotationEntriesFromStubElement(): List<JetAnnotationEntry> { return getChildrenStubs().flatMap { child -> when (child.getStubType()) { JetNodeTypes.ANNOTATION_ENTRY -> listOf(child.getPsi() as JetAnnotationEntry) JetNodeTypes.ANNOTATION -> (child.getPsi() as JetAnnotation).getEntries() else -> emptyList<JetAnnotationEntry>() } } } private fun JetAnnotationsContainer.collectAnnotationEntriesFromPsi(): List<JetAnnotationEntry> { return getChildren().flatMap { child -> when (child) { is JetAnnotationEntry -> listOf(child) is JetAnnotation -> child.getEntries() else -> emptyList<JetAnnotationEntry>() } } } // -------- Recursive tree visiting -------------------------------------------------------------------------------------------------------- // Calls `block` on each descendant of T type // Note, that calls happen in order of DFS-exit, so deeper nodes are applied earlier public inline fun <reified T : JetElement> forEachDescendantOfTypeVisitor(noinline block: (T) -> Unit): JetVisitorVoid { return object : JetTreeVisitorVoid() { override fun visitJetElement(element: JetElement) { super.visitJetElement(element) if (element is T) { block(element) } } } } public inline fun <reified T : JetElement, R> flatMapDescendantsOfTypeVisitor(accumulator: MutableCollection<R>, noinline map: (T) -> Collection<R>): JetVisitorVoid { return forEachDescendantOfTypeVisitor<T> { accumulator.addAll(map(it)) } } // ----------- Other ----------------------------------------------------------------------------------------------------------------------- public fun JetClassOrObject.effectiveDeclarations(): List<JetDeclaration> { return when(this) { is JetClass -> getDeclarations() + getPrimaryConstructorParameters().filter { p -> p.hasValOrVar() } else -> getDeclarations() } } public fun JetDeclaration.isExtensionDeclaration(): Boolean { val callable: JetCallableDeclaration? = when (this) { is JetNamedFunction, is JetProperty -> this as JetCallableDeclaration is JetPropertyAccessor -> getNonStrictParentOfType<JetProperty>() else -> null } return callable?.getReceiverTypeReference() != null } public fun JetClassOrObject.isObjectLiteral(): Boolean = this is JetObjectDeclaration && isObjectLiteral() //TODO: strange method, and not only Kotlin specific (also Java) public fun PsiElement.parameterIndex(): Int { val parent = getParent() return when { this is JetParameter && parent is JetParameterList -> parent.getParameters().indexOf(this) this is PsiParameter && parent is PsiParameterList -> parent.getParameterIndex(this) else -> -1 } } public fun JetModifierListOwner.isPrivate(): Boolean = hasModifier(JetTokens.PRIVATE_KEYWORD) public fun JetSimpleNameExpression.isImportDirectiveExpression(): Boolean { val parent = getParent() if (parent == null) { return false } else { return parent is JetImportDirective || parent.getParent() is JetImportDirective } } public fun JetExpression.isFunctionLiteralOutsideParentheses(): Boolean { val parent = getParent() return when (parent) { is JetFunctionLiteralArgument -> true is JetLabeledExpression -> parent.isFunctionLiteralOutsideParentheses() else -> false } } public fun JetExpression.getAssignmentByLHS(): JetBinaryExpression? { val parent = getParent() as? JetBinaryExpression ?: return null return if (JetPsiUtil.isAssignment(parent) && parent.getLeft() == this) parent else null } public fun JetStringTemplateExpression.getContentRange(): TextRange { val start = getNode().getFirstChildNode().getTextLength() val lastChild = getNode().getLastChildNode() val length = getTextLength() return TextRange(start, if (lastChild.getElementType() == JetTokens.CLOSING_QUOTE) length - lastChild.getTextLength() else length) } public fun JetStringTemplateExpression.isSingleQuoted(): Boolean = getNode().getFirstChildNode().getTextLength() == 1 public fun JetNamedDeclaration.getValueParameters(): List<JetParameter> { return getValueParameterList()?.getParameters() ?: Collections.emptyList() } public fun JetNamedDeclaration.getValueParameterList(): JetParameterList? { return when (this) { is JetCallableDeclaration -> getValueParameterList() is JetClass -> getPrimaryConstructorParameterList() else -> null } } public fun JetFunctionLiteralArgument.getFunctionLiteralArgumentName(bindingContext: BindingContext): Name? { val callExpression = getParent() as JetCallExpression val resolvedCall = callExpression.getResolvedCall(bindingContext) return (resolvedCall?.getArgumentMapping(this) as? ArgumentMatch)?.valueParameter?.getName() }
1
null
1
1
e82adc9d90e5e0b65bf9cb2fd854b542ad1ff58e
15,772
kotlin
Apache License 2.0
app/shared/encryption/public/src/commonTest/kotlin/build/wallet/encrypt/XSealedDataTests.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.encrypt import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.equals.shouldBeEqual import okio.ByteString.Companion.encodeUtf8 class XSealedDataTests : FunSpec({ test("XSealedData round trip") { val original = XSealedData( header = XSealedData.Header(algorithm = "unreal"), ciphertext = "ciphertext".encodeUtf8(), nonce = XNonce("nonce".encodeUtf8()) ) original.toOpaqueCiphertext().value.shouldBeEqual( "<KEY>" ) val roundtrip = original.toOpaqueCiphertext().toXSealedData() roundtrip.shouldBeEqual(original) } })
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
617
bitkey
MIT License
shared/src/commonMain/kotlin/data/repositories/MessagesRepository.kt
gleb-skobinsky
634,563,581
false
{"Kotlin": 136374, "Swift": 580, "HTML": 309, "Shell": 228, "Ruby": 101}
package data.repositories import data.InitialMessages import data.Resource import data.User import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.serialization.decodeFromString import kotlinx.serialization.json.Json import transport.LocalRoute import transport.chirrioClient object MessagesRepository { suspend fun getMessagesForRoom(roomId: String, currentUser: User): Resource<InitialMessages> { val response = chirrioClient.get("${LocalRoute.currentUrl}/messages/$roomId/") { contentType(ContentType.Application.Json) headers.append("Authorization", currentUser.getBearer()) } return try { val messages = Json.decodeFromString<InitialMessages>(response.bodyAsText()) Resource.Data(messages) } catch (e: Exception) { println("Error") println(e.message) Resource.Error("Error fetching messages", response.status) } } }
0
Kotlin
0
8
116bf248513d04f3a67bf5443a0451faea487b7d
1,002
compose-connect
Apache License 2.0
features/messages/impl/src/main/kotlin/io/element/android/features/messages/impl/timeline/model/event/TimelineItemEventContentProvider.kt
vector-im
546,522,002
false
null
/* * Copyright (c) 2023 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.features.messages.impl.timeline.model.event import androidx.compose.ui.tooling.preview.PreviewParameterProvider import io.element.android.libraries.matrix.api.timeline.item.event.UnableToDecryptContent import org.jsoup.Jsoup class TimelineItemEventContentProvider : PreviewParameterProvider<TimelineItemEventContent> { override val values = sequenceOf( aTimelineItemEmoteContent(), aTimelineItemEncryptedContent(), aTimelineItemImageContent(), aTimelineItemVideoContent(), aTimelineItemFileContent(), aTimelineItemFileContent("A bigger file name which doesn't fit.pdf"), aTimelineItemLocationContent(), aTimelineItemLocationContent("Location description"), aTimelineItemNoticeContent(), aTimelineItemRedactedContent(), aTimelineItemTextContent(), aTimelineItemUnknownContent(), aTimelineItemTextContent().copy(isEdited = true), ) } class TimelineItemTextBasedContentProvider : PreviewParameterProvider<TimelineItemTextBasedContent> { override val values = sequenceOf( aTimelineItemEmoteContent(), aTimelineItemEmoteContent().copy(htmlDocument = Jsoup.parse("Emote Document")), aTimelineItemNoticeContent(), aTimelineItemNoticeContent().copy(htmlDocument = Jsoup.parse("Notice Document")), aTimelineItemTextContent(), aTimelineItemTextContent().copy(htmlDocument = Jsoup.parse("Text Document")), ) } fun aTimelineItemEmoteContent() = TimelineItemEmoteContent( body = "Emote", htmlDocument = null, isEdited = false, ) fun aTimelineItemEncryptedContent() = TimelineItemEncryptedContent( data = UnableToDecryptContent.Data.Unknown ) fun aTimelineItemNoticeContent() = TimelineItemNoticeContent( body = "Notice", htmlDocument = null, isEdited = false, ) fun aTimelineItemRedactedContent() = TimelineItemRedactedContent fun aTimelineItemTextContent() = TimelineItemTextContent( body = "Text", htmlDocument = null, isEdited = false, ) fun aTimelineItemUnknownContent() = TimelineItemUnknownContent fun aTimelineItemStateEventContent() = TimelineItemStateEventContent( body = "A state event", )
71
Kotlin
9
80
7918435c5470e27bf4f78109401a9f9902942700
2,839
element-x-android
Apache License 2.0
web/src/main/kotlin/world/phantasmal/web/questEditor/asm/monaco/EditorHistory.kt
DaanVandenBosch
189,066,992
false
null
package world.phantasmal.web.questEditor.asm.monaco import world.phantasmal.web.externals.monacoEditor.* import world.phantasmal.webui.DisposableContainer import kotlin.math.abs class EditorHistory(private val editor: IStandaloneCodeEditor) : DisposableContainer() { private val history = mutableListOf<IPosition>() private var historyIndex = -1 private var captureHistory = true init { addDisposables( editor.onDidChangeCursorPosition(::onDidChangeCursorPosition).toDisposable(), editor.addAction(object : IActionDescriptor { override var id = "phantasmal.action.back" override var label = "Go Back" override var keybindings = arrayOf(KeyMod.Alt or KeyCode.LeftArrow) override fun run(editor: ICodeEditor, vararg args: dynamic) { goBack() } }).toDisposable(), editor.addAction(object : IActionDescriptor { override var id = "phantasmal.action.forward" override var label = "Go Forward" override var keybindings = arrayOf(KeyMod.Alt or KeyCode.RightArrow) override fun run(editor: ICodeEditor, vararg args: dynamic) { goForward() } }).toDisposable(), editor.onMouseUp(::onMouseUp).toDisposable(), editor.onDidChangeModel(::reset).toDisposable(), ) } private fun reset() { history.clear() historyIndex = -1 } private fun onDidChangeCursorPosition(e: ICursorPositionChangedEvent) { if (!captureHistory) return while (history.lastIndex > historyIndex) { history.removeLast() } if ( e.source === "api" || historyIndex == -1 || abs(e.position.lineNumber - history[historyIndex].lineNumber) >= 10 ) { history.add(e.position.unsafeCast<IPosition>()) historyIndex++ } else { history[historyIndex] = e.position.unsafeCast<IPosition>() } } private fun goBack() { if (historyIndex > 0) { setPosition(history[--historyIndex]) } } private fun goForward() { if (historyIndex < history.lastIndex) { setPosition(history[++historyIndex]) } } private fun setPosition(position: IPosition) { captureHistory = false editor.setPosition(position) editor.revealPositionInCenterIfOutsideViewport(position, ScrollType.Immediate) captureHistory = true } private fun onMouseUp(e: IEditorMouseEvent) { val button = e.event.browserEvent.button.toInt() val buttons = e.event.browserEvent.buttons.toInt() if (button == 3) { if (buttons == 0) { e.event.preventDefault() goBack() } editor.focus() } else if (button == 4) { if (buttons == 0) { e.event.preventDefault() goForward() } editor.focus() } } }
1
Kotlin
5
20
423c3e252b2be6de63a03108915861fced90aaa6
3,177
phantasmal-world
MIT License
misk-aws-dynamodb/src/test/kotlin/misk/aws/dynamodb/testing/DyCharacter.kt
cashapp
113,107,217
false
{"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58}
package misk.aws.dynamodb.testing import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBHashKey import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBTable @DynamoDBTable(tableName = "characters") class DyCharacter { @DynamoDBHashKey(attributeName = "movie_name") var movie_name: String = "" @DynamoDBRangeKey(attributeName = "character_name") var character_name: String = "" }
169
Kotlin
169
400
13dcba0c4e69cc2856021270c99857e7e91af27d
476
misk
Apache License 2.0
shared/src/commonMain/kotlin/network/data/PokemonFavorites.kt
ThomasBerthier
753,705,683
false
{"Kotlin": 28769, "Swift": 580, "Shell": 228}
package network.data object FavoritesManager { private val _favoritePokemons = mutableSetOf<String>() val favoritePokemons: Set<String> get() = _favoritePokemons fun addToFavorites(pokemon: String) { println(_favoritePokemons.toString()) _favoritePokemons.add(pokemon) println(_favoritePokemons.toString()) } fun removeFromFavorites(pokemon: String) { _favoritePokemons.remove(pokemon) } }
0
Kotlin
0
0
514e92c0c3068eed03229e73e716c9ea5af270b0
457
Kotlin
Apache License 2.0
sample/src/test/java/com/sebaslogen/resacaapp/ComposeActivityRecreationTests.kt
sebaslogen
431,489,181
false
null
package com.sebaslogen.resacaapp import androidx.compose.ui.test.assert import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.hasTextExactly import androidx.compose.ui.test.junit4.createComposeRule import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import com.sebaslogen.resacaapp.ui.main.ComposeActivity import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class ComposeActivityRecreationTests : ComposeTestUtils { @get:Rule override val composeTestRule = createComposeRule() @Test fun `when the activity is recreated, then the scoped objects are the same`() { ActivityScenario.launch(ComposeActivity::class.java).use { scenario -> scenario.onActivity { activity: ComposeActivity -> // Given the Activity shows a screen with scoped objects printComposeUiTreeToLog() // Find the scoped text fields and grab their texts val initialFakeScopedRepoText = retrieveTextFromNodeWithTestTag("FakeRepo Scoped") val initialFakeScopedViewModelText = retrieveTextFromNodeWithTestTag("FakeScopedViewModel Scoped") // When we recreate the activity activity.recreate() printComposeUiTreeToLog() // Then the scoped objects on the first screen are still the same onNodeWithTestTag("FakeRepo Scoped").assertIsDisplayed().assertTextEquals(initialFakeScopedRepoText) onNodeWithTestTag("FakeScopedViewModel Scoped").assertIsDisplayed().assertTextEquals(initialFakeScopedViewModelText) } } } @Test fun `when the activity is recreated, then the NOT scoped object changes`() { ActivityScenario.launch(ComposeActivity::class.java).use { scenario -> scenario.onActivity { activity: ComposeActivity -> // Given the Activity shows a screen with scoped objects printComposeUiTreeToLog() // Find the NOT scoped text field and grab its text val initialFakeRepoText = retrieveTextFromNodeWithTestTag("FakeRepo Not scoped") // When we recreate the activity activity.recreate() printComposeUiTreeToLog() // Then the text of the NOT scoped object is different from the original one because it's a new object onNodeWithTestTag("FakeRepo Not scoped").assertIsDisplayed().assert(hasTextExactly(initialFakeRepoText).not()) } } } }
1
null
2
56
8dae73cc5c6f3ca873ce4262d39c3df558c618de
2,715
resaca
MIT License
app/src/main/java/com/example/moereng/utils/text/ZHJAMixTextUtils.kt
weirdseed
580,052,539
false
{"C++": 4612946, "C": 478914, "Kotlin": 126957, "CMake": 2028}
package com.example.moereng.utils.text import android.content.res.AssetManager class ZHJAENMixTextUtils(override val symbols: List<String>, override val cleanerName: String, override val assetManager: AssetManager) : BaseTextUtils(symbols, cleanerName, assetManager) { private val cleaner = ZHJAENMixCleaners(assetManager) override fun wordsToLabels(text: String): IntArray { val labels = ArrayList<Int>() labels.add(0) // symbol to id val symbolToIndex = HashMap<String, Int>() symbols.forEachIndexed { index, s -> symbolToIndex[s] = index } // clean text var cleanedText = "" when(cleanerName){ "zh_ja_en_mixture_cleaners"-> { cleanedText = cleaner.zh_ja_en_mixture_cleaners(text) } } if (cleanedText.isEmpty()){ throw RuntimeException("转换失败,请检查输入!") } // symbol to label for (symbol in cleanedText) { if (!symbols.contains(symbol.toString())) { continue } val label = symbolToIndex[symbol.toString()] if (label != null) { labels.add(label) labels.add(0) } } return labels.toIntArray() } }
12
C++
49
296
d109c5117653738ac959197a40ebf1ce0d05dcb3
1,365
Vits-Android-ncnn
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/cloudfront/CfnCachePolicyCachePolicyConfigPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.cloudfront import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.Number import kotlin.String import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.cloudfront.CfnCachePolicy /** * A cache policy configuration. * * This configuration determines the following: * * The values that CloudFront includes in the cache key. These values can include HTTP headers, * cookies, and URL query strings. CloudFront uses the cache key to find an object in its cache * that it can return to the viewer. * * The default, minimum, and maximum time to live (TTL) values that you want objects to stay in * the CloudFront cache. * * The headers, cookies, and query strings that are included in the cache key are also included in * requests that CloudFront sends to the origin. CloudFront sends a request when it can't find a * valid object in its cache that matches the request's cache key. If you want to send values to the * origin but *not* include them in the cache key, use `OriginRequestPolicy` . * * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.cloudfront.*; * CachePolicyConfigProperty cachePolicyConfigProperty = CachePolicyConfigProperty.builder() * .defaultTtl(123) * .maxTtl(123) * .minTtl(123) * .name("name") * .parametersInCacheKeyAndForwardedToOrigin(ParametersInCacheKeyAndForwardedToOriginProperty.builder() * .cookiesConfig(CookiesConfigProperty.builder() * .cookieBehavior("cookieBehavior") * // the properties below are optional * .cookies(List.of("cookies")) * .build()) * .enableAcceptEncodingGzip(false) * .headersConfig(HeadersConfigProperty.builder() * .headerBehavior("headerBehavior") * // the properties below are optional * .headers(List.of("headers")) * .build()) * .queryStringsConfig(QueryStringsConfigProperty.builder() * .queryStringBehavior("queryStringBehavior") * // the properties below are optional * .queryStrings(List.of("queryStrings")) * .build()) * // the properties below are optional * .enableAcceptEncodingBrotli(false) * .build()) * // the properties below are optional * .comment("comment") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-cachepolicy-cachepolicyconfig.html) */ @CdkDslMarker public class CfnCachePolicyCachePolicyConfigPropertyDsl { private val cdkBuilder: CfnCachePolicy.CachePolicyConfigProperty.Builder = CfnCachePolicy.CachePolicyConfigProperty.builder() /** * @param comment A comment to describe the cache policy. The comment cannot be longer than 128 * characters. */ public fun comment(comment: String) { cdkBuilder.comment(comment) } /** * @param defaultTtl The default amount of time, in seconds, that you want objects to stay in * the CloudFront cache before CloudFront sends another request to the origin to see if the * object has been updated. CloudFront uses this value as the object's time to live (TTL) only * when the origin does *not* send `Cache-Control` or `Expires` headers with the object. For * more information, see * [Managing How Long Content Stays in an Edge Cache (Expiration)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) * in the *Amazon CloudFront Developer Guide* . * * The default value for this field is 86400 seconds (one day). If the value of `MinTTL` is more * than 86400 seconds, then the default value for this field is the same as the value of * `MinTTL` . */ public fun defaultTtl(defaultTtl: Number) { cdkBuilder.defaultTtl(defaultTtl) } /** * @param maxTtl The maximum amount of time, in seconds, that objects stay in the CloudFront * cache before CloudFront sends another request to the origin to see if the object has been * updated. CloudFront uses this value only when the origin sends `Cache-Control` or `Expires` * headers with the object. For more information, see * [Managing How Long Content Stays in an Edge Cache (Expiration)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) * in the *Amazon CloudFront Developer Guide* . * * The default value for this field is 31536000 seconds (one year). If the value of `MinTTL` or * `DefaultTTL` is more than 31536000 seconds, then the default value for this field is the same * as the value of `DefaultTTL` . */ public fun maxTtl(maxTtl: Number) { cdkBuilder.maxTtl(maxTtl) } /** * @param minTtl The minimum amount of time, in seconds, that you want objects to stay in the * CloudFront cache before CloudFront sends another request to the origin to see if the object * has been updated. For more information, see * [Managing How Long Content Stays in an Edge Cache (Expiration)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Expiration.html) * in the *Amazon CloudFront Developer Guide* . */ public fun minTtl(minTtl: Number) { cdkBuilder.minTtl(minTtl) } /** @param name A unique name to identify the cache policy. */ public fun name(name: String) { cdkBuilder.name(name) } /** * @param parametersInCacheKeyAndForwardedToOrigin The HTTP headers, cookies, and URL query * strings to include in the cache key. The values included in the cache key are also included * in requests that CloudFront sends to the origin. */ public fun parametersInCacheKeyAndForwardedToOrigin( parametersInCacheKeyAndForwardedToOrigin: IResolvable ) { cdkBuilder.parametersInCacheKeyAndForwardedToOrigin( parametersInCacheKeyAndForwardedToOrigin ) } /** * @param parametersInCacheKeyAndForwardedToOrigin The HTTP headers, cookies, and URL query * strings to include in the cache key. The values included in the cache key are also included * in requests that CloudFront sends to the origin. */ public fun parametersInCacheKeyAndForwardedToOrigin( parametersInCacheKeyAndForwardedToOrigin: CfnCachePolicy.ParametersInCacheKeyAndForwardedToOriginProperty ) { cdkBuilder.parametersInCacheKeyAndForwardedToOrigin( parametersInCacheKeyAndForwardedToOrigin ) } public fun build(): CfnCachePolicy.CachePolicyConfigProperty = cdkBuilder.build() }
4
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
6,903
awscdk-dsl-kotlin
Apache License 2.0
app-rater/src/main/java/com/simplaapliko/apprater/AppRater.kt
simplaapliko
64,045,685
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "XML": 16, "Java": 2, "Kotlin": 2}
/* * Copyright (C) 2015 Oleg Kan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.simplaapliko.apprater import android.app.Activity import android.content.Context import android.content.DialogInterface import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.widget.Toast import androidx.appcompat.app.AlertDialog import java.util.Date @Suppress("MemberVisibilityCanBePrivate") object AppRater { private const val DAY = 24 * 60 * 60 * 1000 /** * Check if 'rate app' dialog needs to be displayed, * based on the first launch date, launch count and do not show again * shared preferences. * * @param activity Activity * @param onPositiveButtonListener Positive button click listener * @param onNegativeButtonListener Negative button click listener * @param onNeutralButtonListener Neutral button click listener */ @JvmStatic @JvmOverloads fun appLaunched( activity: Activity, onPositiveButtonListener: DialogInterface.OnClickListener? = null, onNegativeButtonListener: DialogInterface.OnClickListener? = null, onNeutralButtonListener: DialogInterface.OnClickListener? = null ) { val preferences = PreferencesHelper(activity) if (preferences.isDoNoShowAgain) { return } increment(activity) if (isTimeToRate(activity)) { showDialog(activity, onPositiveButtonListener, onNegativeButtonListener, onNeutralButtonListener) } } @JvmStatic @JvmOverloads fun showDialog( activity: Activity, onPositiveButtonListener: DialogInterface.OnClickListener? = null, onNegativeButtonListener: DialogInterface.OnClickListener? = null, onNeutralButtonListener: DialogInterface.OnClickListener? = null ) { val builder = AlertDialog.Builder(activity) .setCancelable(true) .setTitle(R.string.rate_app_title) .setMessage(R.string.rate_app_message) onPositiveButtonListener?.let { listener -> builder.setPositiveButton( R.string.rate_app_positive_button ) { dialog: DialogInterface?, which: Int -> rateApp(activity) listener.onClick(dialog, which) } } onNegativeButtonListener?.let { listener -> builder.setNegativeButton( R.string.rate_app_negative_button ) { dialog: DialogInterface?, which: Int -> remindLater(activity) listener.onClick(dialog, which) } } onNeutralButtonListener?.let { listener -> builder.setNeutralButton( R.string.rate_app_neutral_button ) { dialog: DialogInterface?, which: Int -> cancelReminders(activity) listener.onClick(dialog, which) } } builder.create() .show() } /** * Increment launch count and set first launch date * @param context Context */ fun increment(context: Context) { val preferences = PreferencesHelper(context) // Increment the launch counter val launchCount = preferences.launchCount + 1 preferences.setLaunchCount(launchCount) // Get date of the first launch val firstLaunchDate = preferences.firstLaunchDate if (firstLaunchDate == 0L) { preferences.setFirstLaunchDate(System.currentTimeMillis()) } } @JvmStatic fun getFirstLaunchDate(context: Context): Date { val preferences = PreferencesHelper(context) val firstLaunchDate = preferences.firstLaunchDate return Date(firstLaunchDate) } @JvmStatic fun getLaunchCount(context: Context): Int { val preferences = PreferencesHelper(context) return preferences.launchCount } @JvmStatic fun isDoNotShowAgain(context: Context): Boolean { val preferences = PreferencesHelper(context) return preferences.isDoNoShowAgain } @JvmStatic fun isTimeToRate(context: Context): Boolean { val resources = context.resources val dayUntilPrompt = resources.getInteger(R.integer.ar_app_rater_days_until_prompt) val launchesUntilPrompt = resources.getInteger(R.integer.ar_app_rater_launches_until_prompt) val preferences = PreferencesHelper(context) val launchCount = preferences.launchCount val firstLaunchDate = preferences.firstLaunchDate return !preferences.isDoNoShowAgain && launchCount >= launchesUntilPrompt && System.currentTimeMillis() >= firstLaunchDate + dayUntilPrompt * DAY } /** * Open Play Store for the related application. */ fun rateApp(context: Context) { PreferencesHelper(context) .setDoNoShowAgain(true) // create Play Store intent var rate = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + context.packageName)) if (!isIntentCallable(context, rate)) { // if Play Store doesn't exist show in browser rate = Intent( Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + context.packageName) ) } if (!isIntentCallable(context, rate)) { // if browser app doesn't exist, show toast and quit Toast.makeText(context, context.getString(R.string.unable_to_find_google_play), Toast.LENGTH_LONG).show() return } if (context is Activity) { context.startActivity(rate) } else { val intent = Intent.createChooser(rate, null) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(intent) } } /** * Reset launch counter. */ fun remindLater(context: Context) { PreferencesHelper(context) .setLaunchCount(0) .setFirstLaunchDate(System.currentTimeMillis()) } /** * Cancel reminders. */ fun cancelReminders(context: Context) { PreferencesHelper(context) .setDoNoShowAgain(true) } /** * Check if this is a first launch */ fun isFirstLaunch(context: Context): Boolean { return PreferencesHelper(context) .firstLaunchDate == 0L } private fun isIntentCallable(context: Context, intent: Intent): Boolean { val list = context.packageManager .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY) return list.size > 0 } }
1
null
1
1
32383a662d4f66aea6030ff3bdc386e440cc381f
7,254
app-rater
Apache License 2.0
app/src/main/java/de/p72b/burstpooltracker/main/list/ListFragment.kt
P72B
178,820,066
false
null
package de.p72b.burstpooltracker.main.list import androidx.fragment.app.Fragment import android.os.Bundle import androidx.preference.PreferenceManager import android.view.ViewGroup import android.view.LayoutInflater import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import de.p72b.burstpooltracker.App import de.p72b.burstpooltracker.R import de.p72b.burstpooltracker.main.MinerAdapter import de.p72b.burstpooltracker.main.BaseMinerViewModel import de.p72b.burstpooltracker.settings.ADDRESS import de.p72b.burstpooltracker.util.Utils import kotlinx.android.synthetic.main.fragment_list.* import org.koin.android.ext.android.inject class ListFragment: Fragment() { private lateinit var adapter: MinerAdapter private val minerViewModel: BaseMinerViewModel by inject() override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_list, null) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recyclerView: RecyclerView = view.findViewById(R.id.vRecyclerView) adapter = MinerAdapter(App.sInstance.applicationContext) recyclerView.adapter = adapter recyclerView.layoutManager = LinearLayoutManager(context) } override fun onResume() { super.onResume() minerViewModel.getMiners(true).observe(this, { miners -> adapter.setMiners(Utils.filter(miners)) }) } }
0
Kotlin
1
1
f7f4239e503bfbe445b069790416c163d57c2d5c
1,621
BurstMonitor
MIT License
app/src/main/java/com/samuelokello/kazihub/presentation/business/home/components/BusinessHomeScreenContent.kt
OkelloSam21
749,782,789
false
{"Kotlin": 304286}
package com.samuelokello.kazihub.presentation.business.home.components import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add import androidx.compose.material.icons.filled.ArrowDropDown import androidx.compose.material.icons.filled.ArrowDropUp import androidx.compose.material.icons.filled.ShoppingBag import androidx.compose.material.icons.filled.Work import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.FloatingActionButton import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.rememberModalBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.samuelokello.kazihub.R import com.samuelokello.kazihub.domain.model.job.category.CategoryResponse import com.samuelokello.kazihub.domain.model.job.data import com.samuelokello.kazihub.presentation.business.home.BusinessHomeUiEvents import com.samuelokello.kazihub.presentation.common.components.CustomButton import com.samuelokello.kazihub.presentation.common.components.LocationAutocompleteTextField import com.samuelokello.kazihub.presentation.common.components.NoJobsMessage import com.samuelokello.kazihub.presentation.shared.components.EditTextField import com.samuelokello.kazihub.ui.theme.primaryLight @OptIn(ExperimentalMaterial3Api::class) @Composable fun BusinessHomeScreenContent( jobs: List<data> = emptyList(), createJobState: CreateJobUiState, showSheet: Boolean = false, onSheetDismissRequest: () -> Unit, onBusinessUiEvent: (BusinessHomeUiEvents) -> Unit, onCreateJobUiEvent: (CreateJobUiEvent) -> Unit, categories: List<CategoryResponse> = emptyList(), selectedCategory: CategoryResponse, ) { // Create a SheetState object val sheetState = rememberModalBottomSheetState() // Update the SheetState object based on the showSheet value LaunchedEffect(showSheet) { if (showSheet) { sheetState.expand() } else { sheetState.hide() } } if (showSheet) { CreateJobUi( createJobState = createJobState, onCreateJobUiEvent = onCreateJobUiEvent, categories = categories, selectedCategory = selectedCategory, ) } Scaffold( floatingActionButton = { FloatingActionButton( modifier = Modifier .padding(end = 16.dp, bottom = 92.dp) .size(64.dp), onClick = { onBusinessUiEvent(BusinessHomeUiEvents.OnFABClick) }, contentColor = Color.White, containerColor = primaryLight, ) { Icon(Icons.Default.Add, contentDescription = "Create data") } }, ) { paddingValues -> Column( modifier = Modifier .padding(paddingValues) .padding(horizontal = 20.dp) .fillMaxWidth(), ) { Spacer(modifier = Modifier.height(16.dp)) Column { Text(text = "Hello 👋 !", style = MaterialTheme.typography.titleMedium) } Spacer(modifier = Modifier.height(16.dp)) Column( modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp), ) { Row { StatsCard( statIcon = { Icon(Icons.Default.ShoppingBag, contentDescription = null) }, title = "Total Expenditure", value = "Ksh 0", ) Spacer(modifier = Modifier.size(32.dp)) StatsCard( statIcon = { Icon(Icons.Default.Work, contentDescription = null) }, title = "Jobs Posted", value = " 0", ) } } Spacer(modifier = Modifier.height(16.dp)) Column { Text( text = "Expenditure Over Time", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(bottom = 8.dp), ) Spacer(Modifier.height(16.dp)) LineGraph(jobs) } Spacer(modifier = Modifier.height(16.dp)) Column { Text( text = "Recent Activities", style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding(bottom = 8.dp), ) } Spacer(modifier = Modifier.height(8.dp)) if (jobs.isEmpty()) { NoJobsMessage(R.string.click_the_button_to_create_your_first_job) } else { LazyColumn { items(jobs) { job -> JobListItem( data = job, onJobClick = { job.id?.let { jobId -> onBusinessUiEvent(BusinessHomeUiEvents.OnJobClick(jobId)) } }, ) } } } } } } @Composable fun CreateJobUi( createJobState: CreateJobUiState, onCreateJobUiEvent: (CreateJobUiEvent) -> Unit, categories: List<CategoryResponse> = emptyList(), selectedCategory: CategoryResponse, ) { Column( modifier = Modifier .fillMaxSize() .padding(16.dp) .padding(bottom = 48.dp), ) { Text(text = "Create Job", style = MaterialTheme.typography.titleMedium) Spacer(modifier = Modifier.height(8.dp)) EditTextField( value = createJobState.title, onValueChange = { onCreateJobUiEvent(CreateJobUiEvent.OnTitleChange(it)) }, label = "Title", singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next, ), modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.height(8.dp)) EditTextField( value = createJobState.description, onValueChange = { onCreateJobUiEvent(CreateJobUiEvent.OnDescriptionChange(it)) }, label = "Description", singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next, ), modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.height(8.dp)) EditTextField( value = createJobState.budget.toString(), onValueChange = { onCreateJobUiEvent(CreateJobUiEvent.OnBudgetChange(it.toInt())) }, label = "Budget", singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Number, imeAction = ImeAction.Next, ), modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.height(8.dp)) LocationAutocompleteTextField( value = createJobState.location, onValueChange = { onCreateJobUiEvent(CreateJobUiEvent.OnLocationChange(it)) }, suggestions = createJobState.locationSuggestion, onSuggestionSelected = { onCreateJobUiEvent(CreateJobUiEvent.OnSuggestionSelected(it)) }, placeholder = "Location", modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.height(8.dp)) EditTextField( value = createJobState.qualifications.joinToString(", "), onValueChange = { onCreateJobUiEvent(CreateJobUiEvent.OnQualificationsChange(it)) }, label = "Qualifications", singleLine = true, keyboardOptions = KeyboardOptions( imeAction = ImeAction.Done, ), modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.height(16.dp)) CategoryDropDown( categories = categories, selectedCategory = selectedCategory, onCreateJobUiEvent = onCreateJobUiEvent, ) Spacer(modifier = Modifier.height(16.dp)) CustomButton( onClick = { // Handle data creation logic onCreateJobUiEvent( CreateJobUiEvent.OnCreateJobClick( title = createJobState.title, description = createJobState.description, budget = createJobState.budget, category = createJobState.category, location = createJobState.location, qualifications = createJobState.qualifications.toString(), ), ) }, isEnabled = createJobState.title.isNotBlank() && createJobState.description.isNotBlank() && createJobState.budget.toString().isNotBlank() && createJobState.location.isNotBlank() && createJobState.qualifications.toString().isNotBlank(), text = "Create data", ) } } @Composable fun CategoryDropDown( categories: List<CategoryResponse?>, selectedCategory: CategoryResponse?, onCreateJobUiEvent: (CreateJobUiEvent) -> Unit, ) { var expanded by remember { mutableStateOf(false) } val icon = if (expanded) Icons.Default.ArrowDropUp else Icons.Default.ArrowDropDown Box( modifier = Modifier .fillMaxWidth() .padding(8.dp), ) { OutlinedTextField( value = selectedCategory?.name ?: "", onValueChange = {}, label = { Text("Category") }, singleLine = true, keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Text, imeAction = ImeAction.Next, ), modifier = Modifier.fillMaxWidth(), trailingIcon = { Icon( imageVector = icon, contentDescription = null, modifier = Modifier.clickable { expanded = !expanded }, ) }, ) DropdownMenu( expanded = expanded, onDismissRequest = { expanded = false }, modifier = Modifier.fillMaxWidth(), ) { categories.forEach { category -> DropdownMenuItem( onClick = { if (category != null) { onCreateJobUiEvent( CreateJobUiEvent.OnCategoryChange( category.name ?: "" ) ) } expanded = false }, text = { if (category != null) { category.name?.let { Text(text = it) } } }, ) } } } }
0
Kotlin
0
0
e2c0776f721e24e2667a98066d79cf6554a5f040
12,919
KaziHub
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/HouseReturn.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.HouseReturn: ImageVector get() { if (_houseReturn != null) { return _houseReturn!! } _houseReturn = Builder(name = "HouseReturn", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(14.0f, 2.5f) curveToRelative(0.0f, -1.381f, 1.119f, -2.5f, 2.5f, -2.5f) reflectiveCurveToRelative(2.5f, 1.119f, 2.5f, 2.5f) reflectiveCurveToRelative(-1.119f, 2.5f, -2.5f, 2.5f) reflectiveCurveToRelative(-2.5f, -1.119f, -2.5f, -2.5f) close() moveTo(8.0f, 15.0f) horizontalLineToRelative(-4.0f) curveToRelative(-1.103f, 0.0f, -2.0f, -0.897f, -2.0f, -2.0f) verticalLineToRelative(-5.338f) curveToRelative(0.0f, -0.929f, 0.419f, -1.79f, 1.151f, -2.362f) lineToRelative(3.324f, -2.601f) curveToRelative(1.062f, -0.832f, 2.501f, -0.932f, 3.607f, -0.296f) lineToRelative(0.498f, 0.337f) curveToRelative(0.458f, 0.31f, 1.08f, 0.19f, 1.389f, -0.268f) curveToRelative(0.31f, -0.458f, 0.189f, -1.08f, -0.268f, -1.389f) lineToRelative(-0.558f, -0.375f) curveToRelative(-1.877f, -1.084f, -4.193f, -0.921f, -5.901f, 0.415f) lineTo(1.918f, 3.724f) curveToRelative(-1.219f, 0.955f, -1.918f, 2.39f, -1.918f, 3.938f) verticalLineToRelative(5.338f) curveToRelative(0.0f, 2.206f, 1.794f, 4.0f, 4.0f, 4.0f) horizontalLineToRelative(4.0f) curveToRelative(0.552f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f) reflectiveCurveToRelative(-0.448f, -1.0f, -1.0f, -1.0f) close() moveTo(5.0f, 9.0f) curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f) verticalLineToRelative(1.0f) curveToRelative(0.0f, 0.552f, 0.448f, 1.0f, 1.0f, 1.0f) horizontalLineToRelative(1.0f) curveToRelative(0.552f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f) horizontalLineToRelative(-1.0f) close() moveTo(24.0f, 11.556f) verticalLineToRelative(2.444f) curveToRelative(0.0f, 0.552f, -0.447f, 1.0f, -1.0f, 1.0f) reflectiveCurveToRelative(-1.0f, -0.448f, -1.0f, -1.0f) verticalLineToRelative(-2.444f) curveToRelative(0.0f, -0.331f, -0.163f, -0.639f, -0.436f, -0.825f) lineToRelative(-1.564f, -1.069f) verticalLineToRelative(3.797f) curveToRelative(0.0f, 0.978f, -0.479f, 1.897f, -1.28f, 2.458f) lineToRelative(-4.271f, 2.824f) curveToRelative(-0.281f, 0.186f, -0.449f, 0.498f, -0.449f, 0.834f) verticalLineToRelative(3.425f) curveToRelative(0.0f, 0.552f, -0.447f, 1.0f, -1.0f, 1.0f) reflectiveCurveToRelative(-1.0f, -0.448f, -1.0f, -1.0f) verticalLineToRelative(-3.425f) curveToRelative(0.0f, -1.01f, 0.503f, -1.945f, 1.346f, -2.502f) lineToRelative(0.654f, -0.433f) verticalLineToRelative(-3.867f) lineToRelative(-2.399f, 1.565f) curveToRelative(-0.463f, 0.302f, -1.083f, 0.171f, -1.384f, -0.292f) curveToRelative(-0.301f, -0.463f, -0.171f, -1.083f, 0.292f, -1.384f) lineToRelative(2.437f, -1.589f) curveToRelative(0.204f, -0.133f, 0.352f, -0.334f, 0.417f, -0.568f) curveToRelative(0.0f, 0.0f, 0.693f, -2.472f, 0.709f, -2.512f) curveToRelative(0.406f, -1.127f, 1.625f, -1.976f, 2.833f, -1.976f) curveToRelative(1.444f, 0.0f, 2.247f, 0.574f, 2.548f, 0.848f) lineToRelative(3.24f, 2.214f) curveToRelative(0.818f, 0.559f, 1.308f, 1.485f, 1.308f, 2.477f) close() moveTo(14.009f, 16.634f) reflectiveCurveToRelative(0.0f, -0.001f, 0.0f, 0.0f) horizontalLineToRelative(0.0f) close() moveTo(18.0f, 8.264f) curveToRelative(-0.154f, -0.094f, -0.496f, -0.248f, -1.096f, -0.248f) curveToRelative(-0.33f, 0.0f, -0.746f, 0.259f, -0.904f, 0.542f) verticalLineToRelative(6.759f) lineToRelative(1.595f, -1.055f) curveToRelative(0.246f, -0.172f, 0.405f, -0.479f, 0.405f, -0.805f) verticalLineToRelative(-5.194f) close() moveTo(19.784f, 18.62f) curveToRelative(-0.209f, -0.511f, -0.792f, -0.755f, -1.305f, -0.546f) curveToRelative(-0.511f, 0.209f, -0.755f, 0.794f, -0.545f, 1.305f) lineToRelative(1.641f, 4.0f) curveToRelative(0.158f, 0.387f, 0.531f, 0.621f, 0.925f, 0.621f) curveToRelative(0.127f, 0.0f, 0.255f, -0.024f, 0.38f, -0.075f) curveToRelative(0.511f, -0.209f, 0.755f, -0.794f, 0.545f, -1.305f) lineToRelative(-1.641f, -4.0f) close() } } .build() return _houseReturn!! } private var _houseReturn: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
6,368
icons
MIT License
spigot/src/main/java/net/isariel/gaia/spigot/greeting/GreetingManagerImpl.kt
Isariel
125,191,777
false
null
package net.isariel.gaia.spigot.greeting import net.isariel.lycan.api.service.tablist.TablistService import org.bukkit.entity.Player import javax.inject.Inject /** * @author <NAME> <<EMAIL>> */ class GreetingManagerImpl @Inject constructor(private val tablistService: TablistService) : GreetingManager { override fun greetPlayer(player: Player) { tablistService.sendHeaderFooter(player, "\nWillkommen auf Isariel\n", "") } }
1
Kotlin
0
0
16fed6d331d50379439b11eb5ce6a4f75290272e
447
gaia
MIT License
modern-treasury-java-core/src/main/kotlin/com/moderntreasury/api/services/async/LedgerableEventServiceAsync.kt
Modern-Treasury
665,761,562
false
null
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.moderntreasury.api.services.async import com.moderntreasury.api.core.RequestOptions import com.moderntreasury.api.models.LedgerableEvent import com.moderntreasury.api.models.LedgerableEventCreateParams import com.moderntreasury.api.models.LedgerableEventRetrieveParams import java.util.concurrent.CompletableFuture interface LedgerableEventServiceAsync { /** Create a ledgerable event. */ @JvmOverloads fun create( params: LedgerableEventCreateParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<LedgerableEvent> /** Get details on a single ledgerable event. */ @JvmOverloads fun retrieve( params: LedgerableEventRetrieveParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<LedgerableEvent> }
1
null
1
1
1c14c652a250e33f8c86d5404906f6fcc833a0b6
983
modern-treasury-java
MIT License
js/js.translator/testData/incremental/invalidation/moveExternalDeclarationsBetweenFiles/lib1/JsModuleA.1.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}
@file:JsModule("../js-module-a.mjs")
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
37
kotlin
Apache License 2.0
app/src/main/java/com/example/sodv3203_carrentalapp/ui/PageSummary.kt
danielkakiuthi
769,632,609
false
{"Kotlin": 39406}
package com.example.sodv3203_carrentalapp.ui import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import com.example.sodv3203_carrentalapp.R import com.example.sodv3203_carrentalapp.data.AppUiState import com.example.sodv3203_carrentalapp.ui.theme.SODV3203_CarRentalAppTheme @Composable fun DisplayPageSearch( appUiState: AppUiState, modifier: Modifier = Modifier, onBackButtonClicked: () -> Unit = {}, onSelectButtonClicked: () -> Unit = {} ) { Column( modifier = modifier ) { Text(text = "Placeholder: Search Page") Row( modifier = Modifier.padding(dimensionResource(R.dimen.padding_medium)) ) { Column( verticalArrangement = Arrangement.spacedBy(dimensionResource(R.dimen.padding_small)) ) { Button( modifier = Modifier.fillMaxWidth(), onClick = { onSelectButtonClicked() } ) { Text(stringResource(R.string.button_next)) } OutlinedButton( modifier = Modifier.fillMaxWidth(), onClick = { onBackButtonClicked() } ) { Text(stringResource(R.string.button_back)) } } } } } @Preview @Composable fun DisplayPageSearchPreview() { SODV3203_CarRentalAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { DisplayPageSearch( appUiState = AppUiState() ) } } }
0
Kotlin
0
1
869e1a76471f7313a77cc5a93a6f1b42297973b8
2,347
SODV3203_CarRentalApp
MIT License
compiler/testData/diagnostics/testsWithJsStdLib/name/classAndTypealias.kt
JetBrains
3,432,266
false
null
// FIR_IDENTICAL package foo @JsName("B") class A(val x: Int) typealias B = A
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
79
kotlin
Apache License 2.0
lib/src/main/java/com/icapps/architecture/utils/caching/Cached.kt
icapps
135,125,148
false
{"Kotlin": 104669}
package com.icapps.architecture.utils.caching import android.os.SystemClock import kotlin.reflect.KProperty /** * @author <NAME> * A utility class to create variables that expire (return null) after a while. * Usage: `var cachedValue: T? by Cached(CACHE_VALIDITY_MS)` */ class Cached<T>(private val cacheValidity: Long = DEFAULT_CACHE_DURATION) { companion object { const val DEFAULT_CACHE_DURATION = 60000L } private var cache: T? = null private var timestamp: Long? = null operator fun getValue(thisRef: Any, property: KProperty<*>): T? { synchronized(this) { return timestamp?.let { if (SystemClock.elapsedRealtime() - it <= cacheValidity) { cache } else { cache = null // Reset cache so we don't keep unnecessary objects in memory null } } } } operator fun setValue(thisRef: Any, property: KProperty<*>, value: T?) { synchronized(this) { cache = value timestamp = if (value == null) null else SystemClock.elapsedRealtime() } } }
0
Kotlin
0
3
3fe769cb62c791325b9fbb36e78f3851023323af
1,171
androidarchitecture
Apache License 2.0
app/src/main/java/husaynhakeem/io/unconnectifyre/data/repository/AlarmsRepository.kt
husaynhakeem
151,892,709
false
null
package husaynhakeem.io.unconnectifyre.data.repository import android.arch.lifecycle.LiveData import husaynhakeem.io.unconnectifyre.data.database.Alarm import husaynhakeem.io.unconnectifyre.data.database.AlarmDao import husaynhakeem.io.unconnectifyre.utilities.runOnIoThread class AlarmsRepository(private val alarmDao: AlarmDao) { fun createAlarm(alarm: Alarm) { runOnIoThread { alarmDao.createAlarm(alarm) } } fun updateAlarm(alarm: Alarm) { runOnIoThread { alarmDao.updateAlarm(alarm) } } fun deleteAlarm(alarmId: Int) { runOnIoThread { alarmDao.deleteAlarm(alarmId) } } fun getAllAlarms(): LiveData<List<Alarm>> = alarmDao.getAllAlarms() fun findAlarmById(alarmId: Int): LiveData<Alarm> = alarmDao.findAlarmById(alarmId) }
0
Kotlin
0
3
4ee13fc554b305a01d132d6e5db2fea44a633992
850
Unconnectify-Re
MIT License
lib_character_search/src/main/java/com/ezike/tobenna/starwarssearch/lib_character_search/data/repository/SearchRepositoryImpl.kt
Ezike
294,171,829
false
null
package com.ezike.tobenna.starwarssearch.lib_character_search.data.repository import com.ezike.tobenna.starwarssearch.lib_character_search.data.contract.remote.SearchRemote import com.ezike.tobenna.starwarssearch.lib_character_search.data.mapper.CharacterEntityMapper import com.ezike.tobenna.starwarssearch.lib_character_search.data.model.CharacterEntity import com.ezike.tobenna.starwarssearch.lib_character_search.domain.model.Character import com.ezike.tobenna.starwarssearch.lib_character_search.domain.repository.SearchRepository import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import javax.inject.Inject internal class SearchRepositoryImpl @Inject constructor( private val searchRemote: SearchRemote, private val characterEntityMapper: CharacterEntityMapper ) : SearchRepository { override fun searchCharacters(characterName: String): Flow<List<Character>> { return flow { val characters: List<CharacterEntity> = searchRemote.searchCharacters(characterName) emit(characterEntityMapper.mapFromEntityList(characters)) } } }
0
Kotlin
28
172
792caabf5a29b8bb4698c36c3257916a1cf6611d
1,112
StarWarsSearch-MVI
Apache License 2.0
app/src/main/kotlin/org/eurofurence/connavigator/util/SharingUtility.kt
eurofurence
50,885,645
false
null
package org.eurofurence.connavigator.util import android.content.Intent /** * Created by David on 6/5/2016. */ class SharingUtility { companion object { fun share(text: String): Intent { val shareIntent = Intent(); shareIntent.action = Intent.ACTION_SEND shareIntent.putExtra(Intent.EXTRA_TEXT, text) shareIntent.type = "text/plain" return shareIntent } } }
21
null
5
13
3da7b778cda0a9b39a5172bf48cb3cbc27604de8
446
ef-app_android
MIT License
build-logic/convention/src/main/kotlin/com/alexereh/csfbrs/BrsBuildType.kt
AlexEreh
680,205,233
false
{"Kotlin": 106073}
package com.alexereh.csfbrs enum class BrsBuildType(val applicationIdSuffix: String? = null) { DEBUG(".debug"), RELEASE, }
2
Kotlin
0
2
c1e9d62fd3eb3f52d1377cce4cb42dd7875d6fb3
131
CSFBRS
MIT License
subprojects/gradle/code-ownership/plugin/src/gradleTest/kotlin/com/avito/android/ConfigurationCacheCompatibilityTest.kt
avito-tech
230,265,582
false
null
package com.avito.android import com.avito.test.gradle.TestProjectGenerator import com.avito.test.gradle.TestResult import com.avito.test.gradle.gradlew import com.avito.test.gradle.module.AndroidLibModule import com.avito.test.gradle.plugin.plugins import org.junit.jupiter.api.Test import org.junit.jupiter.api.io.TempDir import java.io.File internal class ConfigurationCacheCompatibilityTest { @Test fun `configuration with applied plugin and info report - ok`(@TempDir projectDir: File) { TestProjectGenerator( name = "rootapp", plugins = plugins { id("com.avito.android.code-ownership") }, modules = listOf( AndroidLibModule( plugins = plugins { id("com.avito.android.code-ownership") }, name = "lib", imports = listOf( "import com.avito.android.model.Owner", "import com.avito.android.serializers.OwnerIdSerializer", "import com.avito.android.serializers.OwnerNameSerializer", "import com.avito.android.OwnerSerializerProvider", ), buildGradleExtra = """ |object Speed : Owner { } |object SpeedOwnerSerializersProvider : OwnerSerializerProvider { | | override fun provideIdSerializer() = object : OwnerIdSerializer { | override fun deserialize(ownerName: String): com.avito.android.model.Owner { | return Speed | } | | override fun serialize(owner: Owner): List<String> { | return listOf("Speed") | } | } | | override fun provideNameSerializer() = object : OwnerNameSerializer { | override fun deserialize(ownerId: String): com.avito.android.model.Owner { | return Speed | } | | override fun serialize(owner: Owner): String { | return "Speed" | } | } |} | |ownership { | owners(Speed) | ownerSerializersProvider.set(SpeedOwnerSerializersProvider) |} """.trimMargin(), useKts = true ) ) ).generateIn(projectDir) runInfoReportTask(projectDir).assertThat().buildSuccessful() runInfoReportTask(projectDir).assertThat().buildSuccessful().configurationCachedReused() } @Test fun `configuration with applied plugin and file report - ok`(@TempDir projectDir: File) { TestProjectGenerator( name = "rootapp", plugins = plugins { id("com.avito.android.code-ownership") }, imports = listOf( "import com.avito.android.model.StubOwner", "import com.avito.android.diff.provider.SimpleOwnersProvider", "import com.avito.android.diff.report.OwnersDiffReportDestination" ), buildGradleExtra = """ codeOwnershipDiffReport { expectedOwnersProvider.set(SimpleOwnersProvider(setOf())) actualOwnersProvider.set(SimpleOwnersProvider(setOf(StubOwner))) diffReportDestination.set(OwnersDiffReportDestination.File(project.projectDir)) } """.trimIndent(), useKts = true, modules = listOf(AndroidLibModule(name = "lib")) ).generateIn(projectDir) runDiffReportTask(projectDir).assertThat().buildSuccessful() runDiffReportTask(projectDir).assertThat().buildSuccessful().configurationCachedReused() } private fun runDiffReportTask(tempDir: File): TestResult { return gradlew( tempDir, "reportCodeOwnershipDiff", dryRun = false, configurationCache = true, useTestFixturesClasspath = true ) } private fun runInfoReportTask(tempDir: File): TestResult { return gradlew( tempDir, "exportInternalDepsCodeOwners", "-Pavito.ownership.strictOwnership=true", dryRun = true, configurationCache = true ) } }
10
null
50
414
bc94abf5cbac32ac249a653457644a83b4b715bb
4,883
avito-android
MIT License
vetric-core/src/main/kotlin/xyz/xenondevs/vetric/utils/InstructionParent.kt
ByteZ1337
268,610,002
false
{"Kotlin": 103904}
package xyz.xenondevs.vetric.utils import org.objectweb.asm.tree.InsnList import org.objectweb.asm.tree.MethodNode import xyz.xenondevs.bytebase.jvm.ClassWrapper import xyz.xenondevs.bytebase.jvm.JavaArchive /** * Class containing the parents of an instruction. * * - JavaArchive * - Class * - Method * - InsnList */ class InstructionParent(val jar: JavaArchive, val clazz: ClassWrapper, val method: MethodNode, val insnList: InsnList)
6
Kotlin
1
44
147da0512abd613b5a7001884dbddfa27d9c1b34
444
Vetric
MIT License
app/src/main/java/com/example/bookforum/ui/databaseUi/postsUI/viewModels/PostCreationViewModel.kt
KatePril
783,350,221
false
{"Kotlin": 303136}
package com.example.bookforum.ui.databaseUi.postsUI.viewModels import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import com.example.bookforum.data.repositories.PostsRepository import com.example.bookforum.ui.databaseUi.postsUI.states.PostCreationUiState import com.example.bookforum.ui.databaseUi.postsUI.states.PostDetails import com.example.bookforum.ui.databaseUi.postsUI.states.toPost import com.example.bookforum.ui.navigation.destinations.postDestinations.PostCreationDestination class PostCreationViewModel( savedStateHandle: SavedStateHandle, private val postsRepository: PostsRepository ): ViewModel() { val userId: Int = checkNotNull(savedStateHandle[PostCreationDestination.userIdArg]) var postCreationUiState by mutableStateOf(PostCreationUiState()) private set fun updateUiState(postDetails: PostDetails) { postCreationUiState = PostCreationUiState( postDetails = postDetails.copy(userId = userId), areInputsValid = validateInputs(postDetails) ) } private fun validateInputs(postDetails: PostDetails = postCreationUiState.postDetails): Boolean { return with(postDetails) { title.isNotBlank() && author.isNotBlank() && published.isNotBlank() && review.isNotBlank() } } suspend fun savePost() { if (validateInputs()) { postsRepository.insertPost(postCreationUiState.postDetails.toPost()) } } }
0
Kotlin
0
0
bcf718e6dad2bb11cbf5052f9f11f4580e957fba
1,612
BookForum1
MIT License
application/KotlinConcepts/app/src/main/java/com/istudio/app/modules/module_demos/flows/modules/collect_as_state_with_lifecycle/CollectAsStateWithLifeCycleVm.kt
devrath
339,281,472
false
{"Kotlin": 478593, "Java": 3273}
package com.istudio.app.modules.module_demos.flows.modules.collect_as_state_with_lifecycle import android.content.Context import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class CollectAsStateWithLifeCycleVm @Inject constructor( @ApplicationContext private val context: Context, ) : ViewModel() { companion object { const val INITIAL_VALUE = 0 } private var currentTime = INITIAL_VALUE private val _data = MutableStateFlow(0) val data = _data.asStateFlow() init { initiate() } private fun initiate() { viewModelScope.launch { while(true){ delay(1000L) println("Flow is active current time ---> $currentTime") _data.emit(currentTime++) } } } val newTimer = flow { while(true){ delay(1000L) println("Flow is active current time ---> $currentTime") emit(currentTime++) } }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000L),0) }
0
Kotlin
22
246
b87ccbc3cba789ec81744acde724274137204283
1,597
KotlinAlchemy
Apache License 2.0
app/src/main/java/com/notesandroid/codex/notesandroid/note/structure/blocks/ListBlock.kt
codex-team
117,150,893
false
null
package com.notesandroid.codex.notesandroid.note.structure.blocks import android.content.Context import android.graphics.Color import android.text.Spannable import android.text.SpannableStringBuilder import android.util.TypedValue import android.view.View import android.widget.LinearLayout import android.widget.TextView import com.google.gson.JsonElement import com.notesandroid.codex.notesandroid.R import com.notesandroid.codex.notesandroid.utilities.TextFormatter import com.notesandroid.codex.notesandroid.spans.HeightSpan import com.notesandroid.codex.notesandroid.spans.ListSpan /** * Block that contain list of items * @param context - Need for creating [TextView] * @param data - json element that contain information about item of list */ class ListBlock( context: Context, val data:JsonElement ) : NoteBlock(context) { override fun getView(): View = getListView() /** * Method for getting [TextView] like list */ private fun getListView(): View { val textView = TextView(context) textView.setTextColor(Color.BLACK) val builder = SpannableStringBuilder() val param = LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT ) param.setMargins(dpToPx(19).toInt(), dpToPx(5).toInt(), dpToPx(19).toInt(), dpToPx(5).toInt()) textView.layoutParams = param textView.typeface = getSameFont(R.font.roboto_regular) textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14F) val items = data.asJsonObject["items"].asJsonArray for (i in 1..items.size()) { val oldLength = builder.length //builder.append(TextFormatter.init(context).parse(items[i - 1].asString + "\n")) builder.append(TextFormatter.init(context).parse(items[i - 1].asString).append("\n")) builder.setSpan(HeightSpan(25), oldLength, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) if (data.asJsonObject["style"].asString == "ordered") { builder.setSpan(ListSpan(dpToPx(20).toInt(), dpToPx(20).toInt(), i), oldLength, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } else builder.setSpan(ListSpan(dpToPx(20).toInt(), dpToPx(20).toInt()), oldLength, builder.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) } textView.text = builder return textView } }
1
Kotlin
0
4
802f02c8826f1ded5006ad812cc33fdec21ed2b0
2,451
codex.notes.android
MIT License
app/src/main/java/com/saiferwp/lastfmalbums/data/api/request/AlbumInfoRequest.kt
eugene-ltv
221,215,367
false
null
package com.saiferwp.lastfmalbums.data.api.request import com.saiferwp.lastfmalbums.data.api.Api import com.saiferwp.lastfmalbums.data.api.response.AlbumInfoResponse import com.saiferwp.lastfmalbums.domain.model.AlbumMbId import kotlinx.coroutines.Deferred import retrofit2.Response class AlbumInfoRequest(private val mbId: AlbumMbId) : Request<AlbumInfoResponse>() { override fun executeAsync(api: Api): Deferred<Response<AlbumInfoResponse>> { return api.getAlbumDetailsAsync(mbId) } }
0
Kotlin
0
0
d58ea85d994b118a7f17493dc57b592745152e64
508
LastFM-Albums
Apache License 2.0
composeApp/src/commonMain/kotlin/ru/rznnike/demokmp/data/network/interceptor/HttpErrorResponseInterceptor.kt
RznNike
834,057,164
false
{"Kotlin": 253206}
package ru.rznnike.demokmp.data.network.interceptor import okhttp3.Interceptor import okhttp3.Response import ru.rznnike.demokmp.data.network.error.CustomServerException import ru.rznnike.demokmp.data.utils.HttpCode class HttpErrorResponseInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val response = chain .proceed(chain.request()) .run { if (code == HttpCode.NO_CONTENT.code) { newBuilder() .code(HttpCode.CUSTOM_NO_CONTENT.code) .build() } else { this } } if (!response.isSuccessful) { throw CustomServerException( httpCode = response.code ) } return response } }
0
Kotlin
0
0
c63c3676f4cf4d5a27cfe327d976bde45ec11015
863
DemoKMP
MIT License
formats/protobuf/commonTest/src/kotlinx/serialization/test/CurrentPlatform.common.kt
Kotlin
97,827,246
false
null
/* * Copyright 2017-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.serialization.test enum class Platform { JVM, JS, NATIVE, WASM } public expect val currentPlatform: Platform public fun isJs(): Boolean = currentPlatform == Platform.JS public fun isJvm(): Boolean = currentPlatform == Platform.JVM public fun isNative(): Boolean = currentPlatform == Platform.NATIVE public fun isWasm(): Boolean = currentPlatform == Platform.WASM
407
null
621
5,396
d4d066d72a9f92f06c640be5a36a22f75d0d7659
497
kotlinx.serialization
Apache License 2.0
app/src/main/java/uz/javokhirjambulov/notes/App.kt
JavokhirJambulov
514,119,906
false
{"Kotlin": 90074}
package uz.javokhirjambulov.notes import android.app.Application import uz.javokhirjambulov.notes.database.DeletedNoteDatabase import uz.javokhirjambulov.notes.database.NoteDatabase class App : Application() { override fun onCreate() { super.onCreate() NoteDatabase.initDatabase(context = this) DeletedNoteDatabase.initDatabase(context = this) } }
0
Kotlin
1
3
27e79c981969cb9b3dc9285181daebbdec37a484
382
Notes-App-Android
Apache License 2.0
src/test/kotlin/org/rust/FileTree.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.project.Project import com.intellij.openapi.util.text.StringUtil.convertLineSeparators import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.PsiFileSystemItem import com.intellij.psi.PsiManager import com.intellij.testFramework.fixtures.CodeInsightTestFixture import org.intellij.lang.annotations.Language import org.junit.Assert import org.junit.ComparisonFailure import org.rust.lang.core.macros.macroExpansionManagerIfCreated import org.rust.lang.core.psi.ext.RsNamedElement import org.rust.lang.core.psi.ext.RsReferenceElement import org.rust.lang.core.psi.ext.RsReferenceElementBase import org.rust.lang.core.psi.ext.containingCargoPackage import org.rust.lang.core.resolve.ResolveResult import org.rust.lang.core.resolve.checkResolvedFile import org.rust.openapiext.* import org.rust.stdext.exhaustive import java.nio.file.Files import kotlin.text.Charsets.UTF_8 fun fileTree(builder: FileTreeBuilder.() -> Unit): FileTree = FileTree(FileTreeBuilderImpl().apply { builder() }.intoDirectory()) fun fileTreeFromText(@Language("Rust") text: String, commentPrefix: String = "//"): FileTree { val fileSeparator = """^\s*$commentPrefix- (\S+)\s*$""".toRegex(RegexOption.MULTILINE) val fileNames = fileSeparator.findAll(text).map { it.groupValues[1] }.toList() val fileTexts = fileSeparator.split(text) .let { check(it.first().isBlank()) it.drop(1) } .map { it.trimIndent() } check(fileNames.size == fileTexts.size) { "Have you placed `//- filename.rs` markers?" } fun fill(dir: Entry.Directory, path: List<String>, contents: String) { val name = path.first() if (path.size == 1) { dir.children[name] = Entry.File(contents) } else { val childDir = dir.children.getOrPut(name) { Entry.Directory(mutableMapOf()) } as Entry.Directory fill(childDir, path.drop(1), contents) } } return FileTree(Entry.Directory(mutableMapOf()).apply { for ((path, contents) in fileNames.map { it.split("/") }.zip(fileTexts)) { fill(this, path, contents) } }) } interface FileTreeBuilder { fun dir(name: String, builder: FileTreeBuilder.() -> Unit) fun dir(name: String, tree: FileTree) fun file(name: String, code: String? = null) fun symlink(name: String, targetPath: String) fun rust(name: String, @Language("Rust") code: String) = file(name, code) fun toml(name: String, @Language("TOML") code: String) = file(name, code) } class FileTree(val rootDirectory: Entry.Directory) { fun create(project: Project, directory: VirtualFile): TestProject { val files: MutableList<String> = mutableListOf() val filesWithCaret: MutableList<String> = mutableListOf() val filesWithSelection: MutableList<String> = mutableListOf() fun go(dir: Entry.Directory, root: VirtualFile, parentComponents: List<String> = emptyList()) { for ((name, entry) in dir.children) { val components = parentComponents + name when (entry) { is Entry.File -> { val vFile = root.findChild(name) ?: root.createChildData(root, name) if (entry.text != null) { VfsUtil.saveText(vFile, replaceCaretMarker(entry.text)) val filePath = components.joinToString(separator = "/") files += filePath if (hasCaretMarker(entry.text) || "//^" in entry.text || "#^" in entry.text) { filesWithCaret += filePath } if (hasSelectionMarker(entry.text)) { filesWithSelection += filePath } } Unit } is Entry.Directory -> { go(entry, root.createChildDirectory(root, name), components) } is Entry.Symlink -> { check(root.fileSystem == LocalFileSystem.getInstance()) { "Symlinks are available only in LocalFileSystem" } Files.createSymbolicLink(root.pathAsPath.resolve(name), root.pathAsPath.resolve(entry.targetPath)) Unit } }.exhaustive } } runWriteAction { go(rootDirectory, directory) fullyRefreshDirectory(directory) } project.macroExpansionManagerIfCreated?.updateInUnitTestMode() return TestProject(project, directory, files, filesWithCaret, filesWithSelection) } fun assertEquals(baseDir: VirtualFile) = assertFiles(baseDir, true) fun assertContains(baseDir: VirtualFile) = assertFiles(baseDir, false) private fun assertFiles(baseDir: VirtualFile, failOnExtraChildren: Boolean) { fun go(expected: Entry.Directory, actual: VirtualFile) { val actualChildren = actual.children.associateBy { it.name } val expectedChildrenNames = expected.children.keys val actualChildrenNames = actualChildren.keys val relativePath = actual.path.removePrefix(baseDir.path) if (failOnExtraChildren) { if (expectedChildrenNames != actualChildrenNames) { throw ComparisonFailure( "Mismatch in directory $relativePath", expectedChildrenNames.toString(), actualChildrenNames.toString() ) } } else { // Take elements that exist in the first collection and absent in the other val nonExistent = expectedChildrenNames - actualChildrenNames if (nonExistent.isNotEmpty()) { throw ComparisonFailure( "Missing entries at $relativePath", expectedChildrenNames.toString(), actualChildrenNames.toString() ) } } for ((name, entry) in expected.children) { val a = actualChildren[name]!! when (entry) { is Entry.File -> { check(!a.isDirectory) val actualText = convertLineSeparators(String(a.contentsToByteArray(), UTF_8)) if (entry.text != null) { Assert.assertEquals(entry.text.trimEnd(), actualText.trimEnd()) } Unit } is Entry.Directory -> go(entry, a) is Entry.Symlink -> error("Symlink comparison is not supported!") }.exhaustive } } saveAllDocuments() go(rootDirectory, baseDir) } fun check(fixture: CodeInsightTestFixture) { fun go(dir: Entry.Directory, rootPath: String) { for ((name, entry) in dir.children) { val path = "$rootPath/$name" when (entry) { is Entry.File -> { val text = entry.text if (text == null) { if (fixture.findFileInTempDir(path) == null) error("No file at $path") Unit } else { fixture.checkResult(path, text, true) } } is Entry.Directory -> go(entry, path) is Entry.Symlink -> error("Symlink comparison is not supported!") }.exhaustive } } go(rootDirectory, ".") } } fun FileTree.create(fixture: CodeInsightTestFixture): TestProject = create(fixture.project, fixture.findFileInTempDir(".")) fun FileTree.createAndOpenFileWithCaretMarker(fixture: CodeInsightTestFixture): TestProject { val testProject = create(fixture) fixture.configureFromTempProjectFile(testProject.fileWithCaret) return testProject } class TestProject( private val project: Project, val root: VirtualFile, val files: List<String>, private val filesWithCaret: List<String>, private val filesWithSelection: List<String> ) { val fileWithCaret: String get() = when (filesWithCaret.size) { 1 -> filesWithCaret.single() 0 -> error("Please, add `/*caret*/` or `<caret>` marker to some file") else -> error("More than one file with carets found: $filesWithCaret") } val fileWithCaretOrSelection: String get() = filesWithCaret.singleOrNull() ?: fileWithSelection val fileWithSelection: String get() = filesWithSelection.single() inline fun <reified T : PsiElement> findElementInFile(path: String): T { return doFindElementInFile(path, T::class.java) } inline fun <reified T : RsReferenceElement> checkReferenceIsResolved( path: String, shouldNotResolve: Boolean = false, toCrate: String? = null, toFile: String? = null ) { val ref = findElementInFile<T>(path) val reference = ref.reference ?: error("Failed to get reference for `${ref.text}`") val res = reference.resolve() if (shouldNotResolve) { check(res == null) { "Reference ${ref.text} should be unresolved in `$path`" } } else { check(res != null) { "Failed to resolve the reference `${ref.text}` in `$path`." } if (toCrate != null) { val pkg = res.containingCargoPackage?.let { "${it.name} ${it.version}" } ?: "[nowhere]" check(pkg == toCrate) { "Expected to be resolved to $toCrate but actually resolved to $pkg" } } if (toFile != null) { val file = res.containingFile.virtualFile val result = checkResolvedFile(file, toFile) { file.fileSystem.findFileByPath(it) } check(result !is ResolveResult.Err) { (result as ResolveResult.Err).message } } } } @Suppress("unused") fun checkResolveInAllFiles() { for (path in filesWithCaret) { val file = file(path).toPsiFile(project)!! val (refElement, data, offset) = findElementWithDataAndOffsetInFile(file, RsReferenceElementBase::class.java, "^") if (data == "unresolved") { val resolved = refElement.reference?.resolve() check(resolved == null) { "$path: $refElement `${refElement.text}`should be unresolved, was resolved to\n$resolved `${resolved?.text}`" } return } val resolved = refElement.checkedResolve(offset, errorMessagePrefix = "$path: ") val target = findElementInFile(file, RsNamedElement::class.java, "X") check(resolved == target) { "$path: $refElement `${refElement.text}` should resolve to $target (${target.text}), was $resolved (${resolved.text}) instead" } } } fun <T : PsiElement> doFindElementInFile(path: String, psiClass: Class<T>): T { val file = file(path).toPsiFile(project)!! return findElementInFile(file, psiClass, "^") } private fun <T : PsiElement> findElementInFile(file: PsiFile, psiClass: Class<T>, marker: String): T { val (element, data, _) = findElementWithDataAndOffsetInFile(file, psiClass, marker) check(data.isEmpty()) { "Did not expect marker data" } return element } private fun <T : PsiElement> findElementWithDataAndOffsetInFile( file: PsiFile, psiClass: Class<T>, marker: String ): Triple<T, String, Int> { val elementsWithDataAndOffset = findElementsWithDataAndOffsetInFile(file, psiClass, marker) check(elementsWithDataAndOffset.isNotEmpty()) { "No `$marker` marker:\n${file.text}" } check(elementsWithDataAndOffset.size <= 1) { "More than one `$marker` marker:\n${file.text}" } return elementsWithDataAndOffset.first() } private fun <T : PsiElement> findElementsWithDataAndOffsetInFile( file: PsiFile, psiClass: Class<T>, marker: String ): List<Triple<T, String, Int>> { return findElementsWithDataAndOffsetInEditor( file, file.document!!, followMacroExpansions = true, psiClass, marker ) } fun psiFile(path: String): PsiFileSystemItem { val vFile = file(path) val psiManager = PsiManager.getInstance(project) return if (vFile.isDirectory) psiManager.findDirectory(vFile)!! else psiManager.findFile(vFile)!! } fun file(path: String): VirtualFile { return root.findFileByRelativePath(path) ?: error("Can't find `$path`") } } private class FileTreeBuilderImpl(val directory: MutableMap<String, Entry> = mutableMapOf()) : FileTreeBuilder { override fun dir(name: String, builder: FileTreeBuilder.() -> Unit) { check('/' !in name) { "Bad directory name `$name`" } directory[name] = FileTreeBuilderImpl().apply { builder() }.intoDirectory() } override fun dir(name: String, tree: FileTree) { check('/' !in name) { "Bad directory name `$name`" } directory[name] = tree.rootDirectory } override fun file(name: String, code: String?) { check('/' !in name) { "Bad file name `$name`" } directory[name] = Entry.File(code?.trimIndent()) } override fun symlink(name: String, targetPath: String) { directory[name] = Entry.Symlink(targetPath) } fun intoDirectory() = Entry.Directory(directory) } sealed class Entry { class File(val text: String?) : Entry() class Directory(val children: MutableMap<String, Entry>) : Entry() class Symlink(val targetPath: String) : Entry() } fun replaceCaretMarker(text: String): String = text.replace("/*caret*/", "<caret>") fun hasCaretMarker(text: String): Boolean = text.contains("/*caret*/") || text.contains("<caret>") fun hasSelectionMarker(text: String): Boolean = text.contains("<selection>") && text.contains("</selection>")
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
14,937
intellij-rust
MIT License
p8e-shared/src/main/kotlin/io/provenance/p8e/shared/util/ProtoByteColumn.kt
provenance-io
340,506,091
false
null
package io.provenance.p8e.shared.util import com.google.protobuf.Message import io.netty.buffer.ByteBufInputStream import org.jetbrains.exposed.sql.Column import org.jetbrains.exposed.sql.ColumnType import org.jetbrains.exposed.sql.Table import java.io.InputStream import java.sql.ResultSet fun <R : Message, T : Table> T.protoBytes(name: String, message: R): Column<R> = registerColumn(name, ProtoByteAColumnType(message)) class ProtoByteAColumnType<T: Message>(private val message: T): ColumnType() { override fun sqlType() = "bytea" override fun notNullValueToDB(value: Any): Any = when { message::class.java.isInstance(value) -> message::class.java.cast(value).toByteArray() value is ByteArray -> value else -> throw IllegalStateException("Unknown type when serializing ${message::class.java.canonicalName}: ${value::class.java.canonicalName}") } override fun valueFromDB(value: Any): Any = when (value) { is ByteArray -> message.parserForType.parseFrom(value) is Message -> value is InputStream -> value.use { message.parserForType.parseFrom(it) } is ByteBufInputStream -> throw IllegalStateException("Known bug when using ByteBufInputStream inside of valueFromDB due to race between GC and Ref Counting") else -> throw IllegalStateException("Unknown type when serializing ${message::class.java.canonicalName}: ${value::class.java.canonicalName}") } override fun valueToDB(value: Any?): Any? = value?.let { notNullValueToDB(value) } override fun readObject( rs: ResultSet, index: Int ): Any? { return rs.getBinaryStream(index).use { it.readAllBytes() } } }
2
Kotlin
0
23
f39efd898512f9bba240b8d6c5e6bba9dbd6a282
1,754
p8e
Apache License 2.0
simplified-books-controller/src/main/java/org/nypl/simplified/books/controller/ProfileAccountCreateCustomOPDSTask.kt
ThePalaceProject
367,082,997
false
null
package org.nypl.simplified.books.controller import com.io7m.jfunctional.OptionType import com.io7m.jfunctional.Some import io.reactivex.subjects.Subject import one.irradia.mime.api.MIMEType import org.joda.time.DateTime import org.librarysimplified.http.api.LSHTTPClientType import org.librarysimplified.http.api.LSHTTPRequestBuilderType.AllowRedirects.ALLOW_REDIRECTS import org.librarysimplified.http.api.LSHTTPResponseStatus import org.nypl.simplified.accounts.api.AccountEvent import org.nypl.simplified.accounts.api.AccountEventCreation.AccountEventCreationFailed import org.nypl.simplified.accounts.api.AccountEventCreation.AccountEventCreationInProgress import org.nypl.simplified.accounts.api.AccountProviderDescription import org.nypl.simplified.accounts.api.AccountProviderType import org.nypl.simplified.accounts.database.api.AccountType import org.nypl.simplified.accounts.registry.api.AccountProviderRegistryType import org.nypl.simplified.links.Link import org.nypl.simplified.metrics.api.MetricServiceType import org.nypl.simplified.opds.core.OPDSAcquisitionFeed import org.nypl.simplified.opds.core.OPDSFeedConstants import org.nypl.simplified.opds.core.OPDSFeedParserType import org.nypl.simplified.profiles.api.ProfilesDatabaseType import org.nypl.simplified.profiles.controller.api.ProfileAccountCreationStringResourcesType import org.nypl.simplified.taskrecorder.api.TaskRecorder import org.nypl.simplified.taskrecorder.api.TaskResult import org.nypl.simplified.taskrecorder.api.TaskStep import org.slf4j.LoggerFactory import java.io.IOException import java.net.URI import java.util.UUID import java.util.concurrent.Callable /** * A task that creates an account based on a custom OPDS feed. */ class ProfileAccountCreateCustomOPDSTask( private val accountEvents: Subject<AccountEvent>, private val accountProviderRegistry: AccountProviderRegistryType, private val httpClient: LSHTTPClientType, private val opdsURI: URI, private val opdsFeedParser: OPDSFeedParserType, private val profiles: ProfilesDatabaseType, private val strings: ProfileAccountCreationStringResourcesType, private val metrics: MetricServiceType? ) : Callable<TaskResult<AccountType>> { private var title: String = "" private var description: String = "" private val logger = LoggerFactory.getLogger(ProfileAccountCreateCustomOPDSTask::class.java) private val taskRecorder = TaskRecorder.create() override fun call(): TaskResult<AccountType> { this.publishProgressEvent(this.taskRecorder.beginNewStep(this.strings.creatingAccount)) this.logger.debug("creating a custom OPDS account") return try { val accountProviderDescription = this.createAccountProviderDescription() val resolutionResult = this.accountProviderRegistry.resolve( { _, message -> this.publishProgressEvent(this.taskRecorder.beginNewStep(message)) }, accountProviderDescription ) when (resolutionResult) { is TaskResult.Success -> this.createAccount(accountProviderDescription) is TaskResult.Failure -> this.accountResolutionFailed(resolutionResult) } } catch (e: Throwable) { this.logger.error("account creation failed: ", e) this.taskRecorder.currentStepFailedAppending( message = this.strings.unexpectedException, errorCode = "unexpectedException", exception = e, extraMessages = listOf() ) this.publishFailureEvent() this.taskRecorder.finishFailure() } } private fun accountResolutionFailed( resolutionResult: TaskResult.Failure<AccountProviderType> ): TaskResult.Failure<AccountType> { this.logger.error("could not resolve an account provider description") this.taskRecorder.addAll(resolutionResult.steps) this.taskRecorder.addAttributes(resolutionResult.attributes) this.taskRecorder.currentStepFailed( message = this.strings.resolvingAccountProviderFailed, errorCode = "resolvingAccountProviderFailed", extraMessages = listOf() ) return this.taskRecorder.finishFailure() } private fun createAccount( accountProviderDescription: AccountProviderDescription ): TaskResult<AccountType> { val createResult = ProfileAccountCreateTask( accountEvents = this.accountEvents, accountProviderID = accountProviderDescription.id, accountProviders = this.accountProviderRegistry, profiles = this.profiles, strings = this.strings, metrics = this.metrics ).call() return when (createResult) { is TaskResult.Success<AccountType> -> { this.taskRecorder.addAll(createResult.steps) val account = createResult.result account.setPreferences(account.preferences.copy(catalogURIOverride = this.opdsURI)) this.publishProgressEvent(this.taskRecorder.currentStepSucceeded(this.strings.creatingAccountSucceeded)) this.taskRecorder.finishSuccess(createResult.result) } is TaskResult.Failure<AccountType> -> { this.taskRecorder.addAll(createResult.steps) this.taskRecorder.finishFailure() } } } /** * Create a custom account provider description. */ private fun createAccountProviderDescription(): AccountProviderDescription { this.logger.debug("creating an account provider description") this.publishProgressEvent(this.taskRecorder.beginNewStep(this.strings.creatingAnAccountProviderDescription)) val authDocumentURI: URI? = this.findAuthenticationDocumentURI() val id = URI.create("urn:custom:" + UUID.randomUUID().toString()) this.logger.debug("account id will be {}", id) val links = mutableListOf<Link>() links.add( Link.LinkBasic( href = this.opdsURI, relation = "http://opds-spec.org/catalog" ) ) if (authDocumentURI != null) { links.add( Link.LinkBasic( href = authDocumentURI, type = MIMEType("application", "vnd.opds.authentication.v1.0+json", mapOf()), relation = OPDSFeedConstants.AUTHENTICATION_DOCUMENT_RELATION_URI_TEXT ) ) } val description = AccountProviderDescription( id = id, title = this.title, description = this.description, updated = DateTime.now(), links = links, images = listOf(), isProduction = true, isAutomatic = false, location = null ) /* * Publish the description to the account provider registry. It is now possible * to create an account using the description; the account creation task will ask * the registry to resolve the account provider description. */ this.accountProviderRegistry.updateDescription(description) return description } private fun findAuthenticationDocumentURI(): URI? { this.logger.debug("creating an account provider description") this.publishProgressEvent(this.taskRecorder.beginNewStep(this.strings.findingAuthDocumentURI)) this.publishProgressEvent(this.taskRecorder.beginNewStep(this.strings.fetchingOPDSFeed)) val request = this.httpClient.newRequest(this.opdsURI) .allowRedirects(ALLOW_REDIRECTS) .build() return request.execute().use { response -> this.taskRecorder.addAttributes( response.status.properties?.problemReport?.toMap() ?: emptyMap() ) when (val status = response.status) { is LSHTTPResponseStatus.Responded.OK -> { this.logger.debug("fetched opds feed") /* * Parse the result as an OPDS feed and then try to find the authentication document * link inside it. */ try { this.publishProgressEvent(this.taskRecorder.beginNewStep(this.strings.parsingOPDSFeed)) val feed = this.opdsFeedParser.parse(this.opdsURI, status.bodyStream) this.title = feed.feedTitle this.findAuthenticationDocumentLink(feed) } catch (e: Exception) { this.taskRecorder.currentStepFailed( message = e.message ?: e.javaClass.name, errorCode = "parsingOPDSFeedFailed", extraMessages = listOf() ) this.publishFailureEvent() throw e } } is LSHTTPResponseStatus.Responded.Error -> { this.logger.debug("failed to fetch opds feed") /* * If the server returns an error but delivers an authentication document as a result, * well... We've found the authentication document. */ val contentTypes = status.properties.headers["content-type"] if (contentTypes != null) { if (contentTypes.contains("application/vnd.opds.authentication.v1.0+json")) { this.logger.debug("delivered authentication document instead of error") return this.opdsURI } } /* * Any other error is fatal. */ this.taskRecorder.currentStepFailed( message = this.strings.fetchingOPDSFeedFailed, errorCode = "fetchingOPDSFeedFailed", extraMessages = listOf() ) this.publishFailureEvent() throw IOException() } is LSHTTPResponseStatus.Failed -> { this.logger.debug("failed to fetch opds feed: ", status.exception) /* * An exception is fatal. */ this.taskRecorder.currentStepFailed( message = this.strings.fetchingOPDSFeedFailed, errorCode = "httpRequestFailed", exception = status.exception, extraMessages = listOf() ) this.publishFailureEvent() throw status.exception } } } } private fun findAuthenticationDocumentLink(feed: OPDSAcquisitionFeed): URI? { this.publishProgressEvent(this.taskRecorder.beginNewStep(this.strings.searchingFeedForAuthenticationDocument)) return this.someOrNull(feed.authDocument) } private fun <T> someOrNull(opt: OptionType<T>?): T? { return if (opt is Some<T>) { opt.get() } else { null } } private fun publishFailureEvent() = this.accountEvents.onNext(AccountEventCreationFailed(this.taskRecorder.finishFailure<AccountType>())) private fun publishProgressEvent(step: TaskStep) = this.accountEvents.onNext(AccountEventCreationInProgress(step.description)) }
109
null
4
8
f68b6907367e2213f1dcde700ca5c91f2f515ada
10,553
android-core
Apache License 2.0
multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/mangasar/MangaSarGenerator.kt
tachiyomiorg
79,658,844
false
null
package eu.kanade.tachiyomi.multisrc.mangasar import generator.ThemeSourceData.SingleLang import generator.ThemeSourceGenerator class MangaSarGenerator : ThemeSourceGenerator { override val themePkg = "mangasar" override val themeClass = "MangaSar" override val baseVersionCode: Int = 7 override val sources = listOf( SingleLang("Fire Mangás", "https://firemangas.com", "pt-BR", className = "FireMangas"), SingleLang("Mangazim", "https://mangazim.com", "pt-BR"), SingleLang("MangásUp", "https://mangasup.net", "pt-BR", className = "MangasUp"), SingleLang("Seemangas", "https://seemangas.com", "pt-BR", isNsfw = true), ) companion object { @JvmStatic fun main(args: Array<String>) { MangaSarGenerator().createAll() } } }
561
null
963
2,736
ef58b57c6547516045c4c7ca1d6f7a1718d78f35
823
tachiyomi-extensions
Apache License 2.0
src/object_pool/main/Run.kt
yorae39
464,176,357
false
{"Kotlin": 60335}
package object_pool.main import object_pool.api.Employee import object_pool.api.EmployeePool fun main() { poolTest() } fun poolTest() { val employees = createEmployeeList() val employeePool = EmployeePool() for (employee in employees) { println("Acquiring employee: ${employee.name}") employeePool.acquire(employee) } var employee = employeePool.release() println() while (employee != null) { println("Releasing employee: ${employee.name}") employee = employeePool.release() } } fun createEmployeeList(): MutableList<Employee> { val employees = mutableListOf<Employee>() val employee1 = Employee("<NAME>") val employee2 = Employee("Thiago") val employee3 = Employee("Jorge") val employee4 = Employee("Kaio") employees.add(employee1) employees.add(employee2) employees.add(employee3) employees.add(employee4) return employees }
0
Kotlin
0
0
2d5a321f6e60ae91028adda860ab2d75c0b37ed1
941
design-patterns-kotlin
MIT License
app/src/main/java/top/abr/myaccount/MainActivity.kt
AndyBRoswell
428,968,773
false
{"Kotlin": 60548}
package top.abr.myaccount import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.view.Menu import android.view.MenuItem import android.widget.Toast import androidx.appcompat.app.ActionBarDrawerToggle import androidx.appcompat.app.AppCompatDelegate import androidx.drawerlayout.widget.DrawerLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import org.json.JSONObject import org.json.JSONTokener import top.abr.myaccount.databinding.ActivityMainBinding import java.io.* import java.lang.StringBuilder import java.math.BigDecimal import java.time.ZonedDateTime import java.util.* import kotlin.collections.LinkedHashMap class MainActivity : AppCompatActivity() { // Essential vars lateinit var DefIDir: String lateinit var DefEDir: String // UI components lateinit var ActivityMain: ActivityMainBinding lateinit var MainDrawerLayout: DrawerLayout lateinit var NavDrawerListener: ActionBarDrawerToggle lateinit var AccountView: RecyclerView lateinit var AccountViewAdapter: AccountBookAdapter // Demo data val DemoAccountBook = AccountBook().apply { AddItems( AccountBook.Item( Name = "12900K", Time = ZonedDateTime.now(), Site = "京东", Account = "微信", OriginalCurrency = Currency.getInstance("CNY"), OriginalAmount = 4999.00, Details = """ Intel Core i9-12900K CPU 8P16T @ 3.20 GHz / 5.10 GHz 8E8T @ 2.40 GHz / 3.20 GHz L2: 14 MB Pwr: 125 W / 241 W Litro: Intel 7 (10ESF) Mem: 2CH DDR4 3200 (51.2 GB/s), 2CH DDR5 4800 (76.8 GB/s) PCI-E 4.0/5.0 (20 Lanes) """.trimIndent() ), AccountBook.Item( Name = "1DX Mark 3", Time = ZonedDateTime.now(), Site = "Canon Online Store (USA)", Account = "PayPal", OriginalCurrency = Currency.getInstance("USD"), OriginalAmount = 6499.00, ExchangeRate = 6.37, Labels = HashSet(), Details = "Canon 1DX Mark III DSLR Camera, 5.5K@59.94 RAW (1.90:1)" ), AccountBook.Item( Name = "fripSide 24/96", Time = ZonedDateTime.now(), Site = "OTOTOY", Account = "PayPal", OriginalCurrency = Currency.getInstance("JPY"), OriginalAmount = 9900.00, ExchangeRate = 0.056, Labels = HashSet(), Details = """ the very best of fripSide 2009-2020 the very best of fripSide -moving ballads- """.trimIndent() ) ) } override fun onCreate(SavedInstanceState: Bundle?) { super.onCreate(SavedInstanceState) // Load essential vars DefIDir = filesDir.toString() DefEDir = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) getExternalFilesDir(null).toString() else "" // Inflate ActivityMain = ActivityMainBinding.inflate(layoutInflater) setContentView(ActivityMain.root) MainDrawerLayout = ActivityMain.MainDrawerLayout.apply { NavDrawerListener = ActionBarDrawerToggle(this@MainActivity, this, R.string.open_nav_drawer, R.string.close_nav_drawer) addDrawerListener(NavDrawerListener) // Pass the Open and Close toggle for the drawer layout listener to toggle the button } supportActionBar!!.setDisplayHomeAsUpEnabled(true) // To make the navigation drawer icon always appear on the action bar // Theme AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) // Dark theme as default AccountView = ActivityMain.AccountView // AccountViewAdapter = AccountBookAdapter(this, DemoAccountBook) // Use demo data AccountViewAdapter = AccountBookAdapter(this, AccountBook()) AccountView.adapter = AccountViewAdapter AccountView.layoutManager = LinearLayoutManager(this) } override fun onPostCreate(SavedInstanceState: Bundle?) { super.onPostCreate(SavedInstanceState) NavDrawerListener.syncState() // Synchronize the indicator with the state of the linked DrawerLayout after onRestoreInstanceState has occurred. } override fun onCreateOptionsMenu(M: Menu?): Boolean { menuInflater.inflate(R.menu.main_options, M) return true } override fun onOptionsItemSelected(SelectedItem: MenuItem): Boolean { if (NavDrawerListener.onOptionsItemSelected(SelectedItem)) return true // Open and close the navigation drawer when the ≡ icon is clicked when (SelectedItem.itemId) { R.id.MainOptionsOrderByTime -> {} R.id.MainOptionsAddAccountBookItem -> AccountViewAdapter.OnAccountBookContextAddClicked() R.id.MainOptionsClearAccountBookItem -> AccountViewAdapter.ClearAccountItems() R.id.MainOptionsReadFromDefIDir -> OnReadFromDefIDirSelected() R.id.MainOptionsReadFromDefEDir -> OnReadFromDefEDirSelected() R.id.MainOptionsReadFromCustomDir -> {} R.id.MainOptionsSaveToDefIDir -> OnSaveToDefIDirSelected() R.id.MainOptionsSaveToDefEDir -> OnSaveToDefEDirSelected() R.id.MainOptionsSaveToCustomDir -> {} } return super.onOptionsItemSelected(SelectedItem) } private fun ReadAccountBook(PathName: String) { // Failed to ser/deser instances of AccountBookFile with DSL JSON. Temporarily use org.json lib instead. val AccountBookFileReader = BufferedReader(FileReader(File(PathName))) val AccountBookBuilder = StringBuilder() while (true) { val CurrentLine = AccountBookFileReader.readLine() ?: break AccountBookBuilder.append(CurrentLine).append(System.lineSeparator()) } val Root = JSONTokener(AccountBookBuilder.toString()).nextValue() as JSONObject val SerializedItems = Root.getString("Items") val Items = JSONProcessor.Deserialize(Map::class.java, SerializedItems)!! AccountViewAdapter.MAccountBook.ClearItems() for (Entry in Items) { val K = (Entry.key as String).toLong() val MV = Entry.value as LinkedHashMap<*, *> val V = AccountBook.Item( Name = MV["name"]!! as String, Time = ZonedDateTime.parse(MV["time"]!! as CharSequence?), Site = MV["site"]!! as String, Account = MV["account"]!! as String, OriginalAmount = (MV["originalAmount"]!! as BigDecimal).toDouble(), OriginalCurrency = Currency.getInstance(MV["originalCurrency"]!! as String), Details = MV["details"]!! as String ) AccountViewAdapter.MAccountBook.AddItem(K, V) } AccountViewAdapter.Refresh() Toast.makeText(this, resources.getString(R.string.successfully_read) + ' ' + PathName, Toast.LENGTH_SHORT).show() } fun OnReadFromDefIDirSelected() { val PathName = "$DefIDir/AccountBook.json" ReadAccountBook(PathName) } fun OnReadFromDefEDirSelected() { val PathName = "$DefEDir/AccountBook.json" ReadAccountBook(PathName) } private fun SaveAccountBook(PathName: String) { // Failed to ser/deser instances of AccountBookFile with DSL JSON. Temporarily use org.json lib instead. val Items = JSONProcessor.Serialize(AccountViewAdapter.MAccountBook.GetItems()) val DefaultCurrencies = JSONProcessor.Serialize(AccountViewAdapter.MAccountBook.GetAccountDefaultCurrencies()) val JSONO = JSONObject().apply { put("Items", Items) put("DefaultCurrencies", DefaultCurrencies) } val AccountBookSaver = BufferedWriter(FileWriter(File(PathName))) AccountBookSaver.write(JSONO.toString()) AccountBookSaver.close() Toast.makeText(this, resources.getString(R.string.successfully_saved_at) + ' ' + PathName, Toast.LENGTH_SHORT).show() } fun OnSaveToDefIDirSelected() { // val PathName = DefIDir + """/AccountBook-""" + ZonedDateTime.now().format(DefaultShortDateTimeFormat) + ".json" val PathName = "$DefIDir/AccountBook.json" SaveAccountBook(PathName) } fun OnSaveToDefEDirSelected() { // val PathName = DefEDir + """/AccountBook-""" + ZonedDateTime.now().format(DefaultShortDateTimeFormat) + ".json" val PathName = "$DefEDir/AccountBook.json" SaveAccountBook(PathName) } }
0
Kotlin
0
0
3e809f00a0ae58cf7ac847d87c474761ea36d3f0
8,945
MyAccount
MIT License
feature/catalog/data/src/main/java/ru/startandroid/feature/catalog/data/di/MappingModule.kt
startandroid
859,175,838
false
{"Kotlin": 49121}
package ru.startandroid.feature.catalog.data.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import ru.startandroid.core.common.data.mapping.Mapping import ru.startandroid.core.database.catalog.folder.FolderDb import ru.startandroid.feature.catalog.data.mapping.FolderMapDbToDm import ru.startandroid.feature.catalog.data.mapping.FolderMapDmToDb import ru.startandroid.feature.catalog.domain.model.FolderDm @Module @InstallIn(SingletonComponent::class) abstract class MappingModule { @Binds abstract fun bindFolderMapDbToDm(folderMapDbToDm: FolderMapDbToDm): Mapping<FolderDb, FolderDm> @Binds abstract fun bindFolderMapDmToDb(folderMapDmToDb: FolderMapDmToDb): Mapping<FolderDm, FolderDb> }
0
Kotlin
0
0
43ddc4af79393fab18f6ffe46b9ffc00d1121043
785
shoppinglist
MIT License
app/src/main/java/tech/soit/quiet/repository/netease/result/PlaylistDetailResultBean.kt
boyan01
114,945,726
false
null
package tech.summerly.quiet.data.netease.result /** * author : SUMMERLY * e-mail : <EMAIL> * time : 2017/8/25 * desc : */ data class PlaylistDetailResultBean( val playlist: Playlist?, val code: Int) { data class Playlist( val subscribed: Boolean, val tracks: List<Track>?, val coverImgUrl: String, val trackCount: Int, val playCount: Int, val trackUpdateTime: Long, val updateTime: Long, val name: String, val id: Long ) data class Track( val name: String?, val id: Long, val ar: List<Artist>?, val pop: Int, val crbt: String, val al: Album?, val mv: Long, val no: Long, val dt: Int ) data class Artist( val id: Long, val name: String? ) data class Album( val id: Long, val name: String?, val picUrl: String? ) }
0
Kotlin
3
27
0ba7211c39bf6d144dcda8f79a0d10f4e57b2208
1,050
MusicPlayer
Apache License 2.0
solve-problog/src/commonMain/kotlin/it/unibo/tuprolog/solve/problog/lib/knowledge/impl/BinaryDecisionDiagramExplanation.kt
tuProlog
230,784,338
false
null
package it.unibo.tuprolog.solve.problog.lib.knowledge.impl import it.unibo.tuprolog.bdd.BinaryDecisionDiagram import it.unibo.tuprolog.bdd.andThenExpansion import it.unibo.tuprolog.bdd.any import it.unibo.tuprolog.bdd.expansion import it.unibo.tuprolog.bdd.map import it.unibo.tuprolog.bdd.notThenExpansion import it.unibo.tuprolog.bdd.orThenExpansion import it.unibo.tuprolog.solve.problog.lib.knowledge.ProbExplanation import it.unibo.tuprolog.solve.problog.lib.knowledge.ProbTerm /** * This class implements [ProbExplanation] by compiling knowledge into [BinaryDecisionDiagram]s. * * @author <NAME> * */ internal class BinaryDecisionDiagramExplanation( val diagram: BinaryDecisionDiagram<ProbTerm>, private val computedValue: ComputedValue = EMPTY_COMPUTED_VALUE ) : ProbExplanation { internal data class ComputedValue( val probability: Double? ) companion object { internal val EMPTY_COMPUTED_VALUE = ComputedValue(null) internal val FALSE_COMPUTED_VALUE = ComputedValue(0.0) internal val TRUE_COMPUTED_VALUE = ComputedValue(1.0) } private fun getAsInternal(that: ProbExplanation): BinaryDecisionDiagramExplanation { if (that !is BinaryDecisionDiagramExplanation) { throw UnsupportedOperationException("that does not support Binary Decision Diagrams") } return that } private fun computeExpansion(value: ProbTerm, low: ComputedValue, high: ComputedValue): ComputedValue { return ComputedValue( if (low.probability != null && high.probability != null) { value.probability * high.probability + (1.0 - value.probability) * low.probability } else { null } ) } private val cachedNot: ProbExplanation by lazy { val result = diagram.notThenExpansion(FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { node, low, high -> computeExpansion(node, low, high) } BinaryDecisionDiagramExplanation(result.first, result.second) } override fun not(): ProbExplanation = cachedNot override fun and(that: ProbExplanation): ProbExplanation { val result = diagram.andThenExpansion(getAsInternal(that).diagram, FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { node, low, high -> computeExpansion(node, low, high) } return BinaryDecisionDiagramExplanation(result.first, result.second) } override fun or(that: ProbExplanation): ProbExplanation { val result = diagram.orThenExpansion(getAsInternal(that).diagram, FALSE_COMPUTED_VALUE, TRUE_COMPUTED_VALUE) { node, low, high -> computeExpansion(node, low, high) } return BinaryDecisionDiagramExplanation(result.first, result.second) } override val probability: Double by lazy { computedValue.probability ?: diagram.expansion(0.0, 1.0) { node, low, high -> node.probability * high + (1.0 - node.probability) * low } } override val containsAnyNotGroundTerm: Boolean by lazy { diagram.any { !it.isGround } } override fun toString(): String { return "bdd:${diagram.hashCode()}" } override fun apply(transformation: (ProbTerm) -> ProbTerm): ProbExplanation { return BinaryDecisionDiagramExplanation( diagram.map { transformation(it) } ) } }
92
null
14
93
3223ffc302e5da0efe2b254045fa1b6a1a122519
3,498
2p-kt
Apache License 2.0
wear/compose/compose-material/src/main/java/androidx/wear/compose/material/SwipeToDismissBox.kt
androidx
256,589,781
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.compose.material import androidx.annotation.RestrictTo import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.TweenSpec import androidx.compose.foundation.layout.BoxScope import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.Stable import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.wear.compose.foundation.LocalSwipeToDismissBackgroundScrimColor import androidx.wear.compose.foundation.LocalSwipeToDismissContentScrimColor import androidx.wear.compose.foundation.edgeSwipeToDismiss as foundationEdgeSwipeToDismiss /** * Wear Material [SwipeToDismissBox] that handles the swipe-to-dismiss gesture. Takes a single * slot for the background (only displayed during the swipe gesture) and the foreground content. * * Example of a [SwipeToDismissBox] with stateful composables: * @sample androidx.wear.compose.material.samples.StatefulSwipeToDismissBox * * Example of using [Modifier.edgeSwipeToDismiss] with [SwipeToDismissBox] * @sample androidx.wear.compose.material.samples.EdgeSwipeForSwipeToDismiss * * For more information, see the * [Swipe to dismiss](https://developer.android.com/training/wearables/components/swipe-to-dismiss) * guide. * * @param state State containing information about ongoing swipe or animation. * @param modifier Optional [Modifier] for this component. * @param backgroundScrimColor Color for background scrim * @param contentScrimColor Optional [Color] used for the scrim over the * content composable during the swipe gesture. * @param backgroundKey Optional [key] which identifies the content currently composed in * the [content] block when isBackground == true. Provide the backgroundKey if your background * content will be displayed as a foreground after the swipe animation ends * (as is common when [SwipeToDismissBox] is used for the navigation). This allows * remembered state to be correctly moved between background and foreground. * @Param contentKey Optional [key] which identifies the content currently composed in the * [content] block when isBackground == false. See [backgroundKey]. * @Param hasBackground Optional [Boolean] used to indicate if the content has no background, * in which case the swipe gesture is disabled (since there is no parent destination). * @param content Slot for content, with the isBackground parameter enabling content to be * displayed behind the foreground content - the background is normally hidden, * is shown behind a scrim during the swipe gesture, * and is shown without scrim once the finger passes the swipe-to-dismiss threshold. */ @Composable public fun SwipeToDismissBox( state: androidx.wear.compose.foundation.SwipeToDismissBoxState, modifier: Modifier = Modifier, backgroundScrimColor: Color = MaterialTheme.colors.background, contentScrimColor: Color = MaterialTheme.colors.background, backgroundKey: Any = SwipeToDismissKeys.Background, contentKey: Any = SwipeToDismissKeys.Content, hasBackground: Boolean = true, content: @Composable BoxScope.(isBackground: Boolean) -> Unit ) { CompositionLocalProvider( LocalSwipeToDismissBackgroundScrimColor provides backgroundScrimColor, LocalSwipeToDismissContentScrimColor provides contentScrimColor ) { androidx.wear.compose.foundation.SwipeToDismissBox( state = state, modifier = modifier, backgroundKey = backgroundKey, contentKey = contentKey, userSwipeEnabled = hasBackground, content = content ) } } /** * Wear Material [SwipeToDismissBox] that handles the swipe-to-dismiss gesture. Takes a single * slot for the background (only displayed during the swipe gesture) and the foreground content. * * Example of a [SwipeToDismissBox] with stateful composables: * @sample androidx.wear.compose.material.samples.StatefulSwipeToDismissBox * * Example of using [Modifier.edgeSwipeToDismiss] with [SwipeToDismissBox] * @sample androidx.wear.compose.material.samples.EdgeSwipeForSwipeToDismiss * * For more information, see the * [Swipe to dismiss](https://developer.android.com/training/wearables/components/swipe-to-dismiss) * guide. * * @param state State containing information about ongoing swipe or animation. * @param modifier Optional [Modifier] for this component. * @param backgroundScrimColor Color for background scrim * @param contentScrimColor Optional [Color] used for the scrim over the * content composable during the swipe gesture. * @param backgroundKey Optional [key] which identifies the content currently composed in * the [content] block when isBackground == true. Provide the backgroundKey if your background * content will be displayed as a foreground after the swipe animation ends * (as is common when [SwipeToDismissBox] is used for the navigation). This allows * remembered state to be correctly moved between background and foreground. * @Param contentKey Optional [key] which identifies the content currently composed in the * [content] block when isBackground == false. See [backgroundKey]. * @Param hasBackground Optional [Boolean] used to indicate if the content has no background, * in which case the swipe gesture is disabled (since there is no parent destination). * @param content Slot for content, with the isBackground parameter enabling content to be * displayed behind the foreground content - the background is normally hidden, * is shown behind a scrim during the swipe gesture, * and is shown without scrim once the finger passes the swipe-to-dismiss threshold. */ @Suppress("DEPRECATION") @Deprecated( "This overload is provided for backwards compatibility. " + "A newer overload is available that uses " + "androidx.wear.compose.foundation.SwipeToDismissBoxState.", replaceWith = ReplaceWith("SwipeToDismissBox(" + "state, modifier, backgroundScrimColor, contentScrimColor, backgroundKey, contentKey," + "hasBackground, content)" ) ) @Composable public fun SwipeToDismissBox( state: SwipeToDismissBoxState, modifier: Modifier = Modifier, backgroundScrimColor: Color = MaterialTheme.colors.background, contentScrimColor: Color = MaterialTheme.colors.background, backgroundKey: Any = SwipeToDismissKeys.Background, contentKey: Any = SwipeToDismissKeys.Content, hasBackground: Boolean = true, content: @Composable BoxScope.(isBackground: Boolean) -> Unit ) { CompositionLocalProvider( LocalSwipeToDismissBackgroundScrimColor provides backgroundScrimColor, LocalSwipeToDismissContentScrimColor provides contentScrimColor ) { androidx.wear.compose.foundation.SwipeToDismissBox( state = state.foundationState, modifier = modifier, backgroundKey = backgroundKey, contentKey = contentKey, userSwipeEnabled = hasBackground, content = content ) } } /** * Wear Material [SwipeToDismissBox] that handles the swipe-to-dismiss gesture. * This overload takes an [onDismissed] parameter which is used to execute a command when the * swipe to dismiss has completed, such as navigating to another screen. * * Example of a simple SwipeToDismissBox: * @sample androidx.wear.compose.material.samples.SimpleSwipeToDismissBox * * Example of using [Modifier.edgeSwipeToDismiss] with [SwipeToDismissBox] * @sample androidx.wear.compose.material.samples.EdgeSwipeForSwipeToDismiss * * For more information, see the * [Swipe to dismiss](https://developer.android.com/training/wearables/components/swipe-to-dismiss) * guide. * * @param onDismissed Executes when the swipe to dismiss has completed. * @param modifier Optional [Modifier] for this component. * @param state State containing information about ongoing swipe or animation. * @param backgroundScrimColor Color for background scrim * @param contentScrimColor Optional [Color] used for the scrim over the * content composable during the swipe gesture. * @param backgroundKey Optional [key] which identifies the content currently composed in * the [content] block when isBackground == true. Provide the backgroundKey if your background * content will be displayed as a foreground after the swipe animation ends * (as is common when [SwipeToDismissBox] is used for the navigation). This allows * remembered state to be correctly moved between background and foreground. * @Param contentKey Optional [key] which identifies the content currently composed in the * [content] block when isBackground == false. See [backgroundKey]. * @Param hasBackground Optional [Boolean] used to indicate if the content has no background, * in which case the swipe gesture is disabled (since there is no parent destination). * @param content Slot for content, with the isBackground parameter enabling content to be * displayed behind the foreground content - the background is normally hidden, * is shown behind a scrim during the swipe gesture, * and is shown without scrim once the finger passes the swipe-to-dismiss threshold. */ @Composable public fun SwipeToDismissBox( onDismissed: () -> Unit, modifier: Modifier = Modifier, state: androidx.wear.compose.foundation.SwipeToDismissBoxState = androidx.wear.compose.foundation.rememberSwipeToDismissBoxState(), backgroundScrimColor: Color = MaterialTheme.colors.background, contentScrimColor: Color = MaterialTheme.colors.background, backgroundKey: Any = SwipeToDismissKeys.Background, contentKey: Any = SwipeToDismissKeys.Content, hasBackground: Boolean = true, content: @Composable BoxScope.(isBackground: Boolean) -> Unit ) { CompositionLocalProvider( LocalSwipeToDismissBackgroundScrimColor provides backgroundScrimColor, LocalSwipeToDismissContentScrimColor provides contentScrimColor ) { androidx.wear.compose.foundation.SwipeToDismissBox( state = state, modifier = modifier, onDismissed = onDismissed, backgroundKey = backgroundKey, contentKey = contentKey, userSwipeEnabled = hasBackground, content = content ) } } /** * Wear Material [SwipeToDismissBox] that handles the swipe-to-dismiss gesture. * This overload takes an [onDismissed] parameter which is used to execute a command when the * swipe to dismiss has completed, such as navigating to another screen. * * Example of a simple SwipeToDismissBox: * @sample androidx.wear.compose.material.samples.SimpleSwipeToDismissBox * * Example of using [Modifier.edgeSwipeToDismiss] with [SwipeToDismissBox] * @sample androidx.wear.compose.material.samples.EdgeSwipeForSwipeToDismiss * * For more information, see the * [Swipe to dismiss](https://developer.android.com/training/wearables/components/swipe-to-dismiss) * guide. * * @param onDismissed Executes when the swipe to dismiss has completed. * @param modifier Optional [Modifier] for this component. * @param state State containing information about ongoing swipe or animation. * @param backgroundScrimColor Color for background scrim * @param contentScrimColor Optional [Color] used for the scrim over the * content composable during the swipe gesture. * @param backgroundKey Optional [key] which identifies the content currently composed in * the [content] block when isBackground == true. Provide the backgroundKey if your background * content will be displayed as a foreground after the swipe animation ends * (as is common when [SwipeToDismissBox] is used for the navigation). This allows * remembered state to be correctly moved between background and foreground. * @Param contentKey Optional [key] which identifies the content currently composed in the * [content] block when isBackground == false. See [backgroundKey]. * @Param hasBackground Optional [Boolean] used to indicate if the content has no background, * in which case the swipe gesture is disabled (since there is no parent destination). * @param content Slot for content, with the isBackground parameter enabling content to be * displayed behind the foreground content - the background is normally hidden, * is shown behind a scrim during the swipe gesture, * and is shown without scrim once the finger passes the swipe-to-dismiss threshold. */ @Suppress("DEPRECATION") @Deprecated( "This overload is provided for backwards compatibility. " + "A newer overload is available that uses " + "androidx.wear.compose.foundation.SwipeToDismissBoxState.", replaceWith = ReplaceWith("SwipeToDismissBox(" + "onDismiss, modifier, state, backgroundScrimColor, contentScrimColor, backgroundKey," + "contentKey, hasBackground, content)" ), level = DeprecationLevel.HIDDEN ) @Composable public fun SwipeToDismissBox( onDismissed: () -> Unit, modifier: Modifier = Modifier, state: SwipeToDismissBoxState = rememberSwipeToDismissBoxState(), backgroundScrimColor: Color = MaterialTheme.colors.background, contentScrimColor: Color = MaterialTheme.colors.background, backgroundKey: Any = SwipeToDismissKeys.Background, contentKey: Any = SwipeToDismissKeys.Content, hasBackground: Boolean = true, content: @Composable BoxScope.(isBackground: Boolean) -> Unit ) { CompositionLocalProvider( LocalSwipeToDismissBackgroundScrimColor provides backgroundScrimColor, LocalSwipeToDismissContentScrimColor provides contentScrimColor ) { androidx.wear.compose.foundation.SwipeToDismissBox( state = state.foundationState, modifier = modifier, onDismissed = onDismissed, backgroundKey = backgroundKey, contentKey = contentKey, userSwipeEnabled = hasBackground, content = content ) } } /** * State for [SwipeToDismissBox]. * * @param animationSpec The default animation that will be used to animate to a new state. * @param confirmStateChange Optional callback invoked to confirm or veto a pending state change. */ @Suppress("DEPRECATION") @Deprecated( "SwipeToDismissBoxState has been migrated, please import it " + "from androidx.wear.compose.foundation.", ) @Stable public class SwipeToDismissBoxState( animationSpec: AnimationSpec<Float> = SwipeToDismissBoxDefaults.AnimationSpec, confirmStateChange: (SwipeToDismissValue) -> Boolean = { true }, ) { /** * The current value of the state. * * Before and during a swipe, corresponds to [SwipeToDismissValue.Default], then switches to * [SwipeToDismissValue.Dismissed] if the swipe has been completed. */ public val currentValue: SwipeToDismissValue get() = convertFromFoundationSwipeToDismissValue(foundationState.currentValue) /** * The target value of the state. * * If a swipe is in progress, this is the value that the state would animate to if the * swipe finished. If an animation is running, this is the target value of that animation. * Finally, if no swipe or animation is in progress, this is the same as the [currentValue]. */ public val targetValue: SwipeToDismissValue get() = convertFromFoundationSwipeToDismissValue(foundationState.targetValue) /** * Whether the state is currently animating. */ public val isAnimationRunning: Boolean get() = foundationState.isAnimationRunning /** * Set the state without any animation and suspend until it's set * * @param targetValue The new target value to set [currentValue] to. */ public suspend fun snapTo(targetValue: SwipeToDismissValue) = foundationState.snapTo(convertToFoundationSwipeToDismissValue(targetValue)) /** * Foundation version of the [SwipeToDismissBoxState]. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) val foundationState = androidx.wear.compose.foundation.SwipeToDismissBoxState( animationSpec = animationSpec, confirmStateChange = { value: androidx.wear.compose.foundation.SwipeToDismissValue -> confirmStateChange(convertFromFoundationSwipeToDismissValue(value)) } ) @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) get() = field } /** * Create a [SwipeToDismissBoxState] and remember it. * * @param animationSpec The default animation used to animate to a new state. * @param confirmStateChange Optional callback to confirm or veto a pending state change. */ @Suppress("DEPRECATION") @Deprecated( "Please import rememberSwipeToDismissBoxState from androidx.wear.compose.foundation.", ReplaceWith( "androidx.wear.compose.foundation.rememberSwipeToDismissBoxState(", "animationSpec, confirmStateChange)" ) ) @Composable public fun rememberSwipeToDismissBoxState( animationSpec: AnimationSpec<Float> = SWIPE_TO_DISMISS_BOX_ANIMATION_SPEC, confirmStateChange: (SwipeToDismissValue) -> Boolean = { true }, ): SwipeToDismissBoxState { return remember(animationSpec, confirmStateChange) { SwipeToDismissBoxState(animationSpec, confirmStateChange) } } /** * Contains defaults for [SwipeToDismissBox]. */ public object SwipeToDismissBoxDefaults { /** * The default animation that will be used to animate to a new state after the swipe gesture. */ @OptIn(ExperimentalWearMaterialApi::class) public val AnimationSpec = SwipeableDefaults.AnimationSpec /** * The default width of the area which might trigger a swipe * with [edgeSwipeToDismiss] modifier */ public val EdgeWidth = 30.dp } /** * Keys used to persistent state in [SwipeToDismissBox]. */ public enum class SwipeToDismissKeys { /** * The default background key to identify the content displayed by the content block * when isBackground == true. Specifying a background key instead of using the default * allows remembered state to be correctly moved between background and foreground. */ Background, /** * The default content key to identify the content displayed by the content block * when isBackground == false. Specifying a background key instead of using the default * allows remembered state to be correctly moved between background and foreground. */ Content } /** * States used as targets for the anchor points for swipe-to-dismiss. */ @Deprecated( "SwipeToDismiss has been migrated to androidx.wear.compose.foundation. " + "Please import SwipeToDismissValue from androidx.wear.compose.foundation instead.", ) public enum class SwipeToDismissValue { /** * The state of the SwipeToDismissBox before the swipe started. */ Default, /** * The state of the SwipeToDismissBox after the swipe passes the swipe-to-dismiss threshold. */ Dismissed } /** * Limits swipe to dismiss to be active from the edge of the viewport only. Used when the center * of the screen needs to be able to handle horizontal paging, such as 2-d scrolling a Map * or swiping horizontally between pages. Swipe to the right is intercepted on the left * part of the viewport with width specified by [edgeWidth], with other touch events * ignored - vertical scroll, click, long click, etc. * * Currently Edge swipe, like swipe to dismiss, is only supported on the left part of the viewport * regardless of layout direction as content is swiped away from left to right. * * Requires that the element to which this modifier is applied exists within a * SwipeToDismissBox which is using the same [SwipeToDismissBoxState] instance. * * Example of a modifier usage with SwipeToDismiss * @sample androidx.wear.compose.material.samples.EdgeSwipeForSwipeToDismiss * * @param swipeToDismissBoxState A state of SwipeToDismissBox. Used to trigger swipe gestures * on SwipeToDismissBox * @param edgeWidth A width of edge, where swipe should be recognised */ @Suppress("DEPRECATION") @Deprecated( "SwipeToDismiss has been migrated to androidx.wear.compose.foundation. " + "Please import Modifier.edgeSwipeToDismiss from androidx.wear.compose.foundation instead.", replaceWith = ReplaceWith( "androidx.wear.compose.foundation.edgeSwipeToDismiss(", "swipeToDismissBoxState, edgeWidth)" ) ) public fun Modifier.edgeSwipeToDismiss( swipeToDismissBoxState: SwipeToDismissBoxState, edgeWidth: Dp = SwipeToDismissBoxDefaults.EdgeWidth ): Modifier = foundationEdgeSwipeToDismiss( swipeToDismissBoxState = swipeToDismissBoxState.foundationState, edgeWidth = edgeWidth ) @Suppress("DEPRECATION") private fun convertToFoundationSwipeToDismissValue( value: SwipeToDismissValue ) = when (value) { SwipeToDismissValue.Default -> androidx.wear.compose.foundation.SwipeToDismissValue.Default SwipeToDismissValue.Dismissed -> androidx.wear.compose.foundation.SwipeToDismissValue.Dismissed } @Suppress("DEPRECATION") private fun convertFromFoundationSwipeToDismissValue( value: androidx.wear.compose.foundation.SwipeToDismissValue ) = when (value) { androidx.wear.compose.foundation.SwipeToDismissValue.Default -> SwipeToDismissValue.Default androidx.wear.compose.foundation.SwipeToDismissValue.Dismissed -> SwipeToDismissValue.Dismissed } private val SWIPE_TO_DISMISS_BOX_ANIMATION_SPEC = TweenSpec<Float>(200, 0, LinearOutSlowInEasing)
28
null
937
5,108
89ec14e39cf771106a8719337062572717cbad31
22,434
androidx
Apache License 2.0
app/src/main/java/com/cerminnovations/moviesboard/ui/adapter/AllSeriesAdapter.kt
mbobiosio
324,425,383
false
null
package com.cerminnovations.moviesboard.ui.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.cerminnovations.moviesboard.databinding.ItemSeriesBinding import com.cerminnovations.moviesboard.model.shows.Series class AllSeriesAdapter( val listener: (Series) -> Unit ) : PagingDataAdapter<Series, AllSeriesAdapter.AllSeriesVH>(ListItemCallback()) { private class ListItemCallback : DiffUtil.ItemCallback<Series>() { override fun areItemsTheSame(oldItem: Series, newItem: Series): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: Series, newItem: Series): Boolean { return oldItem == newItem } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AllSeriesVH { val binding = ItemSeriesBinding.inflate(LayoutInflater.from(parent.context), parent, false) return AllSeriesVH(binding) } override fun onBindViewHolder(holder: AllSeriesVH, position: Int) { getItem(position)?.let { holder.bind(it) } } inner class AllSeriesVH(private val binding: ItemSeriesBinding) : RecyclerView.ViewHolder(binding.root) { fun bind( series: Series ) = with(itemView) { binding.series = series binding.executePendingBindings() setOnClickListener { listener.invoke(series) } } } }
0
Kotlin
2
1
32754fbb6c107ee48e8a9f06d80b4187e3a55073
1,626
MoviesBoard
MIT License
app/src/main/java/com/vinicius/githubapi/data/network/UsersResponse.kt
KhomDrake
471,202,847
false
{"Kotlin": 122985}
package com.vinicius.githubapi.data.network import com.google.gson.annotations.SerializedName class UsersResponse( @SerializedName("items") val users: List<UserResponse>, @SerializedName("total_count") val totalCount: Int ) class UserResponse( val login: String, val id: Int, @SerializedName("avatar_url") val avatarUrl: String, @SerializedName("html_url") val url: String, val type: String )
0
Kotlin
0
0
54ff30b6598f469be66ef2cbbfe7eff815114d5f
439
android-exercises
X.Net License
skrapers/src/main/kotlin/ru/sokomishalov/skraper/provider/vk/VkSkraper.kt
edwinRNDR
266,203,781
true
{"Kotlin": 272787, "Shell": 41, "Batchfile": 33}
/** * Copyright (c) 2019-present Mikhael Sokolov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("RemoveExplicitTypeArguments", "MoveVariableDeclarationIntoWhen") package ru.sokomishalov.skraper.provider.vk import org.jsoup.nodes.Document import org.jsoup.nodes.Element import ru.sokomishalov.skraper.Skraper import ru.sokomishalov.skraper.SkraperClient import ru.sokomishalov.skraper.client.jdk.DefaultBlockingSkraperClient import ru.sokomishalov.skraper.fetchDocument import ru.sokomishalov.skraper.internal.jsoup.* import ru.sokomishalov.skraper.model.* import java.time.LocalDate import java.time.LocalTime import java.time.ZoneId import java.time.format.DateTimeFormatterBuilder import java.util.Locale.ENGLISH /** * @author sokomishalov */ open class VkSkraper @JvmOverloads constructor( override val client: SkraperClient = DefaultBlockingSkraperClient, override val baseUrl: URLString = "https://vk.com" ) : Skraper { override suspend fun getPosts(path: String, limit: Int): List<Post> { val page = getUserPage(path = path) val posts = page ?.getElementsByClass("wall_item") ?.take(limit) .orEmpty() return posts.map { with(it) { Post( id = extractPostId(), text = extractPostCaption(), publishedAt = extractPostPublishedDate(), rating = extractPostLikes(), commentsCount = extractPostReplies(), viewsCount = extractViewsCount(), media = extractPostMediaItems() ) } } } override suspend fun getPageInfo(path: String): PageInfo? { val page = getUserPage(path = path) return page?.run { PageInfo( nick = extractPageNick(), name = extractPageName(), description = extractDescription(), followersCount = extractFollowersCount(), postsCount = extractPostsCount(), avatarsMap = extractPageAvatarsMap(), coversMap = extractPageCoversMap() ) } } override suspend fun resolve(media: Media): Media { return when (media) { is Video -> { val page = client.fetchDocument( url = media.url, headers = emptyMap() ) val video = page?.getFirstElementByTag("video") media.copy( url = video ?.getElementsByTag("source") ?.lastOrNull() ?.attr("src") ?: media.url, thumbnail = video ?.attr("poster") ?.toImage() ?: media.thumbnail ) } is Image -> { val page = client.fetchDocument( url = media.url, headers = emptyMap() ) val url = page ?.getFirstElementByClass("PhotoviewPage__photo") ?.getFirstElementByTag("img") ?.attr("src") media.copy( url = url ?: media.url ) } else -> { media } } } private suspend fun getUserPage(path: String): Document? { return client.fetchDocument( url = baseUrl.buildFullURL(path = path), headers = mapOf("Accept-Language" to "en-US") ) } private fun Element.extractPostId(): String { return getElementsByAttribute("data-post-id") .attr("data-post-id") .substringAfter("_") } private fun Element.extractPostCaption(): String? { return getFirstElementByClass("pi_text") ?.wholeText() } private fun Element.extractPostPublishedDate(): Long? { return getFirstElementByClass("wi_date") ?.wholeText() ?.run { val localDate = runCatching { when { startsWith("today at ") -> { removePrefix("today at ") .let { LocalTime.parse(it.toUpperCase(), VK_SHORT_TIME_AGO_DATE_FORMATTER) } .let { LocalDate .now() .atTime(it) .atZone(ZoneId.systemDefault()) } } startsWith("yesterday at ") -> { removePrefix("yesterday at ") .let { LocalTime.parse(it.toUpperCase(), VK_SHORT_TIME_AGO_DATE_FORMATTER) } .let { LocalDate .now() .minusDays(1) .atTime(it) .atZone(ZoneId.systemDefault()) } } else -> { LocalDate .parse(this, VK_LONG_TIME_AGO_DATE_FORMATTER) .atTime(LocalTime.NOON) .atZone(ZoneId.systemDefault()) } } }.getOrNull() return localDate?.toEpochSecond() } } private fun Element.extractPostLikes(): Int? { return getFirstElementByClass("v_like") ?.wholeText() ?.toIntOrNull() } private fun Element.extractPostReplies(): Int? { return getFirstElementByClass("v_replies") ?.wholeText() ?.toIntOrNull() } private fun Element.extractViewsCount(): Int? { return getFirstElementByClass("item_views") ?.attr("aria-label") ?.replace("views", "") ?.trim() ?.toIntOrNull() } private fun Element.extractPostMediaItems(): List<Media> { val thumbElement = getFirstElementByClass("thumbs_map_helper") val aspectRatio = thumbElement ?.getStyle("padding-top") ?.removeSuffix("%") ?.toDoubleOrNull() ?.run { 100 / this } return thumbElement ?.getElementsByTag("a") ?.mapNotNull { with(it) { val isVideo = attr("href").startsWith("/video") val hrefLink = "${baseUrl}${attr("href")}" when { isVideo -> Video( url = hrefLink, aspectRatio = aspectRatio ) else -> Image( url = getFirstElementByClass("thumb_map_img") ?.getBackgroundImageStyle() ?: hrefLink, aspectRatio = aspectRatio ) } } } .orEmpty() } private fun Document.extractPageNick(): String? { return getFirstElementByAttributeValue("rel", "canonical") ?.attr("href") ?.substringAfterLast("/") } private fun Document.extractPageName(): String? { return getFirstElementByClass("op_header") ?.wholeText() } private fun Document.extractDescription(): String? { return getFirstElementByClass("pp_status") ?.wholeText() } private fun Document.extractFollowersCount(): Int? { return getElementsByClass("pm_item") .map { it.wholeText() } .find { "Followers" in it } ?.replace("Followers", "") ?.replace(",", "") ?.trim() ?.toIntOrNull() } private fun Document.extractPostsCount(): Int? { return getFirstElementByClass("slim_header_label") ?.wholeText() ?.replace("posts", "") ?.replace(",", "") ?.trim() ?.toIntOrNull() } private fun Document.extractPageCoversMap(): Map<MediaSize, Image> { return singleImageMap(url = this .getFirstElementByClass("groupCover__image") ?.getBackgroundImageStyle() ) } private fun Document.extractPageAvatarsMap(): Map<MediaSize, Image> { return singleImageMap(url = this .getFirstElementByClass("profile_panel") ?.getFirstElementByTag("img") ?.attr("src") ) } companion object { private val VK_SHORT_TIME_AGO_DATE_FORMATTER = DateTimeFormatterBuilder() .appendPattern("h:mm a") .parseLenient() .toFormatter(ENGLISH) private val VK_LONG_TIME_AGO_DATE_FORMATTER = DateTimeFormatterBuilder() .appendPattern("d MMM yyyy") .parseLenient() .toFormatter(ENGLISH) } }
0
Kotlin
0
0
dc0c806e653fb0c346ee6f75b7d1281917bf30bf
10,793
skraper
Apache License 2.0
library-res/src/main/kotlin/com/wsdydeni/library_view/loadingdialog/LoadingDialog.kt
wsdydeni
294,493,450
false
null
package com.wsdydeni.library_view.loadingdialog import android.app.Dialog import android.content.Context import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.constraintlayout.widget.ConstraintLayout import com.wsdydeni.library_res.R /* * Create by wsdydeni on 2020/10/4 15:24 */ class LoadingDialog(context: Context) { private var mContext: Context? = null private var mDialog: Dialog? = null private var mLoadingCircleView: LoadingCircleView private var mLoadingText: TextView private var isCanBack = false init { mContext = context val view = LayoutInflater.from(mContext).inflate(R.layout.layout_loading_dialog_view,null) mLoadingCircleView = view.findViewById(R.id.dialog_loading_view) mLoadingText = view.findViewById(R.id.dialog_loading_text) initView(view) } private fun initView(view: View) { mDialog = object : Dialog(mContext!!,R.style.Dialog_Fullscreen) { override fun onBackPressed() { if(!isCanBack) return } } mDialog?.setCancelable(isCanBack) mDialog?.setContentView(view.findViewById(R.id.dialog_loading_layout) as ConstraintLayout, ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT,ConstraintLayout.LayoutParams.MATCH_PARENT)) } fun setLoadingStatusListener(listener: LoadingStatusListener) { mLoadingCircleView.setLoadingStatusListener(listener) } fun show(text: String) { mLoadingCircleView.loadLoading() mLoadingText.text = text mDialog?.show() } fun success(text: String) { mLoadingCircleView.loadSuccess() mLoadingText.text = text } fun failure(text: String) { mLoadingCircleView.loadFailure() mLoadingText.text = text } fun close() { mLoadingCircleView.stopAllAnimator() mDialog?.dismiss() } fun clear() { mContext = null } }
1
null
1
5
e908db6bcf7cefa43500cc334c07c0bcc655819a
2,038
WanAndroid
MIT License
app/src/main/java/com/commov/ui/note/NoteAdapter.kt
palexandrefernandes
241,940,599
false
null
package com.commov.ui.note import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.os.bundleOf import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.commov.data.note.DatabaseHelper import com.commov.data.note.Note import com.commov.R class NoteAdapter(private var data : ArrayList<Note>): RecyclerView.Adapter<ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val view = layoutInflater.inflate(R.layout.note, parent, false) as View return ViewHolder(view) } override fun getItemCount(): Int { return this.data.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.updateContent(this.data[position]) holder.onDeleteClickListen { if(DatabaseHelper(it.context).deleteNote(this.data[position])) { this.data.removeAt(position); this.notifyDataSetChanged(); } } holder.onEditClickListen { val send = bundleOf("note" to this.data[position]) it.findNavController().navigate(R.id.noteEditorFragment, send) } } }
0
Kotlin
0
0
b60b0f82a7148b161740d4439da811fa60063973
1,320
Android-Maps-Note-App
MIT License
hubdle-gradle-plugin/main/kotlin/com/javiersc/hubdle/extensions/shared/features/gradle/HubdleGradleVersionCatalogFeatureExtension.kt
JavierSegoviaCordoba
348,863,451
false
null
package com.javiersc.hubdle.extensions.shared.features.gradle import com.javiersc.hubdle.extensions.HubdleDslMarker import com.javiersc.hubdle.extensions._internal.ApplicablePlugin.Scope import com.javiersc.hubdle.extensions._internal.Configurable.Priority import com.javiersc.hubdle.extensions._internal.PluginId import com.javiersc.hubdle.extensions._internal.getHubdleExtension import com.javiersc.hubdle.extensions.apis.BaseHubdleDelegateExtension import com.javiersc.hubdle.extensions.apis.HubdleConfigurableExtension import com.javiersc.hubdle.extensions.apis.HubdleEnableableExtension import com.javiersc.hubdle.extensions.apis.enableAndExecute import com.javiersc.hubdle.extensions.config.publishing._internal.configurableMavenPublishing import com.javiersc.hubdle.extensions.kotlin.hubdleKotlin import java.io.File import javax.inject.Inject import org.gradle.api.Action import org.gradle.api.Project import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.plugins.catalog.CatalogPluginExtension import org.gradle.api.provider.Property import org.gradle.kotlin.dsl.configure public open class HubdleGradleVersionCatalogFeatureExtension @Inject constructor( project: Project, ) : HubdleConfigurableExtension(project) { override val isEnabled: Property<Boolean> = property { false } override val requiredExtensions: Set<HubdleEnableableExtension> get() = setOf(hubdleKotlin) override val priority: Priority = Priority.P3 public val catalogs: ConfigurableFileCollection = project.files(emptyList<File>()) @HubdleDslMarker public fun catalogs(vararg files: File) { catalogs.setFrom(files) } override fun Project.defaultConfiguration() { applicablePlugin( priority = Priority.P3, scope = Scope.CurrentProject, PluginId.GradleVersionCatalog, ) configurable { configure<CatalogPluginExtension> { versionCatalog { catalog -> catalog.from(catalogs) } } } configurableMavenPublishing(mavenPublicationName = "versionCatalog") } } public interface HubdleGradleVersionCatalogDelegateFeatureExtension : BaseHubdleDelegateExtension { public val versionCatalog: HubdleGradleVersionCatalogFeatureExtension get() = project.getHubdleExtension() @HubdleDslMarker public fun versionCatalog( action: Action<HubdleGradleVersionCatalogFeatureExtension> = Action {} ) { versionCatalog.enableAndExecute(action) } } internal val HubdleEnableableExtension.hubdleGradleVersionCatalog: HubdleGradleVersionCatalogFeatureExtension get() = getHubdleExtension()
14
Kotlin
8
16
ca21470528b8f62b91c2f16e14d8ef62b39bf3b9
2,695
hubdle
Apache License 2.0
app/src/main/java/com/jonathanlee/popcorn/data/compose/MockData.kt
jonathanlee06
403,033,324
false
null
package com.jonathanlee.popcorn.data.compose import com.jonathanlee.popcorn.data.model.network.SearchModel val searchModel = SearchModel( id = 603692, originalLanguage = "en", originalTitle = "<NAME>: Chapter 4", overview = "With the price on his head ever increasing, <NAME> uncovers a path to defeating The High Table. But before he can earn his freedom, Wick must face off against a new enemy with powerful alliances across the globe and forces that turn old friends into foes.", popularity = 1698.338F, adult = false, backdropPath = "/h8gHn0OzBoaefsYseUByqsmEDMY.jpg", genreIds = listOf(28, 53, 80), posterPath = "/vZloFAK7NmvMGKE7VkF5UHaz0I.jpg", title = "<NAME>: Chapter 4", video = false, voteAverage = 7.997F, voteCount = 1012, knownFor = emptyList(), originalName = null, originCountry = emptyList() ) val searchList = listOf(searchModel, searchModel, searchModel)
0
Kotlin
0
4
78c7a80150a475ff3e5715abc75ee34b613347bc
940
Popcorn
Apache License 2.0
examples/nft/collection/getASingleCollection/main.kt
GWT-M3O-TEST
485,009,715
false
null
package examples.nft.collection import com.m3o.m3okotlin.M3O import com.m3o.m3okotlin.services.nft suspend fun main() { M3O.initialize(System.getenv("M3O_API_TOKEN")) val req = NftCollectionRequest(Slug = "doodles-official",) try { val response = NftServ.collection(req) println(response) } catch (e: Exception) { println(e) } }
1
Kotlin
1
0
54158b584ba47bd7323a484804dcd78c55ef7f69
364
m3o-kotlin
Apache License 2.0
ktfx-thirdparty/controlsfx/src/ktfx/controlsfx/control/HiddenSidesPane.kt
alilosoft
182,138,993
true
{"Kotlin": 364065, "HTML": 1385, "Java": 682}
@file:Suppress("PackageDirectoryMismatch", "NOTHING_TO_INLINE", "ClassName") package ktfx.controlsfx import javafx.scene.Node import ktfx.layouts.LayoutDslMarker import ktfx.layouts.NodeManager import org.controlsfx.control.HiddenSidesPane /** * Invoking layout DSL will only set content. * To set other sides, explicitly use `top`, `left`, `bottom`, or `right`. */ open class _HiddenSidesPane : HiddenSidesPane(), NodeManager { override fun <R : Node> R.add(): R = also { content = it } } /** Creates a [HiddenSidesPane]. */ fun hiddenSidesPane( init: ((@LayoutDslMarker _HiddenSidesPane).() -> Unit)? = null ): HiddenSidesPane = _HiddenSidesPane().also { init?.invoke(it) } /** Creates a [HiddenSidesPane] and add it to this manager. */ inline fun NodeManager.hiddenSidesPane( noinline init: ((@LayoutDslMarker _HiddenSidesPane).() -> Unit)? = null ): HiddenSidesPane = ktfx.controlsfx.hiddenSidesPane(init).add()
0
Kotlin
0
0
f499c9d7abddb270f1946c0e9ffb9072e45cd625
936
ktfx
Apache License 2.0
home/src/main/java/com/kingsland/home/domain/repository/IProjectRepository.kt
data-programmer
599,861,493
false
null
package com.kingsland.home.domain.repository import com.kingsland.home.domain.model.ProjectDomain interface IProjectRepository { fun getAllProjects(): List<ProjectDomain> }
0
Kotlin
0
0
bcd53b9784689e5b60d893248ccc2910b17391e0
178
ProjectTrakAndroid
MIT License
app/src/main/java/com/stocksexchange/android/ui/dashboard/DashboardPresenter.kt
libertaria-project
183,030,087
true
{"Kotlin": 2210140}
package com.stocksexchange.android.ui.dashboard import com.stocksexchange.android.Constants import com.stocksexchange.android.R import com.stocksexchange.android.api.model.User import com.stocksexchange.android.events.SettingsEvent import com.stocksexchange.android.events.UserEvent import com.stocksexchange.android.ui.base.mvp.model.StubModel import com.stocksexchange.android.ui.base.mvp.presenters.BaseViewPagerPresenter import com.stocksexchange.android.utils.providers.BooleanProvider import com.stocksexchange.android.utils.providers.StringProvider import org.greenrobot.eventbus.Subscribe import org.greenrobot.eventbus.ThreadMode import org.koin.standalone.inject class DashboardPresenter( model: StubModel, view: DashboardContract.View ) : BaseViewPagerPresenter<StubModel, DashboardContract.View>(model, view), DashboardContract.ActionListener { private val mBooleanProvider: BooleanProvider by inject() private val mStringProvider: StringProvider by inject() constructor(view: DashboardContract.View): this(StubModel(), view) override fun onFavoritesButtonClicked() { mView.launchFavoriteCurrencyMarketsActivity() } override fun onSearchButtonClicked() { mView.launchSearchActivity() } override fun onSignInButtonClicked() { mView.launchSignInActivity() } override fun onDrawerHeaderClicked(user: User?) { if(user == null) { return } mView.launchSettingsActivity() } override fun onWalletsClicked() { mView.launchWalletsActivity() } override fun onOrdersClicked() { mView.launchOrdersActivity() } override fun onDepositsClicked() { mView.launchDepositsActivity() } override fun onWithdrawalsClicked() { mView.launchWithdrawalsActivity() } override fun onSettingsClicked() { mView.launchSettingsActivity() } override fun onAboutClicked() { mView.launchAboutActivity() } override fun onFeedbackClicked() { mView.launchFeedbackActivity() } override fun onHelpClicked() { mView.launchHelpActivity() } override fun onShareTheAppClicked() { mView.shareText( mStringProvider.getString( R.string.app_sharing_template, Constants.PLAY_STORE_APP_REFERENCE ), mStringProvider.getString(R.string.action_share_via) ) } override fun onTabReselected(position: Int) { super.onTabReselected(position) mView.showAppBar(true) } override fun onBackPressed(): Boolean { return if(shouldCloseDrawer()) { mView.closeDrawer() true } else { false } } private fun shouldCloseDrawer(): Boolean { return ((!(mBooleanProvider.getBoolean(R.bool.isTablet) && mView.isLandscape())) && mView.isDrawerOpen()) } @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) fun onEvent(event: SettingsEvent) { if(event.isOriginatedFrom(this) || event.isConsumed) { return } when(event.action) { SettingsEvent.Actions.THEME_CHANGED, SettingsEvent.Actions.DEFAULTS_RESTORED, SettingsEvent.Actions.GROUPING_STATE_CHANGED, SettingsEvent.Actions.GROUPING_SEPARATOR_CHANGED, SettingsEvent.Actions.DECIMAL_SEPARATOR_CHANGED -> { mView.restartActivity() } } event.consume() } @Subscribe(sticky = true, threadMode = ThreadMode.MAIN) fun onEvent(event: UserEvent) { if(event.isOriginatedFrom(this) || event.isConsumed) { return } when(event.action) { UserEvent.Actions.SIGNED_IN, UserEvent.Actions.SIGNED_OUT -> { mView.restartActivity() } } event.consume() } override fun canReceiveEvents(): Boolean { return true } }
0
Kotlin
0
0
35a7f9a61f52f68ab3267da24da3c1d77d84e9c3
4,048
Android-app
MIT License
src/main/java/framework/physics/collisions/Collision.kt
HansDampf37
238,090,617
false
{"Kotlin": 178799}
package framework.physics.collisions import framework.interfaces.Mass import framework.interfaces.Status import kotlin.math.pow /** * Use [Collision.occur] to calculate the new velocities after the collision and the amount of energy transmitted. */ class Collision { companion object{ /** * Simulates the (inelastic) collision of two masses with k being the coefficient of restitution. * **See** [wikipedia](https://en.wikipedia.org/wiki/Inelastic_collision) * @param mass1 the first [Mass] * @param mass2 the second [Mass] * @param k the coefficient of restitution * @return energy transmitted in the collision */ fun occur(mass1: Mass, mass2: Mass, k: Double = 1.0): Double { val dir = mass2.position - mass1.position if (dir.length == 0.0) return 0.0 val v1 = mass1.velocity.projectOnto(dir) val v2 = mass2.velocity.projectOnto(dir) val v1O = mass1.velocity - v1 val v2O = mass2.velocity - v2 if (listOf(mass1, mass2).all { it.status == Status.Movable }) { val m1: Double = mass1.mass val m2: Double = mass2.mass val v1New = (v1 * m1 + v2 * m2 - (v1 - v2) * m2 * k) / (m1 + m2) val v2New = (v1 * m1 + v2 * m2 - (v2 - v1) * m1 * k) / (m1 + m2) mass1.velocity = v1New + v1O mass2.velocity = v2New + v2O return m1 * m2 / (2 * m1 + 2 * m2) * (v1.length - v2.length).pow(2) * (1-k.pow(2)) } else if (mass1.status == Status.Immovable && mass2.status == Status.Movable) { // if mass 1 is not movable treat it like its mass is infinity mass2.velocity = v1 + (v1 - v2) * k + v2O return (k-1).pow(2)/2 * mass1.mass * (v1.length - v2.length).pow(2) } else if (mass1.status == Status.Movable && mass2.status == Status.Immovable) { // if mass 2 is not movable treat it like its mass is infinity mass1.velocity = v2 + (v2 - v1) * k + v1O return (k-1).pow(2)/2 * mass2.mass * (v1.length - v2.length).pow(2) } return 0.0 } } }
0
Kotlin
0
0
4bd52d21d759f96b65dbc81bf15d344feeed8325
2,252
SimulationFramework
MIT License
pillarbox-core-business/src/test/java/ch/srgssr/pillarbox/core/business/integrationlayer/data/MediaUrnTest.kt
SRGSSR
519,157,987
false
{"Kotlin": 1520146, "Shell": 549}
/* * Copyright (c) SRG SSR. All rights reserved. * License information is available from the LICENSE file. */ package ch.srgssr.pillarbox.core.business.integrationlayer.data import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse class MediaUrnTest { @Test fun `is valid media urn`() { urnData.forEach { (urn, isValid) -> assertEquals(isValid, urn.isValidMediaUrn(), "Expected '$urn' to be ${if (isValid) "a valid" else "an invalid"} urn") } } @Test fun `is valid media urn, urn is null`() { val urn: String? = null assertFalse(urn.isValidMediaUrn()) } @Test fun `MediaUrn is valid`() { urnData.forEach { (urn, isValid) -> assertEquals(isValid, MediaUrn.isValid(urn), "Expected '$urn' to be ${if (isValid) "a valid" else "an invalid"} urn") } } private companion object { private val urnData = mapOf( "" to false, " " to false, "Hello guys!" to false, "https://www.rts.ch/media" to false, "https://www.rts.ch/media/urn:rts:video:123345" to false, "urn:rts:channel:tv:1234" to false, "urn:rts:show:tv:1234" to false, "urn:rts:audio:123345" to true, "urn:rts:video:123345" to true, ) } }
15
Kotlin
1
13
2e0ed86b0c3120984ff75298cf4c47d38cd79115
1,366
pillarbox-android
MIT License
src/main/kotlin/com/robotutor/loggingstarter/serializer/DefaultSerializer.kt
IOT-echo-system
768,195,181
false
{"Kotlin": 94913, "Shell": 609, "HTML": 428, "Dockerfile": 130}
package com.robotutor.iot.logging.serializer object DefaultSerializer { fun serialize(obj: Any?): String { return ObjectMapperCache.objectMapper.toJson(obj) } fun <T> deserialize(str: String, type: Class<T>): T { return ObjectMapperCache.objectMapper.fromJson(str, type) } }
0
Kotlin
0
0
bf28073703d3e937b97a5f15d86c7baceb8b5d42
309
logging-starter
MIT License
library/src/main/java/co/zsmb/materialdrawerkt/draweritems/expandable/ExpandableBadgeDrawerItemKt.kt
developersancho
148,280,254
false
null
@file:Suppress("RedundantVisibilityModifier") package co.zsmb.materialdrawerkt.draweritems.expandable import co.zsmb.materialdrawerkt.builders.Builder import co.zsmb.materialdrawerkt.createItem import co.zsmb.materialdrawerkt.draweritems.badgeable.BadgeableKt import co.zsmb.materialdrawerkt.draweritems.base.BaseDescribeableDrawerItemKt import com.mikepenz.materialdrawer.holder.BadgeStyle import com.mikepenz.materialdrawer.holder.StringHolder import com.mikepenz.materialdrawer.model.ExpandableBadgeDrawerItem /** * Adds a new ExpandableBadgeDrawerItem with the given [name] and [description]. * @return The created ExpandableBadgeDrawerItem instance */ public fun Builder.expandableBadgeItem(name: String = "", description: String? = null, setup: ExpandableBadgeDrawerItemKt.() -> Unit = {}): ExpandableBadgeDrawerItem { return createItem(ExpandableBadgeDrawerItemKt(), name, description, setup) } /** * Adds a new ExpandableBadgeDrawerItem with the given [nameRes] and [descriptionRes]. * @return The created ExpandableBadgeDrawerItem instance */ public fun Builder.expandableBadgeItem(nameRes: Int, descriptionRes: Int? = null, setup: ExpandableBadgeDrawerItemKt.() -> Unit = {}): ExpandableBadgeDrawerItem { return createItem(ExpandableBadgeDrawerItemKt(), nameRes, descriptionRes, setup) } public class ExpandableBadgeDrawerItemKt : BaseDescribeableDrawerItemKt<ExpandableBadgeDrawerItem>(ExpandableBadgeDrawerItem()), BadgeableKt { // Documentation inherited override var badgeHolder: StringHolder get() = item.badge set(value) { item.withBadge(value) } // Documentation inherited override var badgeRes: Int get() = item.badge.textRes set(value) { item.withBadge(value) } // Documentation inherited override var badgeStyle: BadgeStyle get() = item.badgeStyle set(value) { item.withBadgeStyle(value) } }
0
Kotlin
0
0
8ec51fa99dfb799e67bc138b87ab73e190091fc9
2,139
MaterialDrawerKt-master
Apache License 2.0
torkit/src/main/kotlin/io/horizontalsystems/tor/core/TorConstants.kt
horizontalsystems
251,509,228
false
null
package com.lyfebloc.core interface TorConstants { companion object { const val TAG = "TorBinary" const val DIRECTORY_TOR_DATA = "data" const val TOR_CONTROL_PORT_FILE = "control.txt" const val LIB_NAME = "tor" const val LIB_SO_NAME = "libtor.so" const val SHELL_CMD_PS = "ps" //geoip data file asset key const val GEOIP_ASSET_KEY = "geoip" const val GEOIP6_ASSET_KEY = "geoip6" //torrc (tor config file) const val TOR_ASSET_KEY = "libtor" const val TORRC_ASSET_KEY = "torrc" const val COMMON_ASSET_KEY = "common/" const val TOR_CONTROL_COOKIE = "control_auth_cookie" const val IP_LOCALHOST = "127.0.0.1" const val TOR_TRANSPROXY_PORT_DEFAULT = "9040" const val TOR_DNS_PORT_DEFAULT = "5400" const val HTTP_PROXY_PORT_DEFAULT = "8118" // like Privoxy! const val SOCKS_PROXY_PORT_DEFAULT = "9050" var FILE_WRITE_BUFFER_SIZE = 1024 fun getIntValue(value: String):Int { try{ return value.toInt() } catch (e: Exception){ return -1 } } } }
1
null
3
8
13750c4b8dff092df3ff9ab602eea747f5c6b007
1,206
tor-kit-android
MIT License
app/src/main/java/io/github/fate_grand_automata/ui/support_img_namer/SupportImageNamer.kt
ArthurKun21
743,056,546
false
{"Kotlin": 1454408}
package io.github.fate_grand_automata.ui.support_img_namer import android.content.Context import android.content.DialogInterface import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import io.github.fate_grand_automata.R import io.github.fate_grand_automata.ui.components.FGATheme import io.github.fate_grand_automata.ui.components.FastScrollLazyColumn import io.github.fate_grand_automata.ui.components.padding import io.github.fate_grand_automata.util.FakedComposeView import io.github.fate_grand_automata.util.StorageProvider import io.github.fate_grand_automata.util.showOverlayDialog import io.github.fate_grand_automata.util.title import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import timber.log.Timber import kotlin.coroutines.resume suspend fun showSupportImageMaker( context: Context, storageProvider: StorageProvider ) = withContext(Dispatchers.Main) { suspendCancellableCoroutine { continuation -> var dialog: DialogInterface? = null val composeView = FakedComposeView(context) { SupportImageMakerScreen( storageProvider = storageProvider, onResponse = { dialog?.dismiss() } ) } dialog = showOverlayDialog(context) { setView(composeView.view) setOnDismissListener { composeView.close() continuation.resume(Unit) } } } } @Composable private fun SupportImageMakerScreen( storageProvider: StorageProvider, onResponse: () -> Unit ) { val entries by remember { derivedStateOf { getSupportEntries(storageProvider) } } val state = rememberLazyListState() FGATheme { Column( modifier = Modifier.fillMaxSize() ) { Text( text = stringResource(id = R.string.p_script_mode_support_image_maker), style = MaterialTheme.typography.titleLarge, modifier = Modifier .padding(horizontal = 16.dp) .padding(bottom = 16.dp, top = 5.dp) ) HorizontalDivider() Box( modifier = Modifier .weight(1f) .clipToBounds(), ) { FastScrollLazyColumn( modifier = Modifier .fillMaxSize(), contentPadding = PaddingValues( vertical = 8.dp ), state = state ) { entries.forEach { support -> if (support.index == 0) { item { Text( text = stringResource(id = support.kind.title), style = MaterialTheme.typography.titleMedium, modifier = Modifier.padding( horizontal = MaterialTheme.padding.small, ) ) } item { HorizontalDivider( modifier = Modifier.padding( vertical = MaterialTheme.padding.extraSmall, horizontal = MaterialTheme.padding.small, ) ) } } if (support.imgExists) { item { support.Entry() } } } } } HorizontalDivider() Row( horizontalArrangement = Arrangement.End, modifier = Modifier.padding( horizontal = MaterialTheme.padding.small, ) ) { Spacer(modifier = Modifier.weight(1f)) TextButton( onClick = { onResponse() } ) { Text( text = stringResource(android.R.string.cancel).uppercase() ) } Spacer( modifier = Modifier .padding(horizontal = MaterialTheme.padding.extraSmall) ) TextButton( onClick = { entries .filter { item -> item.isValid() } .forEach { item -> Timber.d("Renaming ${item.kind} ${item.index}") item.rename(storageProvider) } onResponse() }, enabled = entries .filter { it.checkBoxStatus } .any { it.isValid() } ) { Text( text = stringResource(R.string.save).uppercase() ) } } } } }
22
Kotlin
0
1
049fdfc02c85c0cb2cd4d9507a02e4faa4df7137
6,468
FGA-Preview
MIT License
server/src/main/kotlin/net/eiradir/server/entity/components/MapViewComponent.kt
Eiradir
635,460,745
false
null
package net.eiradir.server.entity.components import com.badlogic.ashley.core.Component import net.eiradir.server.map.view.MapView data class MapViewComponent(val mapView: MapView) : Component
12
Kotlin
0
0
7ae18b87a37ebd9f20766796b9fa94e2dd6dafc6
193
eiradir-server
MIT License
neo4k-api/src/test/kotlin/me/roybailey/neo4k/embedded/EmbeddedStandaloneTest.kt
roybailey
189,282,455
false
null
package me.roybailey.neo4k.embedded import mu.KotlinLogging import org.neo4j.graphdb.GraphDatabaseService import org.neo4j.graphdb.Node import org.neo4j.graphdb.factory.GraphDatabaseFactory import org.neo4j.kernel.configuration.BoltConnector import java.io.File import java.net.InetAddress /** * Direct driver sample code to investigate query/result structure/performance outside the Neo4jService solution */ class Neo4jEmbeddedTest( neo4jUri: String, boltPort: Int = 7988, neo4jConfiguration: String = "/neo4j.conf") { private val logger = KotlinLogging.logger {} lateinit var graphDb: GraphDatabaseService init { val graphDbBuilder = GraphDatabaseFactory() .newEmbeddedDatabaseBuilder(File(neo4jUri)) .loadPropertiesFromURL(Neo4jEmbeddedTest::class.java.getResource((neo4jConfiguration))) if (boltPort > 0) { val bolt = BoltConnector("0") val boltListenAddress = "0.0.0.0:$boltPort" val boltAdvertisedAddress = InetAddress.getLocalHost().hostName + ":" + boltPort graphDbBuilder.setConfig(bolt.type, "BOLT") .setConfig(bolt.enabled, "true") .setConfig(bolt.listen_address, boltListenAddress) .setConfig(bolt.advertised_address, boltAdvertisedAddress) logger.info("Creating Neo4j Bolt Connector on Port : $boltPort") logger.info("Creating Neo4j Bolt Listen Address : $boltListenAddress") logger.info("Creating Neo4j Bolt Advertised Address : $boltAdvertisedAddress") } try { graphDb = graphDbBuilder.newGraphDatabase() } catch (err: Exception) { logger.error("########### ########## ########## ########## ##########") logger.error("!!!!!!!!!! Error creating Neo4j Database !!!!!!!!!!") logger.error("Error creating Neo4j Database", err) logger.error("########### ########## ########## ########## ##########") System.exit(-1) } val cypher = Neo4jEmbeddedTest::class.java.getResource("/cypher/create-movies.cypher").readText() graphDb.execute(cypher) } fun sampleObjectQuery() { data class PersonResult(val id: Long, val name: String, val born: Long) data class MovieResult(val id: Long, val title: String, val released: Long, val directors: MutableList<PersonResult>) val mapMovies = mutableMapOf<String, MovieResult>() val mapDirectors = mutableMapOf<String, PersonResult>() graphDb.beginTx().run { val result = graphDb.execute("match (m:Movie)-[:DIRECTED]-(d:Person) return m, d", emptyMap()) while (result.hasNext()) { val record = result.next() logger.info { record } val movie = (record["m"] as Node) val director = (record["d"] as Node) logger.info { "movieId=${movie.id} directorId=${director.id}" } logger.info { "movie.labels=${movie.labels} director.labels=${director.labels}" } if (!mapDirectors.containsKey(director.id.toString())) mapDirectors[director.id.toString()] = PersonResult(director.id, (director.getProperty("name")!!) as String, (director.getProperty("born")!!) as Long) if (!mapMovies.containsKey(movie.id.toString())) mapMovies[movie.id.toString()] = MovieResult(movie.id, (movie.getProperty("title")!!) as String, (movie.getProperty("released")!!) as Long, mutableListOf()) mapMovies[movie.id.toString()]?.directors?.add(mapDirectors[director.id.toString()]!!) } success() } mapMovies.forEach { logger.info { it } } } fun shutdown() { graphDb.shutdown() logger.info { "Closed Neo4j connection" } } } fun main(args: Array<String>) { val neo4jUri = if (args.isNotEmpty()) args[0] else "file://./target/neo4j/EmbeddedServiceBasicTest" val neo4j = Neo4jEmbeddedTest(neo4jUri = neo4jUri) neo4j.sampleObjectQuery() neo4j.shutdown() }
10
Kotlin
0
0
1749bafb650a95fd2668dc05cea8ecb1aefbda35
4,306
neo4k
Apache License 2.0
client/android/src/main/kotlin/client/android/ui/Watchlist.kt
4face-studi0
280,630,732
false
null
package client.android.ui import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.material.OutlinedButton import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import client.Screen import client.android.Get import client.android.ui.list.MovieList import client.android.widget.CenteredText import client.android.widget.ErrorMessage import client.android.widget.LoadingScreen import client.android.widget.MessageScreen import client.resource.Strings import client.viewModel.WatchlistViewModel import co.touchlab.kermit.Logger import domain.stats.GetMoviesInWatchlist import entities.Either import entities.movies.Movie import org.koin.core.Koin import util.exhaustive @Composable fun Watchlist( koin: Koin, buildViewModel: Get<WatchlistViewModel>, toSearch: () -> Unit, toSuggestions: () -> Unit, toMovieDetails: (Movie) -> Unit, logger: Logger ) { HomeScaffold( koin, currentScreen = Screen.Watchlist, topBar = { TitleTopBar(title = Strings.WatchlistAction) }, toSearch = toSearch, toSuggestions = toSuggestions, toWatchlist = {} ) { val scope = rememberCoroutineScope() val viewModel = remember { buildViewModel(scope) } val result by viewModel.result.collectAsState() Column( Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally ) { @Suppress("UnnecessaryVariable") // Needed for smart cast when (val viewState = result) { is Either.Left -> when (result.leftOrThrow()) { is GetMoviesInWatchlist.Error.Unknown -> logger.e(result.toString(), "Watchlist") is GetMoviesInWatchlist.Error.NoMovies -> NoWatchlistMovies(toSuggestions) } is Either.Right -> when (val state = result.rightOrThrow()) { is GetMoviesInWatchlist.State.Loading -> LoadingScreen() is GetMoviesInWatchlist.State.Success -> MovieList( movies = state.movies.toList(), toMovieDetails = toMovieDetails ) } }.exhaustive } } } @Composable private fun NoWatchlistMovies(toSuggestions: () -> Unit) { MessageScreen { ErrorMessage(message = Strings.NoWatchlistMoviesError) CenteredText(text = Strings.GetSuggestionsAndAddToWatchlist, style = MaterialTheme.typography.h5) OutlinedButton(onClick = toSuggestions) { Text(text = Strings.GoToSuggestionsAction) } } }
24
Kotlin
1
3
572514b24063815fba93809a9169a470f89fd445
3,011
CineScout
Apache License 2.0
BaseLibrary/src/main/java/com/kotlin/base/widgets/BannerImageLoader.kt
starktonys
140,391,283
false
null
package com.kotlin.base.widgets import android.content.Context import android.widget.ImageView import com.kotlin.base.utils.GlideUtils import com.youth.banner.loader.ImageLoader /* Banner图片加载器 */ class BannerImageLoader : ImageLoader() { override fun displayImage(context: Context, path: Any, imageView: ImageView) { GlideUtils.loadUrlImage(context, path.toString(), imageView) } }
1
null
1
8
7cb3f869a27c9f8a6ba44b72a7d328a1383ec4aa
405
KotlinMall-App
Apache License 2.0
app/src/main/java/com/fireblocks/sdkdemo/bl/core/server/ResponseInterceptor.kt
fireblocks
690,587,303
false
{"Kotlin": 686152, "HTML": 788}
package com.fireblocks.sdkdemo.bl.core.server import com.fireblocks.sdkdemo.bl.useraction.ResponseReceived import com.google.gson.Gson import okhttp3.Interceptor import okhttp3.Response import okio.Buffer import java.nio.charset.Charset import java.nio.charset.StandardCharsets /** * Created by Fireblocks Ltd. on 18/09/2023 */ class ResponseInterceptor : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val response = chain.proceed(chain.request()) val responseBody = response.body val source = responseBody?.source() source?.request(Long.MAX_VALUE) // Buffer the entire body. val buffer = source?.buffer val contentType = responseBody?.contentType() val charset: Charset = contentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8 val responseString = buffer?.clone()?.readString(charset) val headersMap = hashMapOf<String, String>() response.headers.names().forEach { headersMap[it] = response.header(it) ?: "" } val requestBuffer = Buffer() response.request.body?.writeTo(requestBuffer) val requestContentType = response.request.body?.contentType() val requestCharset: Charset = requestContentType?.charset(StandardCharsets.UTF_8) ?: StandardCharsets.UTF_8 val requestBodyString = requestBuffer.readString(requestCharset) responseReceived(response.request.url.pathSegments.toString().replace("[", "") // .replace("]", ""), // response.request.url.query, // requestBodyString, responseString ?: "", // response.code, // headersMap) return response } private val gson = Gson() fun responseReceived(url: String, query: String?, requestData: String, data: String, statusCode: Int, headers: Map<String, Any>) { val finalUrl = when (query) { null -> url else -> "$url?$query" } val response = hashMapOf("url" to finalUrl, "requestData" to requestData, "body" to data, "statusCode" to statusCode, "headers" to headers) ResponseReceived(gson.toJson(response)).execute() } }
1
Kotlin
3
1
71d5b09868bfb97766fd2bafbd657bcf66c1a5f3
2,425
android-ncw-demo
MIT License
compiler/fir/raw-fir/light-tree2fir/tests/org/jetbrains/kotlin/fir/lightTree/AbstractLightTree2FirConverterTestCase.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.lightTree import org.jetbrains.kotlin.fir.FirRenderer import org.jetbrains.kotlin.fir.builder.AbstractRawFirBuilderTestCase import org.jetbrains.kotlin.fir.builder.StubFirScopeProvider import org.jetbrains.kotlin.fir.render import org.jetbrains.kotlin.fir.session.FirSessionFactory import org.jetbrains.kotlin.test.KotlinTestUtils import java.io.File import java.nio.file.Paths abstract class AbstractLightTree2FirConverterTestCase : AbstractRawFirBuilderTestCase() { fun doTest(filePath: String) { val firFile = LightTree2Fir( session = FirSessionFactory.createEmptySession(), scopeProvider = StubFirScopeProvider, diagnosticsReporter = null ).buildFirFile(Paths.get(filePath)) val firDump = firFile.render(mode = FirRenderer.RenderMode.WithDeclarationAttributes) val expectedFile = File(filePath.replace(".kt", ".txt")) KotlinTestUtils.assertEqualsToFile(expectedFile, firDump) } }
34
null
5074
40,992
57fe6721e3afb154571eb36812fd8ef7ec9d2026
1,170
kotlin
Apache License 2.0
tsvm_core/src/net/torvald/tsvm/UnsafePtr.kt
curioustorvald
258,372,649
false
{"JavaScript": 1125433, "Kotlin": 617197, "BASIC": 44303, "HTML": 29967, "Java": 19462, "Shell": 4521, "C": 1011, "Stata": 948, "Batchfile": 846, "Lua": 744}
package net.torvald import sun.misc.Unsafe import java.io.PrintStream class DanglingPointerException(msg: String) : NullPointerException(msg) class AddressOverflowException(msg: String) : IndexOutOfBoundsException(msg) /** * Further read: * - http://www.docjar.com/docs/api/sun/misc/Unsafe.html * * Created by minjaesong on 2019-06-21. */ internal object UnsafeHelper { val unsafe: Unsafe init { val unsafeConstructor = Unsafe::class.java.getDeclaredConstructor() unsafeConstructor.isAccessible = true unsafe = unsafeConstructor.newInstance() } /** * A factory method to allocate a memory of given size and return its starting address as a pointer. */ fun allocate(size: Long, caller: Any): UnsafePtr { val ptr = unsafe.allocateMemory(size) return UnsafePtr(ptr, size, caller) } fun memcpy(src: UnsafePtr, fromIndex: Long, dest: UnsafePtr, toIndex: Long, copyLength: Long) = unsafe.copyMemory(src.ptr + fromIndex, dest.ptr + toIndex, copyLength) fun memcpy(srcAddress: Long, destAddress: Long, copyLength: Long) = unsafe.copyMemory(srcAddress, destAddress, copyLength) fun memcpyRaw(srcObj: Any?, srcPos: Long, destObj: Any?, destPos: Long, len: Long) = unsafe.copyMemory(srcObj, srcPos, destObj, destPos, len) /** * The array object in JVM is stored in this memory map: * * 0 w 2w * * | Some identifier | Other identifier | the actual data ... | * * (where w = 4 for 32-bit JVM and 8 for 64-bit JVM. If Compressed-OOP is involved, things may get complicated) * * @return offset from the array's base memory address (aka pointer) that the actual data begins. */ fun getArrayOffset(obj: Any) = unsafe.arrayBaseOffset(obj.javaClass).toLong() } /** * To allocate a memory, use UnsafeHelper.allocate(long) * * All the getFloat/Int/whatever methods will follow the endianness of your system, * e.g. it'll be Little Endian on x86, Big Endian on PPC, User-defined on ARM; therefore these functions should not be * used when the portability matters (e.g. Savefile). In such situations, do byte-wise operations will be needed. * * Use of hashCode() is forbidden, use the pointer instead. */ internal class UnsafePtr(pointer: Long, allocSize: Long, private val caller: Any) { var destroyed = false private set var ptr: Long = pointer private set var size: Long = allocSize private set fun realloc(newSize: Long) { ptr = UnsafeHelper.unsafe.reallocateMemory(ptr, newSize) size = newSize } fun destroy() { if (!destroyed) { // println("[UnsafePtr] Destroying pointer $this; called from:") // printStackTrace(this) UnsafeHelper.unsafe.freeMemory(ptr) destroyed = true } } private inline fun checkNullPtr(index: Long) { // ignore what IDEA says and do inline this //// commenting out because of the suspected (or minor?) performance impact. //// You may break the glass and use this tool when some fucking incomprehensible bugs ("vittujen vitun bugit") //// appear (e.g. getting garbage values when it fucking shouldn't) if (destroyed) { throw DanglingPointerException("The pointer is already destroyed ($this)") } if (index !in 0 until size) throw AddressOverflowException("Index: $index; alloc size: $size; pointer: ${this}\n${Thread.currentThread().stackTrace.joinToString("\n", limit=10) { " $it" }}") } operator fun get(index: Long): Byte { checkNullPtr(index) return UnsafeHelper.unsafe.getByte(ptr + index) } operator fun set(index: Long, value: Byte) { checkNullPtr(index) UnsafeHelper.unsafe.putByte(ptr + index, value) } fun getFloatFree(index: Long): Float { checkNullPtr(index) return UnsafeHelper.unsafe.getFloat(ptr + index) } fun getFloat(unit: Long): Float { checkNullPtr(unit * 4L) return UnsafeHelper.unsafe.getFloat(ptr + (unit * 4L)) } fun getIntFree(index: Long): Int { checkNullPtr(index) return UnsafeHelper.unsafe.getInt(ptr + index) } fun getInt(unit: Long): Int { checkNullPtr(unit * 4L) return UnsafeHelper.unsafe.getInt(ptr + (unit * 4L)) } fun getShortFree(index: Long): Short { checkNullPtr(index) return UnsafeHelper.unsafe.getShort(ptr + index) } fun getShort(unit: Long): Short { checkNullPtr(unit * 2L) return UnsafeHelper.unsafe.getShort(ptr + (unit * 2L)) } fun setFloatFree(index: Long, value: Float) { checkNullPtr(index) UnsafeHelper.unsafe.putFloat(ptr + index, value) } fun setFloat(unit: Long, value: Float) { checkNullPtr(unit * 4L) UnsafeHelper.unsafe.putFloat(ptr + (unit * 4L), value) } fun setIntFree(index: Long, value: Int) { checkNullPtr(index) UnsafeHelper.unsafe.putInt(ptr + index, value) } fun setInt(unit: Long, value: Int) { checkNullPtr(unit * 4L) UnsafeHelper.unsafe.putInt(ptr + (unit * 4L), value) } fun setShortFree(index: Long, value: Short) { checkNullPtr(index) UnsafeHelper.unsafe.putShort(ptr + index, value) } fun setShortUnit(unit: Long, value: Short) { checkNullPtr(unit * 2L) UnsafeHelper.unsafe.putShort(ptr + (unit * 2L), value) } fun fillWith(byte: Byte) { UnsafeHelper.unsafe.setMemory(ptr, size, byte) } override fun toString() = "0x${ptr.toString(16)} with size $size, created by $caller" override fun equals(other: Any?) = this.ptr == (other as UnsafePtr).ptr && this.size == other.size inline fun printStackTrace(obj: Any) = printStackTrace(obj, System.out) // because of Java fun printStackTrace(obj: Any, out: PrintStream = System.out) { Thread.currentThread().stackTrace.forEach { out.println("[${obj.javaClass.simpleName}] ... $it") } } }
1
JavaScript
0
2
c520c7214196c53b89c0d2a1260cb48651c6970d
6,156
tsvm
MIT License
app/src/main/java/com/ead/project/dreamer/app/data/util/system/PreferencesExtensions.kt
darkryh
490,353,600
false
{"Kotlin": 766116, "Java": 2316}
package com.ead.project.dreamer.app.data.util.system import com.ead.project.dreamer.app.data.preference.Preferences suspend fun <T>Preferences.setGeneric(key : String,value : T) { when(value) { is Boolean -> set(key,value) is String -> set(key,value) is Int -> set(key,value) is Float -> set(key,value) is Double -> set(key,value) } }
0
Kotlin
1
2
34fe195fe9fec58c7a2b71b8646c1e8c5988a281
385
Dreamer
MIT License
app/src/main/java/com/example/android/barebone/ui/extensions/LiveEvent.kt
hossain-khan
178,583,979
false
null
package com.example.android.ytc.ui.extensions /** * Copyright 2019 <NAME> * 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. */ import androidx.annotation.MainThread import androidx.collection.ArraySet import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.MediatorLiveData import androidx.lifecycle.Observer /** * Single event live data that is intended to be used only once. For example SnackBar, Navigation and other events. * Once event is emitted, it won't be emitted again if activity is restarted. * * Usage: * * ``` * viewModel.singleEventData.observe(this, Observer { * // is the event data `it` to navigate to screen or show single toast/snackbar message * }); * ``` * * Source: * - https://raw.githubusercontent.com/hadilq/LiveEvent/master/lib/src/main/java/com/hadilq/liveevent/LiveEvent.kt * * References: * - https://link.medium.com/qjuB2VGnoV (SingleLiveEvent) * - https://proandroiddev.com/livedata-with-single-events-2395dea972a8 */ class LiveEvent<T> : MediatorLiveData<T>() { private val observers = ArraySet<ObserverWrapper<in T>>() @MainThread override fun observe(owner: LifecycleOwner, observer: Observer<in T>) { val wrapper = ObserverWrapper(observer) observers.add(wrapper) super.observe(owner, wrapper) } @MainThread override fun removeObserver(observer: Observer<in T>) { if (observers.remove(observer)) { super.removeObserver(observer) return } val iterator = observers.iterator() while (iterator.hasNext()) { val wrapper = iterator.next() if (wrapper.observer == observer) { iterator.remove() super.removeObserver(wrapper) break } } } @MainThread override fun setValue(t: T?) { observers.forEach { it.newValue() } super.setValue(t) } private class ObserverWrapper<T>(val observer: Observer<T>) : Observer<T> { private var pending = false override fun onChanged(t: T?) { if (pending) { pending = false observer.onChanged(t) } } fun newValue() { pending = true } } }
6
null
2
7
9857e4a6f90450a92e817249a8f8e9ca526b829c
2,784
android-barebone
Apache License 2.0
shared/src/commonMain/kotlin/com/example/common/models/common/ContentLight.kt
DeNyWho
584,003,645
false
{"Kotlin": 511314}
package com.example.common.models.common import com.example.common.models.animeResponse.common.AnimeGenres import com.example.common.models.animeResponse.common.AnimeStudios import kotlinx.serialization.Serializable @Serializable data class ContentLight( val url: String = "", var title: String = "", var image: String = "", var type: String = "", val studio: List<AnimeStudios> = listOf(), val season: String = "", val year: Int = 0, val episodesCount: Int = 0, val genres: List<AnimeGenres> = listOf(), val status: String = "", val ratingMpa: String = "", val minimalAge: Int = 0, val accentColor: String = "", )
0
Kotlin
0
0
11fa00d9b54d0e460f6f2e76e301f7c9e17087d5
668
AniFoxKMP
Apache License 2.0
src/test/kotlin/canon/parser/xml/strategy/SelectionStrategyTest.kt
leftshiftone
205,671,409
false
null
package canon.parser.xml.strategy import canon.extension.toNode import canon.parser.xml.CanonXmlParser import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.Test class SelectionStrategyTest { @Test fun testParse() { val xml = "<selection id='testId' class='testClass' name='testName' countdownInSec='12'>" + "<items>" + "<item id='a' class='b'></item>" + "</items>" + "</selection>" val parsed = SelectionStrategy().parse(xml.toNode(), CanonXmlParser()::toRenderables) assertThat(parsed).isNotNull assertThat(parsed.id).isEqualTo("testId") assertThat(parsed.`class`).isEqualTo("testClass") assertThat(parsed.name).isEqualTo("testName") assertThat(parsed.countdownInSec).isEqualTo(12) assertThat(parsed.renderables?.get(0)).isNotNull assertThat(parsed.renderables?.size).isEqualTo(1) } }
0
Kotlin
1
0
5babc577eeca5655cf92e64dd2693c591c72eb50
1,071
canon
MIT License
game-api/src/main/kotlin/org/alter/api/ext/InventoryExt.kt
AlterRSPS
421,831,790
false
null
package org.alter.api.ext import org.alter.game.model.attr.INTERACTING_ITEM_SLOT import org.alter.game.model.attr.OTHER_ITEM_SLOT_ATTR import org.alter.game.model.container.ItemContainer import org.alter.game.model.entity.Player import org.alter.game.model.item.Item import org.alter.api.Skills /** * As the "inventory" itself is a specific [ItemContainer] of a [Player], extension functions * here are applied by way of the [Player] to allow for more context to these [Item] operations. * Note| the functions provided herein are designed loosely "allowing" flexibility over slot * awareness and even the container to use in operations and can be used in very unintended * degrees, such as an [ItemContainer] which isn't the [Player]'s or maintaining presumed [getInteractingItemSlot] */ fun Player.maxPossible(vararg items: Int, container: ItemContainer = inventory): Int { val counts = mutableListOf<Int>() items.forEach { item -> counts.add(container.getItemCount(item)) } return Math.min(counts.maxOrNull()!!, container.capacity) } // not slot-aware (uses first available) defaults to inventory fun Player.replaceItem(oldItem: Int, newItem: Int, container: ItemContainer = inventory): Boolean { return replaceItemInSlot(oldItem, newItem, -1, container) } // slot-aware defaulting to interacting slot and inventory fun Player.replaceItemInSlot(oldItem: Int, newItem: Int, slot: Int = getInteractingItemSlot(), container: ItemContainer = inventory): Boolean { return container.replace(oldItem, newItem, slot) } /** * Works to replace all [oldItem] in [container] with [newItem] upto [max] times * in a loop with an increasing delay upto 3 cycles between each replacement and optional * slot awareness. */ fun Player.autoReplace(oldItem: Int, newItem: Int, growingDelay: Boolean = true, slotAware: Boolean = false, container: ItemContainer = inventory, max: Int = container.getItemCount(oldItem), perform: () -> Unit, success: () -> Unit) { val count = container.getItemCount(oldItem) when { count <= 0 -> return count == 1 -> { perform() queue { when(slotAware){ false -> if(container.replace(oldItem, newItem)) success() true -> if(container.replace(oldItem, newItem, container.getItemIndex(oldItem, false))) success() } } } else -> { var made = 0 if(!slotAware) { queue { while (container.contains(oldItem) && made < max){ if(growingDelay){ perform() wait(Math.min(1 + made, 3)) } else { perform() wait(1) } if (container.replace(oldItem, newItem)){ made++ success() } else break } } } else { var slot: Int = getInteractingItemSlot() queue { while(container.contains(oldItem) && made < max){ if(growingDelay){ repeat(Math.min(1 + made, 2)){ perform() wait(1) } } else { perform() wait(1) } if(container.replace(oldItem, newItem, slot)){ made++ success() slot = container.getItemIndex(oldItem, false) } else break } } } } } } fun Player.replaceItemWithSkillRequirement(oldItem: Int, newItem: Int, skill: Int, minLvl: Int = 1, slot: Int = -1, minLvlMessage: String = "You need level $minLvl ${Skills.getSkillName(world, skill)} to do that.", boostable: Boolean = true, container: ItemContainer = inventory): Boolean { val level = if(boostable) getSkills().getCurrentLevel(skill) else getSkills().getBaseLevel(skill) return if(level < minLvl){ message(minLvlMessage) false } else container.replace(oldItem, newItem, slot) } /** * provides wrapper for [ItemContainer.replaceWithItemRequirement] with a customizable * message to respond with if [container] does not contain the [requiredItem] * Note| this method is extremely loose and primarily for giving use to * [ItemContainer.replaceWithItemRequirement] and adds customizable message feedback */ fun Player.replaceItemWithItemRequirement(oldItem: Int, newItem: Int, requiredItem: Int, slot: Int = -1, missingItemMessage: String = "You do not have the #ITEM needed to do that.", container: ItemContainer = inventory): Boolean { return if(!container.contains(requiredItem)){ message(missingItemMessage.replaceItemName(requiredItem, world.definitions)) false } else { // while item requirement has already been assured, no harm comes in using redundancy container.replaceWithItemRequirement(oldItem, newItem, requiredItem, slot) } } fun Player.replaceItemWithItemAndSkillRequirement(oldItem: Int, newItem: Int, requiredItem: Int, skill: Int, minLvl: Int = 1, slot: Int = -1, missingItemMessage: String = "You do not have the #ITEM needed to do that.", minLvlMessage: String = "You need level $minLvl ${Skills.getSkillName(world, skill)} to do that.", unboosted: Boolean = false, container: ItemContainer = inventory): Boolean { val level = if(!unboosted) getSkills().getCurrentLevel(skill) else getSkills().getBaseLevel(skill) return if(level < minLvl){ message(minLvlMessage) false } else if(!container.contains(requiredItem)){ message(missingItemMessage.replaceItemName(requiredItem, world.definitions)) false } else container.replace(oldItem, newItem, slot) } fun Player.replaceItemAndRemoveAnother(oldItem: Int, newItem: Int, otherItem: Item, container: ItemContainer = inventory): Boolean { return container.replaceAndRemoveAnother(oldItem, newItem, otherItem, -1, -1) } fun Player.replaceItemAndRemoveAnotherInSlot(oldItem: Int, newItem: Int, otherItem: Item, slot: Int = -1, otherSlot: Int = -1, container: ItemContainer = inventory): Boolean { return container.replaceAndRemoveAnother(oldItem, newItem, otherItem, slot, otherSlot) } fun Player.replaceItemAndRemoveAnotherWithItemRequirement(oldItem: Int, newItem: Int, otherItem: Item, requiredItem: Int, slot: Int = -1, otherSlot: Int = -1, missingItemMessage: String = "You do not have the #ITEM needed to do that.", container: ItemContainer = inventory): Boolean { return if(!container.contains(requiredItem)){ message(missingItemMessage.replaceItemName(requiredItem, world.definitions)) false } else { // while item requirement has already been assured, no harm comes in using redundancy container.replaceAndRemoveAnotherWithItemRequirement(oldItem, newItem, otherItem, requiredItem, slot, otherSlot) } } fun Player.replaceItemAndRemoveAnotherWithSkillRequirement(oldItem: Int, newItem: Int, otherItem: Item, skill: Int, minLvl: Int = 1, slot: Int = -1, otherSlot: Int = -1, minLvlMessage: String = "You need level $minLvl ${Skills.getSkillName(world, skill)} to do that.", boostable: Boolean = true, container: ItemContainer = inventory): Boolean { val level = if(boostable) getSkills().getCurrentLevel(skill) else getSkills().getBaseLevel(skill) return if(level < minLvl){ message(minLvlMessage) false } else { container.replaceAndRemoveAnother(oldItem, newItem, otherItem, slot, otherSlot) } } fun Player.replaceItemAndRemoveAnotherWithItemAndSkillRequirement(oldItem: Int, newItem: Int, otherItem: Item, requiredItem: Int, skill: Int, minLvl: Int = 1, slot: Int = -1, otherSlot: Int = -1, missingItemMessage: String = "You do not have the #ITEM needed to do that.", minLvlMessage: String = "You need level $minLvl ${Skills.getSkillName(world, skill)} to do that.", boostable: Boolean = true, container: ItemContainer = inventory): Boolean { val level = if(boostable) getSkills().getCurrentLevel(skill) else getSkills().getBaseLevel(skill) return if (level < minLvl) { message(minLvlMessage) false } else if(!container.contains(requiredItem)){ message(missingItemMessage.replaceItemName(requiredItem, world.definitions)) false } else { // while item requirement has already been assured, no harm comes in using redundancy container.replaceAndRemoveAnotherWithItemRequirement(oldItem, newItem, otherItem, requiredItem, slot, otherSlot) } } /** * if [slotAware] is true this method works to instill the first presented pair as the "main" * [Item] and slot determinations are derived from [INTERACTING_ITEM_SLOT] and [OTHER_ITEM_SLOT_ATTR] * Note| if manual slot controls are needed instead, [container.replaceBoth] should be called directly */ fun Player.comboItemReplace(oldItem: Int, newItem: Int, otherOld: Int, otherNew: Int, slotAware: Boolean = false, container: ItemContainer = inventory): Boolean { return if(!slotAware) container.replaceBoth(oldItem, newItem, otherOld, otherNew) else { val interactSlot = getInteractingItemSlot() val mainSlot = if(inventory[interactSlot]!!.id == oldItem) interactSlot else attr[OTHER_ITEM_SLOT_ATTR]!! val otherSlot = if(mainSlot == interactSlot) attr[OTHER_ITEM_SLOT_ATTR]!! else interactSlot container.replaceBoth(oldItem, newItem, otherOld, otherNew, mainSlot, otherSlot) } } fun Player.produceItemBoxMessage(vararg itemsToMake: Int, title: String = if (itemsToMake.size==1) "How many do you wish to make?" else "What would you like to make?", max: Int = inventory.capacity, growingDelay: Boolean = false, logic: () -> Unit){ when { max <= 0 -> { return } max == 1 -> { queue { logic() } } else -> { queue { produceItemBox(*itemsToMake, title = title, maxProducable = max){ _, qty -> player.queue { repeat(qty){ if(growingDelay) wait(Math.min(1+it,2)) else wait(1) // insures production tasks are not spammed logic() // logic may contain it's own delays } } } } } } }
8
null
33
23
8d3b3cb38ab6a0e4bed7976cb2dbfcf75bfac9b3
11,056
Alter
Apache License 2.0
src/commonMain/kotlin/io/klibs/math/big/MutableBigIntImpl.kt
k-libs
598,863,246
false
null
package io.klibs.math.big private const val KNUTH_POW2_THRESH_LEN = 6 private const val KNUTH_POW2_THRESH_ZEROS = 3 internal class MutableBigIntImpl { private var value: IntArray private var intLen: Int private var offset = 0 constructor() { this.value = IntArray(1) this.intLen = 0 } constructor(value: Int) { this.value = intArrayOf(value) this.intLen = 1 } constructor(value: IntArray) { this.value = value this.intLen = value.size } constructor(b: BigIntImpl) { this.intLen = b.mag.size this.value = b.mag.copyOf(intLen) } constructor(value: MutableBigIntImpl) { this.intLen = value.intLen this.value = value.value.copyOfRange(value.offset, value.offset + intLen) } fun isOdd(): Boolean { return if (isZero()) false else value[offset + intLen - 1] and 1 == 1 } fun divide(b: MutableBigIntImpl, quotient: MutableBigIntImpl): MutableBigIntImpl = divide(b, quotient, true)!! fun divide(b: MutableBigIntImpl, quotient: MutableBigIntImpl, needRemainder: Boolean): MutableBigIntImpl? = if (b.intLen < BURNIKEL_ZIEGLER_THRESHOLD || intLen - b.intLen < BURNIKEL_ZIEGLER_OFFSET) divideKnuth(b, quotient, needRemainder) else divideAndRemainderBurnikelZiegler(b, quotient) fun divideKnuth(b: MutableBigIntImpl, quotient: MutableBigIntImpl): MutableBigIntImpl = divideKnuth(b, quotient, true)!! fun divideKnuth(ab: MutableBigIntImpl, quotient: MutableBigIntImpl, needRemainder: Boolean): MutableBigIntImpl? { var b = ab if (b.intLen == 0) throw ArithmeticException("BigInteger divide by zero") // Dividend is zero // Dividend is zero if (intLen == 0) { quotient.offset = 0 quotient.intLen = quotient.offset return if (needRemainder) MutableBigIntImpl() else null } val cmp: Int = compareTo(b) // Dividend less than divisor // Dividend less than divisor if (cmp < 0) { quotient.offset = 0 quotient.intLen = quotient.offset return if (needRemainder) MutableBigIntImpl(this) else null } // Dividend equal to divisor // Dividend equal to divisor if (cmp == 0) { quotient.intLen = 1 quotient.value[0] = quotient.intLen quotient.offset = 0 return if (needRemainder) MutableBigIntImpl() else null } quotient.clear() // Special case one word divisor // Special case one word divisor if (b.intLen == 1) { val r = divideOneWord(b.value.get(b.offset), quotient) return if (needRemainder) { if (r == 0) MutableBigIntImpl() else MutableBigIntImpl(r) } else { null } } // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds // Cancel common powers of two if we're above the KNUTH_POW2_* thresholds if (intLen >= KNUTH_POW2_THRESH_LEN) { val trailingZeroBits: Int = min(getLowestSetBit(), b.getLowestSetBit()) if (trailingZeroBits >= KNUTH_POW2_THRESH_ZEROS * 32) { val a = MutableBigIntImpl(this) b = MutableBigIntImpl(b) a.rightShift(trailingZeroBits) b.rightShift(trailingZeroBits) val r: MutableBigIntImpl = a.divideKnuth(b, quotient) r.leftShift(trailingZeroBits) return r } } return divideMagnitude(b, quotient, needRemainder) } fun divideAndRemainderBurnikelZiegler(b: MutableBigIntImpl, quotient: MutableBigIntImpl): MutableBigIntImpl { val r = intLen val s: Int = b.intLen quotient.offset = 0 quotient.intLen = 0 return if (r < s) { this } else { val m = 1 shl 32 - (s / BURNIKEL_ZIEGLER_THRESHOLD).countLeadingZeroBits() val j = (s + m - 1) / m val n = j * m val n32 = 32L * n val sigma = max(0L, n32 - b.bitLength()).toInt() val bShifted = MutableBigIntImpl(b) bShifted.safeLeftShift(sigma) val aShifted = MutableBigIntImpl(this) aShifted.safeLeftShift(sigma) var t: Int = ((aShifted.bitLength() + n32) / n32).toInt() if (t < 2) { t = 2 } val a1: MutableBigIntImpl = aShifted.getBlock(t - 1, t, n) var z: MutableBigIntImpl = aShifted.getBlock(t - 2, t, n) z.addDisjoint(a1, n) // z[t-2] val qi = MutableBigIntImpl() var ri: MutableBigIntImpl for (i in t - 2 downTo 1) { ri = z.divide2n1n(bShifted, qi) z = aShifted.getBlock(i - 1, t, n) z.addDisjoint(ri, n) quotient.addShifted(qi, i * n) } ri = z.divide2n1n(bShifted, qi) quotient.add(qi) ri.rightShift(sigma) ri } } fun divideOneWord(divisor: Int, quotient: MutableBigIntImpl): Int { val divisorLong = divisor.toLong() and LONG_MASK if (intLen == 1) { val dividendValue = value[offset].toLong() and LONG_MASK val q = (dividendValue / divisorLong).toInt() val r = (dividendValue - q * divisorLong).toInt() quotient.value[0] = q quotient.intLen = if (q == 0) 0 else 1 quotient.offset = 0 return r } if (quotient.value.size < intLen) quotient.value = IntArray(intLen) quotient.offset = 0 quotient.intLen = intLen val shift: Int = divisor.countLeadingZeroBits() var rem = value[offset] var remLong = rem.toLong() and LONG_MASK if (remLong < divisorLong) { quotient.value[0] = 0 } else { quotient.value[0] = (remLong / divisorLong).toInt() rem = (remLong - quotient.value[0] * divisorLong).toInt() remLong = rem.toLong() and LONG_MASK } var xlen = intLen while (--xlen > 0) { val dividendEstimate = remLong shl 32 or (value[offset + intLen - xlen].toLong() and LONG_MASK) var q: Int if (dividendEstimate >= 0) { q = (dividendEstimate / divisorLong).toInt() rem = (dividendEstimate - q * divisorLong).toInt() } else { val tmp: Long = divWord(dividendEstimate, divisor) q = (tmp and LONG_MASK).toInt() rem = (tmp ushr 32).toInt() } quotient.value[intLen - xlen] = q remLong = rem.toLong() and LONG_MASK } quotient.normalize() return if (shift > 0) rem % divisor else rem } fun divide2n1n(b: MutableBigIntImpl, quotient: MutableBigIntImpl): MutableBigIntImpl { val n = b.intLen if (n % 2 != 0 || n < BURNIKEL_ZIEGLER_THRESHOLD) { return divideKnuth(b, quotient) } val aUpper = MutableBigIntImpl(this) aUpper.safeRightShift(32 * (n / 2)) keepLower(n / 2) val q1 = MutableBigIntImpl() val r1: MutableBigIntImpl = aUpper.divide3n2n(b, q1) addDisjoint(r1, n / 2) val r2: MutableBigIntImpl = divide3n2n(b, quotient) quotient.addDisjoint(q1, n / 2) return r2 } fun divide3n2n(b: MutableBigIntImpl, quotient: MutableBigIntImpl): MutableBigIntImpl { val n = b.intLen / 2 val a12 = MutableBigIntImpl(this) a12.safeRightShift(32 * n) val b1 = MutableBigIntImpl(b) b1.safeRightShift(n * 32) val b2: BigIntImpl = b.getLower(n) val r: MutableBigIntImpl val d: MutableBigIntImpl if (compareShifted(b, n) < 0) { r = a12.divide2n1n(b1, quotient) d = MutableBigIntImpl(quotient.toBigInt().times(b2) as BigIntImpl) } else { quotient.ones(n) a12.add(b1) b1.leftShift(32 * n) a12.subtract(b1) r = a12 d = MutableBigIntImpl(b2) d.leftShift(32 * n) d.subtract(MutableBigIntImpl(b2)) } r.leftShift(32 * n) r.addLower(this, n) while (r < d) { r.add(b) quotient.subtract(MutableBigIntImpl(1)) } r.subtract(d) return r } fun divideMagnitude(div: MutableBigIntImpl, quotient: MutableBigIntImpl, needRemainder: Boolean): MutableBigIntImpl? { val shift: Int = div.value[div.offset].countLeadingZeroBits() val dlen = div.intLen val divisor: IntArray val rem: MutableBigIntImpl if (shift > 0) { divisor = IntArray(dlen) copyAndShift(div.value, div.offset, dlen, divisor, 0, shift) if (value[offset].countLeadingZeroBits() >= shift) { val remarr = IntArray(intLen + 1) rem = MutableBigIntImpl(remarr) rem.intLen = intLen rem.offset = 1 copyAndShift(value, offset, intLen, remarr, 1, shift) } else { val remarr = IntArray(intLen + 2) rem = MutableBigIntImpl(remarr) rem.intLen = intLen + 1 rem.offset = 1 var rFrom = offset var c = 0 val n2 = 32 - shift var i = 1 while (i < intLen + 1) { val b = c c = value[rFrom] remarr[i] = b shl shift or (c ushr n2) i++ rFrom++ } remarr[intLen + 1] = c shl shift } } else { divisor = div.value.copyOfRange(div.offset, div.offset + div.intLen) rem = MutableBigIntImpl(IntArray(intLen + 1)) value.copyInto(rem.value, 1, offset, intLen) rem.intLen = intLen rem.offset = 1 } val nlen: Int = rem.intLen val limit = nlen - dlen + 1 if (quotient.value.size < limit) { quotient.value = IntArray(limit) quotient.offset = 0 } quotient.intLen = limit val q = quotient.value if (rem.intLen == nlen) { rem.offset = 0 rem.value[0] = 0 rem.intLen++ } val dh = divisor[0] val dhLong = dh.toLong() and LONG_MASK val dl = divisor[1] for (j in 0 until limit - 1) { var qhat = 0 var qrem = 0 var skipCorrection = false val nh: Int = rem.value.get(j + rem.offset) val nh2 = nh + -0x80000000 val nm: Int = rem.value.get(j + 1 + rem.offset) if (nh == dh) { qhat = 0.inv() qrem = nh + nm skipCorrection = qrem + -0x80000000 < nh2 } else { val nChunk = nh.toLong() shl 32 or (nm.toLong() and LONG_MASK) if (nChunk >= 0) { qhat = (nChunk / dhLong).toInt() qrem = (nChunk - qhat * dhLong).toInt() } else { val tmp: Long = divWord(nChunk, dh) qhat = (tmp and LONG_MASK).toInt() qrem = (tmp ushr 32).toInt() } } if (qhat == 0) continue if (!skipCorrection) { val nl: Long = rem.value.get(j + 2 + rem.offset).toLong() and LONG_MASK var rs = qrem.toLong() and LONG_MASK shl 32 or nl var estProduct = (dl.toLong() and LONG_MASK) * (qhat.toLong() and LONG_MASK) if (unsignedLongCompare(estProduct, rs)) { qhat-- qrem = ((qrem.toLong() and LONG_MASK) + dhLong).toInt() if (qrem.toLong() and LONG_MASK >= dhLong) { estProduct -= dl.toLong() and LONG_MASK rs = qrem.toLong() and LONG_MASK shl 32 or nl if (unsignedLongCompare(estProduct, rs)) qhat-- } } } rem.value[j + rem.offset] = 0 val borrow = mulsub(rem.value, divisor, qhat, dlen, j + rem.offset) if (borrow + -0x80000000 > nh2) { divadd(divisor, rem.value, j + 1 + rem.offset) qhat-- } q[j] = qhat } var qhat = 0 var qrem = 0 var skipCorrection = false val nh: Int = rem.value.get(limit - 1 + rem.offset) val nh2 = nh + -0x80000000 val nm: Int = rem.value.get(limit + rem.offset) if (nh == dh) { qhat = 0.inv() qrem = nh + nm skipCorrection = qrem + -0x80000000 < nh2 } else { val nChunk = nh.toLong() shl 32 or (nm.toLong() and LONG_MASK) if (nChunk >= 0) { qhat = (nChunk / dhLong).toInt() qrem = (nChunk - qhat * dhLong).toInt() } else { val tmp: Long = divWord(nChunk, dh) qhat = (tmp and LONG_MASK).toInt() qrem = (tmp ushr 32).toInt() } } if (qhat != 0) { if (!skipCorrection) { val nl: Long = rem.value.get(limit + 1 + rem.offset).toLong() and LONG_MASK var rs = qrem.toLong() and LONG_MASK shl 32 or nl var estProduct = (dl.toLong() and LONG_MASK) * (qhat.toLong() and LONG_MASK) if (unsignedLongCompare(estProduct, rs)) { qhat-- qrem = ((qrem.toLong() and LONG_MASK) + dhLong).toInt() if (qrem.toLong() and LONG_MASK >= dhLong) { estProduct -= dl.toLong() and LONG_MASK rs = qrem.toLong() and LONG_MASK shl 32 or nl if (unsignedLongCompare(estProduct, rs)) qhat-- } } } val borrow: Int rem.value[limit - 1 + rem.offset] = 0 borrow = if (needRemainder) mulsub(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset) else mulsubBorrow(rem.value, divisor, qhat, dlen, limit - 1 + rem.offset) if (borrow + -0x80000000 > nh2) { if (needRemainder) divadd(divisor, rem.value, limit - 1 + 1 + rem.offset) qhat-- } // Store the quotient digit q[limit - 1] = qhat } if (needRemainder) { if (shift > 0) rem.rightShift(shift) rem.normalize() } quotient.normalize() return if (needRemainder) rem else null } fun getBlock(index: Int, numBlocks: Int, blockLength: Int): MutableBigIntImpl { val blockStart = index * blockLength if (blockStart >= intLen) return MutableBigIntImpl() val blockEnd = if (index == numBlocks - 1) intLen else (index + 1) * blockLength if (blockEnd > intLen) return MutableBigIntImpl() return MutableBigIntImpl(value.copyOfRange(offset + intLen - blockEnd, offset + intLen - blockStart)) } fun getLowestSetBit(): Int { if (intLen == 0) return -1 var j = intLen - 1 while (j > 0 && value[j+offset] == 0) j-- val b = value[j + offset] if (b == 0) return -1 return ((intLen - 1 - j) shl 5) + b.countTrailingZeroBits() } fun bitLength() = if (intLen == 0) 0L else 32L * intLen - value[offset].countLeadingZeroBits() fun clear() { offset = 0 intLen = 0 for (i in 0 .. value.lastIndex) value[i] = 0 } fun reset() { offset = 0 intLen = 0 } fun safeRightShift(n: Int) { if (n / 32 >= intLen) reset() else rightShift(n) } fun rightShift(n: Int) { if (intLen == 0) return val nInts = n ushr 5 val nBits = n and 0x1F intLen -= nInts if (nBits == 0) return val bitsInHighWord = bitLengthForInt(value[offset]) if (nBits >= bitsInHighWord) { primitiveLeftShift(32 - nBits) intLen-- } else { primitiveRightShift(nBits) } } fun primitiveRightShift(n: Int) { val value = this.value val n2 = 32 - n var i = offset + intLen - 1 var c = value[i] while (i > offset) { val b = c c = value[i - 1] value[i] = (c shl n2) or (b ushr n) i-- } value[offset] = value[offset] ushr n } fun primitiveLeftShift(n: Int) { val value = this.value val n2 = 32 - n var i = offset var c = value[i] val m = i + intLen - 1 while (i < m) { val b = c c = value[i + 1] value[i] = (b shl n) or (c ushr n2) i++ } value[offset + intLen - 1] = value[offset + intLen - 1] shl n } fun safeLeftShift(n: Int) { if (n > 0) leftShift(n) } fun leftShift(n: Int) { if (intLen == 0) return val nInts = n ushr 5 val nBits = n and 0x1F val bitsInHighWord = bitLengthForInt(value[offset]) if (n <= 32 - bitsInHighWord) { primitiveLeftShift(nBits) return } var newLen = intLen + nInts + 1 if (nBits <= 32 - bitsInHighWord) newLen-- if (value.size < newLen) { val result = IntArray(newLen) for (i in 0 until intLen) result[i] = value[offset + i] setValue(result, newLen) } else if (value.size - offset >= newLen) { for (i in 0 until newLen - intLen) value[offset + intLen + i] = 0 } else { for (i in 0 until intLen) value[i] = value[offset + i] for (i in intLen until newLen) value[i] = 0 offset = 0 } intLen = newLen if (nBits == 0) return if (nBits <= 32 - bitsInHighWord) primitiveLeftShift(nBits) else primitiveRightShift(32 - nBits) } fun normalize() { if (intLen == 0) { offset = 0 return } var index = offset if (value[index] != 0) return val indexBound = index + intLen do { index++ } while (index < indexBound && value[index] == 0) val numZeros = index - offset intLen -= numZeros offset = if (intLen == 0) 0 else offset + numZeros } fun setValue(value: IntArray, length: Int) { this.value = value this.intLen = length this.offset = 0 } fun ones(n: Int) { if (n > value.size) value = IntArray(n) for (i in 0 .. value.lastIndex) value[i] = -1 offset = 0 intLen = n } fun subtract(tb: MutableBigIntImpl): Int { var a = this var b = tb var result = value var sign = a.compareTo(b) if (sign == 0) { reset() return 0 } if (sign < 0) { val tmp = a a = b b = tmp } val resultLen = a.intLen if (result.size < resultLen) result = IntArray(resultLen) var diff = 0L var x = a.intLen var y = b.intLen var rStart = result.size - 1 while (y > 0) { x--; y-- diff = (a.value[x+a.offset].toLong() and LONG_MASK) - (b.value[y+b.offset].toLong() and LONG_MASK) - (-(diff shr 32)).toInt() result[rStart--] = diff.toInt() } while (x > 0) { x-- diff = (a.value[x+a.offset].toLong() and LONG_MASK) - (-(diff shr 32)).toInt() result[rStart--] = diff.toInt() } value = result intLen = resultLen offset = value.size - resultLen normalize() return sign } fun compareShifted(b: MutableBigIntImpl, ints: Int): Int { val blen = b.intLen val alen = intLen - ints if (alen < blen) return -1 if (alen > blen) return 1 val bval = b.value var i = offset var j = b.offset while (i < alen + offset) { val b1 = value[i] + 0x80000000 val b2 = bval[j] + 0x80000000 if (b1 < b2) return -1 if (b1 > b2) return 1 i++ j++ } return 0 } fun isZero() = intLen == 0 fun add(addend: MutableBigIntImpl) { var x = intLen var y = addend.intLen var resultLen = if (intLen > addend.intLen) intLen else addend.intLen var result = if (value.size < resultLen) IntArray(resultLen) else value var rstart = result.size - 1 var sum: Long var carry: Long = 0 // Add common parts of both numbers // Add common parts of both numbers while (x > 0 && y > 0) { x-- y-- sum = (value[x + offset].toLong() and LONG_MASK) + (addend.value[y + addend.offset].toLong() and LONG_MASK) + carry result[rstart--] = sum.toInt() carry = sum ushr 32 } // Add remainder of the longer number // Add remainder of the longer number while (x > 0) { x-- if (carry == 0L && result == value && rstart == x + offset) return sum = (value[x + offset].toLong() and LONG_MASK) + carry result[rstart--] = sum.toInt() carry = sum ushr 32 } while (y > 0) { y-- sum = (addend.value[y + addend.offset].toLong() and LONG_MASK) + carry result[rstart--] = sum.toInt() carry = sum ushr 32 } if (carry > 0) { // Result must grow in length resultLen++ if (result.size < resultLen) { val temp = IntArray(resultLen) // Result one word longer from carry-out; copy low-order // bits into new result. result.copyInto(temp, 1, 0, result.size) temp[0] = 1 result = temp } else { result[rstart--] = 1 } } value = result intLen = resultLen offset = result.size - resultLen } fun addDisjoint(addend: MutableBigIntImpl, n: Int) { if (addend.isZero()) return val x = intLen var y = addend.intLen + n val resultLen = if (intLen > y) intLen else y val result: IntArray if (value.size < resultLen) { result = IntArray(resultLen) } else { result = value value.fill(0, offset + intLen, value.size) } var rStart = result.size - 1 value.copyInto(result, rStart + 1 - x, offset, x) y -= x rStart -= x val len: Int = min(y, addend.value.size - addend.offset) addend.value.copyInto(result, rStart + 1 - y, addend.offset, len) // zero the gap // zero the gap for (i in rStart + 1 - y + len until rStart + 1) result[i] = 0 value = result intLen = resultLen offset = result.size - resultLen } fun addShifted(addend: MutableBigIntImpl, n: Int) { if (addend.isZero()) { return } var x = intLen var y = addend.intLen + n var resultLen = if (intLen > y) intLen else y var result = if (value.size < resultLen) IntArray(resultLen) else value var rstart = result.size - 1 var sum: Long var carry: Long = 0 // Add common parts of both numbers // Add common parts of both numbers while (x > 0 && y > 0) { x-- y-- val bval = if (y + addend.offset < addend.value.size) addend.value[y + addend.offset] else 0 sum = (value[x + offset].toLong() and LONG_MASK) + (bval.toLong() and LONG_MASK) + carry result[rstart--] = sum.toInt() carry = sum ushr 32 } // Add remainder of the longer number // Add remainder of the longer number while (x > 0) { x-- if (carry == 0L && result == value && rstart == x + offset) { return } sum = (value[x + offset].toLong() and LONG_MASK) + carry result[rstart--] = sum.toInt() carry = sum ushr 32 } while (y > 0) { y-- val bval = if (y + addend.offset < addend.value.size) addend.value[y + addend.offset] else 0 sum = (bval.toLong() and LONG_MASK) + carry result[rstart--] = sum.toInt() carry = sum ushr 32 } if (carry > 0) { // Result must grow in length resultLen++ if (result.size < resultLen) { val temp = IntArray(resultLen) // Result one word longer from carry-out; copy low-order // bits into new result. result.copyInto(temp, 1, 0, result.size) temp[0] = 1 result = temp } else { result[rstart--] = 1 } } value = result intLen = resultLen offset = result.size - resultLen } fun keepLower(n: Int) { if (intLen >= n) { offset += intLen - n intLen = n } } fun getLower(n: Int): BigIntImpl { if (isZero()) { return BigInt.Zero as BigIntImpl } else if (intLen < n) { return toBigInt(1) } else { var len = n while (len > 0 && value[offset + intLen - len] == 0) len-- val sign = if (len > 0) 1 else 0 return BigIntImpl(sign.toByte(), value.copyOfRange(offset + intLen - len, offset + intLen)) } } fun addLower(addend: MutableBigIntImpl, n: Int) { val a = MutableBigIntImpl(addend) if (a.offset + a.intLen >= n) { a.offset = a.offset + a.intLen - n a.intLen = n } a.normalize() add(a) } fun divide(v: Long, quotient: MutableBigIntImpl): Long { var v = v if (v == 0L) throw ArithmeticException("BigInteger divide by zero") // Dividend is zero if (intLen == 0) { quotient.offset = 0 quotient.intLen = quotient.offset return 0 } if (v < 0) v = -v val d = (v ushr 32).toInt() quotient.clear() // Special case on word divisor return if (d == 0) divideOneWord(v.toInt(), quotient).toLong() and LONG_MASK else { divideLongMagnitude(v, quotient).toLong() } } private fun divideLongMagnitude(ldivisor: Long, quotient: MutableBigIntImpl): MutableBigIntImpl { var ldivisor = ldivisor val rem = MutableBigIntImpl(IntArray(intLen + 1)) value.copyInto(rem.value, 1, offset, intLen) rem.intLen = intLen rem.offset = 1 val nlen: Int = rem.intLen val limit = nlen - 2 + 1 if (quotient.value.size < limit) { quotient.value = IntArray(limit) quotient.offset = 0 } quotient.intLen = limit val q: IntArray = quotient.value // D1 normalize the divisor val shift: Int = ldivisor.countLeadingZeroBits() if (shift > 0) { ldivisor = ldivisor shl shift rem.leftShift(shift) } // Must insert leading 0 in rem if its length did not change if (rem.intLen == nlen) { rem.offset = 0 rem.value[0] = 0 rem.intLen++ } val dh = (ldivisor ushr 32).toInt() val dhLong = dh.toLong() and LONG_MASK val dl = (ldivisor and LONG_MASK).toInt() for (j in 0 until limit) { var qhat: Int var qrem: Int var skipCorrection = false val nh: Int = rem.value.get(j + rem.offset) val nh2 = nh + -0x80000000 val nm: Int = rem.value.get(j + 1 + rem.offset) if (nh == dh) { qhat = 0.inv() qrem = nh + nm skipCorrection = qrem + -0x80000000 < nh2 } else { val nChunk = nh.toLong() shl 32 or (nm.toLong() and LONG_MASK) if (nChunk >= 0) { qhat = (nChunk / dhLong).toInt() qrem = (nChunk - qhat * dhLong).toInt() } else { val tmp: Long = divWord(nChunk, dh) qhat = (tmp and LONG_MASK).toInt() qrem = (tmp ushr 32).toInt() } } if (qhat == 0) continue if (!skipCorrection) { val nl: Long = rem.value.get(j + 2 + rem.offset).toLong() and LONG_MASK var rs = qrem.toLong() and LONG_MASK shl 32 or nl var estProduct = (dl.toLong() and LONG_MASK) * (qhat.toLong() and LONG_MASK) if (unsignedLongCompare(estProduct, rs)) { qhat-- qrem = ((qrem.toLong() and LONG_MASK) + dhLong).toInt() if (qrem.toLong() and LONG_MASK >= dhLong) { estProduct -= dl.toLong() and LONG_MASK rs = qrem.toLong() and LONG_MASK shl 32 or nl if (unsignedLongCompare(estProduct, rs)) qhat-- } } } rem.value[j + rem.offset] = 0 val borrow: Int = mulsubLong(rem.value, dh, dl, qhat, j + rem.offset) if (borrow + -0x80000000 > nh2) { // D6 Add back divaddLong(dh, dl, rem.value, j + 1 + rem.offset) qhat-- } q[j] = qhat } if (shift > 0) rem.rightShift(shift) quotient.normalize() rem.normalize() return rem } private fun mulsubLong(q: IntArray, dh: Int, dl: Int, x: Int, offset: Int): Int { var offset = offset val xLong = x.toLong() and LONG_MASK offset += 2 var product = (dl.toLong() and LONG_MASK) * xLong var difference = q[offset] - product q[offset--] = difference.toInt() var carry = ((product ushr 32) + if (difference and LONG_MASK > product.toInt().inv().toLong() and LONG_MASK) 1 else 0) product = (dh.toLong() and LONG_MASK) * xLong + carry difference = q[offset] - product q[offset--] = difference.toInt() carry = ((product ushr 32) + if (difference and LONG_MASK > product.toInt().inv().toLong() and LONG_MASK) 1 else 0) return carry.toInt() } private fun divaddLong(dh: Int, dl: Int, result: IntArray, offset: Int): Int { var carry: Long = 0 var sum = (dl.toLong() and LONG_MASK) + (result[1 + offset].toLong() and LONG_MASK) result[1 + offset] = sum.toInt() sum = (dh.toLong() and LONG_MASK) + (result[offset].toLong() and LONG_MASK) + carry result[offset] = sum.toInt() carry = sum ushr 32 return carry.toInt() } operator fun compareTo(b: MutableBigIntImpl): Int { if (intLen < b.intLen) return -1 if (intLen > b.intLen) return 1 var i = offset var j = b.offset while (i < intLen + offset) { val b1 = value[i] + 0x80000000 val b2 = b.value[j] + 0x80000000 if (b1 < b2) return -1 if (b1 > b2) return 1 i++ j++ } return 0 } fun toBigInt(sign: Int): BigIntImpl { return if (intLen == 0 || sign == 0) BigInt.Zero as BigIntImpl else BigIntImpl(sign.toByte(), getMagnitudeArray()) } fun toBigInt(): BigIntImpl { normalize() return toBigInt(if (isZero()) 0 else 1) } private fun getMagnitudeArray(): IntArray { if (offset > 0 || value.size != intLen) { val tmp: IntArray = value.copyOfRange(offset, offset + intLen) value.fill(0) offset = 0 intLen = tmp.size value = tmp } return value } private fun toLong(): Long { if (intLen == 0) return 0 val d = value[offset].toLong() and LONG_MASK return if (intLen == 2) d shl 32 or (value[offset + 1].toLong() and LONG_MASK) else d } private fun mulsub(q: IntArray, a: IntArray, x: Int, len: Int, offset: Int): Int { val xLong = x.toLong() and LONG_MASK var carry = 0L var o = offset + len for (j in len - 1 downTo 0) { val product = (a[j].toLong() and LONG_MASK) * xLong + carry val difference = q[o] - product q[o--] = difference.toInt() carry = (product ushr 32) + if (difference and LONG_MASK > product.toInt().inv().toLong() and LONG_MASK) 1 else 0 } return carry.toInt() } private fun mulsubBorrow(q: IntArray, a: IntArray, x: Int, len: Int, offset: Int): Int { val xLong = x.toLong() and LONG_MASK var carry: Long = 0 var o = offset + len for (j in len - 1 downTo 0) { val product = (a[j].toLong() and LONG_MASK) * xLong + carry val difference = q[o--] - product carry = ((product ushr 32) + if (difference and LONG_MASK > product.toInt().inv().toLong() and LONG_MASK) 1 else 0) } return carry.toInt() } private fun divadd(a: IntArray, result: IntArray, offset: Int): Int { var carry = 0L for (j in a.lastIndex downTo 0) { val sum = (a[j].toLong() and LONG_MASK) + (result[j + offset].toLong() and LONG_MASK) + carry result[j + offset] = sum.toInt() carry = sum ushr 32 } return carry.toInt() } private fun divWord(n: Long, d: Int): Long { val dLong = d.toLong() and LONG_MASK var r: Long var q: Long if (dLong == 1L) { q = n.toInt().toLong() r = 0 return (r shl 32) or (q and LONG_MASK) } q = (n ushr 1) / (dLong ushr 1) r = n - q * dLong while (r < 0) { r += dLong q-- } while (r >= dLong) { r -= dLong q++ } return (r shl 32) or (q and LONG_MASK) } fun compareHalf(b: MutableBigIntImpl): Int { val blen: Int = b.intLen val len = intLen if (len <= 0) return if (blen <= 0) 0 else -1 if (len > blen) return 1 if (len < blen - 1) return -1 val bval: IntArray = b.value var bstart = 0 var carry = 0 // Only 2 cases left:len == blen or len == blen - 1 if (len != blen) { // len == blen - 1 carry = if (bval[bstart] == 1) { ++bstart -0x80000000 } else return -1 } // compare values with right-shifted values of b, // carrying shifted-out bits across words val `val` = value var i = offset var j = bstart while (i < len + offset) { val bv = bval[j++] val hb = ((bv ushr 1) + carry).toLong() and LONG_MASK val v = `val`[i++].toLong() and LONG_MASK if (v != hb) return if (v < hb) -1 else 1 carry = bv and 1 shl 31 // carray will be either 0x80000000 or 0 } return if (carry == 0) 0 else -1 } } private fun copyAndShift(src: IntArray, srcFrom: Int, srcLen: Int, dst: IntArray, dstFrom: Int, shift: Int) { var srcFrom = srcFrom val n2 = 32 - shift var c = src[srcFrom] for (i in 0 until srcLen - 1) { val b = c c = src[++srcFrom] dst[dstFrom + i] = b shl shift or (c ushr n2) } dst[dstFrom + srcLen - 1] = c shl shift } private fun unsignedLongCompare(one: Long, two: Long) = (one + Long.MIN_VALUE) > (two + Long.MIN_VALUE)
0
Kotlin
0
0
129b2aefb2b528b2605c4a6f05fd96f2ebde2225
32,143
k-big-numbers
MIT License
api/src/main/kotlin/de/hanno/hpengine/graphics/constants/PrimitiveType.kt
hannomalie
330,376,962
false
{"Kotlin": 905817, "GLSL": 694474, "JavaScript": 3160, "Shell": 137, "Batchfile": 65}
package de.hanno.hpengine.graphics.constants enum class PrimitiveType { Lines, Triangles, Patches, }
0
Kotlin
0
0
cfa74a4aff78ae913c1369a6e9852a309bec8186
114
hpengine
MIT License
app/src/main/kotlin/com/akinci/chatter/data/rest/user/Id.kt
AttilaAKINCI
353,730,900
false
{"Kotlin": 193030}
package com.akinci.chatter.data.rest.user import kotlinx.serialization.Serializable @Serializable data class Id( val name: String, val value: String?, )
0
Kotlin
0
0
22fcbbc4b5ec2f98094ea89d52d2e9baa05ca7e6
163
ChatterAI
Apache License 2.0
funcify-feature-eng-materializer/src/main/kotlin/funcify/feature/materializer/output/SingleRequestJsonFieldValueDeserializer.kt
anticipasean
458,910,592
false
{"Kotlin": 2751524, "HTML": 1817}
package funcify.feature.materializer.output import arrow.core.Option import com.fasterxml.jackson.databind.JsonNode import funcify.feature.materializer.session.field.SingleRequestFieldMaterializationSession /** * @author smccarron * @created 2024-04-23 */ interface SingleRequestJsonFieldValueDeserializer : JsonFieldValueDeserializer<SingleRequestFieldMaterializationSession> { override fun deserializeValueForFieldFromJsonInSession( session: SingleRequestFieldMaterializationSession, jsonValue: JsonNode ): Option<Any> }
0
Kotlin
0
0
284b941de10a5b85b9ba1b5236a1d57289e10492
557
funcify-feature-eng
Apache License 2.0
app/presentation/src/main/java/com/wiensmit/rmapp/presentation/ui/overview/OverviewFragment.kt
wiensmit
672,520,737
false
null
package com.wiensmit.rmapp.presentation.ui.overview import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import com.wiensmit.rmapp.presentation.components.compose.theme.AppTheme import com.wiensmit.rmapp.presentation.ui.overview.ui.OverviewScreen import dagger.hilt.android.AndroidEntryPoint /** * Art overview fragment, used as a wrapper for its compose screen * * version 1.0 */ @AndroidEntryPoint class OverviewFragment : Fragment() { private val overviewVM: OverviewViewModel by viewModels() @ExperimentalFoundationApi override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return ComposeView(requireContext()).apply { setViewCompositionStrategy( ViewCompositionStrategy.DisposeOnLifecycleDestroyed(requireActivity().lifecycle) ) setContent { AppTheme { OverviewScreen( viewModel = overviewVM, onItemClicked = ::navigateDetails ) } } } } private fun navigateDetails(objectNumber: String) { findNavController().navigate(OverviewFragmentDirections.actionDashboardToAddExtras(objectNumber)) } }
0
Kotlin
0
0
1b3d022dd9d49ac07345e271ad5da82638909045
1,657
rm-app
Apache License 2.0
app/src/main/java/com/push/nycschools/model/apiservice/SchoolService.kt
kokoAfantchao
258,697,326
false
null
package com.push.nycschools.model.apiservice import com.push.nycschools.model.School import retrofit2.Call import retrofit2.http.GET interface SchoolService { companion object { val API_BASE_URL ="https://data.cityofnewyork.us/resource/" } @GET("s3k6-pzi2.json") fun getListSchool() : Call<List<School>> }
1
null
1
1
5d2031bb8a875876c0d5a6eb0549b3ddd032a91b
336
20200425-kokoNestor-Afantchao-NYCSchools
MIT License
src/test/kotlin/version/VersionServiceTest.kt
exigow
202,529,822
false
null
package version import BaseTest import version.data.Version class VersionServiceTest : BaseTest() { fun `test v3_2 is default`() { assertEquals(VersionService.current().versionId, "3.2") } fun `test v3_2`() { val version = VersionService.all().find { it.versionId == "3.2" }!! assertUniqueClasses(version) assertNotEmpty(version.classes) assertNotEmpty(version.primitives) assertNotEmpty(version.singletons) assertNotEmpty(version.globals) } fun `test v3_3`() { val version = VersionService.all().find { it.versionId == "3.3" }!! assertUniqueClasses(version) assertNotEmpty(version.classes) assertNotEmpty(version.primitives) assertNotEmpty(version.singletons) assertNotEmpty(version.globals) } fun `test v3_4`() { val version = VersionService.all().find { it.versionId == "3.4" }!! assertUniqueClasses(version) assertNotEmpty(version.classes) assertNotEmpty(version.primitives) assertNotEmpty(version.singletons) assertNotEmpty(version.globals) } fun `test v4_0`() { val version = VersionService.all().find { it.versionId == "4.0" }!! assertUniqueClasses(version) assertNotEmpty(version.classes) assertNotEmpty(version.primitives) assertNotEmpty(version.singletons) assertNotEmpty(version.globals) } fun `test disabled`() { val disabled = VersionService.all().find { it.versionId == "Disabled" }!! assertEmpty(disabled.classes) assertEmpty(disabled.primitives) assertEmpty(disabled.singletons) assertEmpty(disabled.globals) } private fun assertUniqueClasses(version: Version) { val all = version.classes + version.globals + version.singletons + version.primitives val noDuplicates = all.groupingBy { it } .eachCount() .filter { it.value > 1 } .none() assertTrue(noDuplicates) } }
17
Kotlin
7
98
44c934ed885fa733d5766cff359bc3335daab8a0
2,047
intellij-gdscript
MIT License
app/src/main/java/net/pilseong/todocompose/ui/screen/task/TaskAppBar.kt
pilseong
640,470,050
false
null
package net.pilseong.todocompose.ui.screen.task import android.util.Log import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Edit import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import net.pilseong.todocompose.R import net.pilseong.todocompose.data.model.Priority import net.pilseong.todocompose.data.model.TodoTask import net.pilseong.todocompose.ui.components.DisplayAlertDialog import net.pilseong.todocompose.ui.theme.TodoComposeTheme import net.pilseong.todocompose.ui.theme.topBarContainerColor import net.pilseong.todocompose.ui.theme.topBarContentColor import net.pilseong.todocompose.util.Action import net.pilseong.todocompose.util.TaskAppBarState @Composable fun TaskAppBar( taskAppBarState: TaskAppBarState = TaskAppBarState.VIEWER, todoTask: TodoTask, toListScreen: (Action) -> Unit, onCopyClicked: () -> Unit, onUpdateClicked: () -> Unit ) { when (taskAppBarState) { TaskAppBarState.VIEWER -> { Log.i("PHILIP", "[TaskAppBar] todo received ${todoTask.title}") DetailTaskBar( todoTask = todoTask, toListScreen = toListScreen, onCopyClicked = onCopyClicked, onUpdateClicked = onUpdateClicked ) } TaskAppBarState.EDITOR -> { Log.i("PHILIP", "[TaskAppBar] todo received ${todoTask.id != -1}") EditTaskBar(toListScreen = toListScreen, edit = todoTask.id != -1) } } } // 새로운 메모 작성 이나 기존 메모 수정을 위한 화면의 app bar // edit 이 true 일 경우는 기존 메모 수정 false 일 경우는 신규 메모 @OptIn(ExperimentalMaterial3Api::class) @Composable fun EditTaskBar( toListScreen: (Action) -> Unit, edit: Boolean = false ) { TopAppBar( navigationIcon = { CommonAction( onClicked = { toListScreen(Action.NO_ACTION) }, icon = Icons.Default.ArrowBack, description = "Arrow backwards Icon" ) }, title = { Text( text = if (edit) stringResource(id = R.string.edit_task_appbar_title) else stringResource(id = R.string.new_task_appbar_title), color = MaterialTheme.colorScheme.topBarContentColor ) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.topBarContainerColor ), actions = { // done action CommonAction( onClicked = { if (edit) { toListScreen(Action.UPDATE) } else { toListScreen(Action.ADD) } }, icon = Icons.Default.Check, description = "Check Icon for new task" ) } ) } @Composable fun CommonAction( onClicked: () -> Unit, icon: ImageVector? = null, painter: Painter? = null, description: String, tint: Color = MaterialTheme.colorScheme.topBarContentColor ) { IconButton(onClick = { onClicked() }) { if (icon == null && painter != null) { Icon( painter = painter, contentDescription = description, tint = tint ) } else if (icon != null && painter == null) { Icon( imageVector = icon, contentDescription = description, tint = tint ) } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun DetailTaskBar( todoTask: TodoTask, toListScreen: (Action) -> Unit, onCopyClicked: () -> Unit, onUpdateClicked: () -> Unit ) { Log.i("PHILIP", "[DetailTaskBar] todo received $todoTask") TopAppBar( navigationIcon = { CommonAction( onClicked = { toListScreen(Action.NO_ACTION) }, icon = Icons.Default.Close, description = stringResource( R.string.default_task_bar_back_arrow_icon ) ) }, title = { Text( text = todoTask.title, overflow = TextOverflow.Ellipsis, color = MaterialTheme.colorScheme.topBarContentColor ) }, colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.topBarContainerColor ), actions = { DetailTaskBarActions( todoTask = todoTask, toListScreen = toListScreen, onCopyClicked = onCopyClicked, onUpdateClicked = onUpdateClicked ) } ) } @Composable fun DetailTaskBarActions( todoTask: TodoTask, toListScreen: (Action) -> Unit, onCopyClicked: () -> Unit, onUpdateClicked: () -> Unit ) { // deletion confirmation popup state var expanded by remember { mutableStateOf(false) } // 경고 팝업 DisplayAlertDialog( title = stringResource(id = R.string.delete_task_dialog_title, todoTask.title), message = stringResource(id = R.string.delete_task_dialog_confirmation, todoTask.title), openDialog = expanded, onCloseDialog = { expanded = false }, onYesClicked = { toListScreen(Action.DELETE) } ) // copy to clipboard CommonAction( onClicked = { onCopyClicked() }, painter = painterResource(id = R.drawable.ic_baseline_content_copy_24), description = stringResource(id = R.string.viewer_appbar_clipboard_icon) ) // update CommonAction( onClicked = { onUpdateClicked() }, icon = Icons.Default.Edit, description = stringResource(id = R.string.viewer_appbar_update_icon) ) // delete CommonAction( onClicked = { expanded = true }, icon = Icons.Default.Delete, description = stringResource(id = R.string.viewer_appbar_delete_icon) ) } @Preview @Composable fun EditTaskBarPreview() { TodoComposeTheme { EditTaskBar(toListScreen = {}) } } @Preview @Composable fun DetailTaskBarPreview() { TodoComposeTheme { DetailTaskBar( todoTask = TodoTask( 1, "필성 힘내!!!", "할 수 있어. 다 와 간다. 힘내자 다 할 수 있어 잘 될 거야", Priority.HIGH ), toListScreen = {}, onCopyClicked = {}, onUpdateClicked = {} ) } }
0
Kotlin
0
0
24bf15bd78691ab8dde62bd1d50c92f8c2376714
7,557
todocompose
Apache License 2.0
server/claroforma-backend/src/test/kotlin/com/claroaprende/repository/UserEsRepositoryIT.kt
ysahnpark
91,903,074
false
{"JavaScript": 916942, "CSS": 602318, "TypeScript": 37386, "Vue": 18243, "Kotlin": 11104, "HTML": 145, "Batchfile": 63}
package com.claroaprende.repository import com.claroaprende.model.UserAccount import org.assertj.core.api.Assertions import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner /** * Created by Young-Suk on 10/28/2017. */ @RunWith(SpringRunner::class) @SpringBootTest class MapHelperTest { @Autowired lateinit var repo: UserEsRepository @Test fun test_crud() { val userAccount = UserAccount(sid="1", username = "test", password = "xyz", givenName = "John", familyName = "Doe") repo.save(userAccount) val fetched = repo.findOne("1") Assertions.assertThat(fetched).isNotNull() repo.delete("1") val fetched2 = repo.findOne("1") Assertions.assertThat(fetched2).isNull() } }
0
JavaScript
0
0
a7c19b45d51d665326cc0e30fbf0715f95244f87
949
claroforma
MIT License
idea/tests/testData/resolve/references/qualifiedAccess/callableReference3.kt
JetBrains
278,369,660
false
null
// IGNORE_FE10 package foo.bar.baz class AA { companion object { fun foo() {} } } fun test() { A<caret>A::foo // FE1.0 won't resolve this } // REF: companion object of (foo.bar.baz).AA
284
Kotlin
5748
82
cc81d7505bc3e9ad503d706998ae8026c067e838
208
intellij-kotlin
Apache License 2.0
day/src/main/java/com/ruzhan/day/DayHomeFragment.kt
wy676579037
209,918,227
true
{"Kotlin": 92278, "Java": 4398}
package com.ruzhan.day import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.lion.font.FontHelper import com.ruzhan.common.TitleHelper import com.ruzhan.day.adapter.DayHomeAdapter import kotlinx.android.synthetic.main.day_frag_home.* class DayHomeFragment : Fragment() { companion object { @JvmStatic fun newInstance() = DayHomeFragment() } private var dayHomeAdapter: DayHomeAdapter? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.day_frag_home, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val dayViewModel = ViewModelProviders.of(activity!!) .get(DayViewModel::class.java) initData() initLiveData(dayViewModel) dayViewModel.getLocalDayList() dayViewModel.refreshDayNewList() } private fun initLiveData(dayViewModel: DayViewModel) { dayViewModel.tagListLiveData.observe(this, Observer<List<String>> { tagList -> if (tagList != null) { dayHomeAdapter?.setData(tagList) } }) } private fun initData() { titleTv.typeface = FontHelper.get().getBoldTypeface() titleTv.text = resources.getString(R.string.day_common_title_name) TitleHelper.setToolbar(toolbar, activity) TitleHelper.setAlphaScaleAnimate(titleTv) val dayHomeAdapter = DayHomeAdapter(childFragmentManager) this.dayHomeAdapter = dayHomeAdapter viewPager.adapter = dayHomeAdapter tabLayout.setupWithViewPager(viewPager) } }
0
null
0
0
d615d3e28da4a3dfc62937b0392ae73f167dc4f2
2,007
awaker
Apache License 2.0
core/src/ru/deadsoftware/cavedroid/misc/utils/MeasureUnitsUtils.kt
fredboy
196,049,035
false
null
package ru.deadsoftware.cavedroid.misc.utils import com.badlogic.gdx.math.MathUtils /** * Converts this value in BLOCKS into pixels */ val Float.px get() = this * 16f /** * Converts this value in BLOCKS into pixels */ val Int.px get() = this * 16f /** * Converts this value in PIXELS into blocks */ val Float.bl get() = MathUtils.floor(this / 16f)
0
null
1
6
1e285247085ba04351feb486a0be6aa577f43093
357
cavedroid
MIT License
msal/src/main/java/com/microsoft/identity/nativeauth/statemachine/states/SignUpStates.kt
AzureAD
64,339,521
false
{"Java": 2084397, "Kotlin": 783134}
// Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files(the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and / or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package com.microsoft.identity.nativeauth.statemachine.states import android.os.Parcel import android.os.Parcelable import com.microsoft.identity.nativeauth.NativeAuthPublicClientApplication import com.microsoft.identity.nativeauth.NativeAuthPublicClientApplicationConfiguration import com.microsoft.identity.nativeauth.UserAttributes import com.microsoft.identity.client.exception.MsalException import com.microsoft.identity.client.internal.CommandParametersAdapter import com.microsoft.identity.nativeauth.statemachine.results.SignUpResendCodeResult import com.microsoft.identity.nativeauth.statemachine.results.SignUpResult import com.microsoft.identity.nativeauth.statemachine.results.SignUpSubmitAttributesResult import com.microsoft.identity.nativeauth.statemachine.results.SignUpSubmitCodeResult import com.microsoft.identity.nativeauth.statemachine.results.SignUpSubmitPasswordResult import com.microsoft.identity.nativeauth.toListOfRequiredUserAttribute import com.microsoft.identity.nativeauth.toMap import com.microsoft.identity.common.nativeauth.internal.commands.SignUpResendCodeCommand import com.microsoft.identity.common.nativeauth.internal.commands.SignUpSubmitCodeCommand import com.microsoft.identity.common.nativeauth.internal.commands.SignUpSubmitPasswordCommand import com.microsoft.identity.common.nativeauth.internal.commands.SignUpSubmitUserAttributesCommand import com.microsoft.identity.common.nativeauth.internal.controllers.NativeAuthMsalController import com.microsoft.identity.common.java.controllers.CommandDispatcher import com.microsoft.identity.common.java.nativeauth.controllers.results.INativeAuthCommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpCommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpResendCodeCommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpSubmitCodeCommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpSubmitPasswordCommandResult import com.microsoft.identity.common.java.nativeauth.controllers.results.SignUpSubmitUserAttributesCommandResult import com.microsoft.identity.common.java.eststelemetry.PublicApiId import com.microsoft.identity.common.java.logging.LogSession import com.microsoft.identity.common.java.logging.Logger import com.microsoft.identity.common.java.util.StringUtil import com.microsoft.identity.common.java.nativeauth.util.checkAndWrapCommandResultType import com.microsoft.identity.nativeauth.statemachine.errors.ErrorTypes import com.microsoft.identity.nativeauth.statemachine.errors.ResendCodeError import com.microsoft.identity.nativeauth.statemachine.errors.SignUpErrorTypes import com.microsoft.identity.nativeauth.statemachine.errors.SignUpSubmitAttributesError import com.microsoft.identity.nativeauth.statemachine.errors.SignUpSubmitPasswordError import com.microsoft.identity.nativeauth.statemachine.errors.SubmitCodeError import com.microsoft.identity.nativeauth.utils.serializable import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * Native Auth uses a state machine to denote state of and transitions within a flow. * SignUpCodeRequiredState class represents a state where the user has to provide a code to progress * in the signup flow. * @property continuationToken: Continuation token to be passed in the next request * @property correlationId: Correlation ID taken from the previous API response and passed to the next request * @property username: Email address of the user * @property config Configuration used by Native Auth */ class SignUpCodeRequiredState internal constructor( override val continuationToken: String, override val correlationId: String, private val username: String, private val config: NativeAuthPublicClientApplicationConfiguration ) : BaseState(continuationToken = continuationToken, correlationId = correlationId), State, Parcelable { private val TAG: String = SignUpCodeRequiredState::class.java.simpleName constructor(parcel: Parcel) : this( continuationToken = parcel.readString() ?: "", correlationId = parcel.readString() ?: "UNSET", username = parcel.readString() ?: "", config = parcel.serializable<NativeAuthPublicClientApplicationConfiguration>() as NativeAuthPublicClientApplicationConfiguration ) interface SubmitCodeCallback : Callback<SignUpSubmitCodeResult> /** * Submits the verification code received to the server; callback variant. * * @param code the code to submit. * @param callback [com.microsoft.identity.nativeauth.statemachine.states.SignUpCodeRequiredState.SubmitCodeCallback] to receive the result on. * @return The results of the submit code action. */ fun submitCode(code: String, callback: SubmitCodeCallback) { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.submitCode" ) NativeAuthPublicClientApplication.pcaScope.launch { try { val result = submitCode(code) callback.onResult(result) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in submitCode", e) callback.onError(e) } } } /** * Submits the verification code received to the server; Kotlin coroutines variant. * * @param code the code to submit. * @return The results of the submit code action. */ suspend fun submitCode( code: String, ): SignUpSubmitCodeResult { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.submitCode(code: String)" ) return withContext(Dispatchers.IO) { val commandParameters = CommandParametersAdapter.createSignUpSubmitCodeCommandParameters( config, config.oAuth2TokenCache, code, continuationToken, correlationId ) val command = SignUpSubmitCodeCommand( commandParameters, NativeAuthMsalController(), PublicApiId.NATIVE_AUTH_SIGN_UP_SUBMIT_CODE ) val rawCommandResult = CommandDispatcher.submitSilentReturningFuture(command).get() return@withContext when (val result = rawCommandResult.checkAndWrapCommandResultType<SignUpSubmitCodeCommandResult>()) { is SignUpCommandResult.PasswordRequired -> { SignUpResult.PasswordRequired( nextState = SignUpPasswordRequiredState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ) ) } is SignUpCommandResult.AttributesRequired -> { SignUpResult.AttributesRequired( nextState = SignUpAttributesRequiredState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ), requiredAttributes = result.requiredAttributes.toListOfRequiredUserAttribute() ) } is SignUpCommandResult.Complete -> { SignUpResult.Complete( nextState = SignInContinuationState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ) ) } is SignUpCommandResult.InvalidCode -> { SubmitCodeError( errorType = ErrorTypes.INVALID_CODE, error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId, subError = result.subError ) } is INativeAuthCommandResult.Redirect -> { SubmitCodeError( errorType = ErrorTypes.BROWSER_REQUIRED, error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId ) } // This should be caught earlier in the flow, so throwing UnexpectedError is SignUpCommandResult.UsernameAlreadyExists -> { Logger.warn( TAG, result.correlationId, "Submit code received unexpected result: $result" ) SubmitCodeError( errorMessage = result.errorDescription, error = result.error, correlationId = result.correlationId ) } is INativeAuthCommandResult.UnknownError -> { Logger.warn( TAG, result.correlationId, "Submit code received unexpected result: $result" ) SubmitCodeError( errorMessage = result.errorDescription, error = result.error, correlationId = result.correlationId, exception = result.exception ) } } } } interface SignUpWithResendCodeCallback : Callback<SignUpResendCodeResult> /** * Resends a new verification code to the user; callback variant. * * @param callback [com.microsoft.identity.nativeauth.statemachine.states.SignUpCodeRequiredState.SignUpWithResendCodeCallback] to receive the result on. * @return The results of the resend code action. */ fun resendCode( callback: SignUpWithResendCodeCallback ) { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.resendCode" ) NativeAuthPublicClientApplication.pcaScope.launch { try { val result = resendCode() callback.onResult(result) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in resendCode", e) callback.onError(e) } } } /** * Resends a new verification code to the user; Kotlin coroutines variant. * * @return The results of the resend code action. */ suspend fun resendCode(): SignUpResendCodeResult { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.resendCode()" ) return withContext(Dispatchers.IO) { val commandParameters = CommandParametersAdapter.createSignUpResendCodeCommandParameters( config, config.oAuth2TokenCache, continuationToken, correlationId ) val command = SignUpResendCodeCommand( commandParameters, NativeAuthMsalController(), PublicApiId.NATIVE_AUTH_SIGN_UP_RESEND_CODE ) val rawCommandResult = CommandDispatcher.submitSilentReturningFuture(command).get() return@withContext when (val result = rawCommandResult.checkAndWrapCommandResultType<SignUpResendCodeCommandResult>()) { is SignUpCommandResult.CodeRequired -> { SignUpResendCodeResult.Success( nextState = SignUpCodeRequiredState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ), codeLength = result.codeLength, sentTo = result.challengeTargetLabel, channel = result.challengeChannel ) } is INativeAuthCommandResult.Redirect, is INativeAuthCommandResult.UnknownError -> { Logger.warn( TAG, result.correlationId, "Resend code received unexpected result: $result" ) ResendCodeError( errorMessage = (result as INativeAuthCommandResult.Error).errorDescription, error = (result as INativeAuthCommandResult.Error).error, correlationId = (result as INativeAuthCommandResult.Error).correlationId, errorCodes = (result as INativeAuthCommandResult.Error).errorCodes, exception = if (result is INativeAuthCommandResult.UnknownError) result.exception else null ) } } } } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(continuationToken) parcel.writeString(correlationId) parcel.writeString(username) parcel.writeSerializable(config) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<SignUpCodeRequiredState> { override fun createFromParcel(parcel: Parcel): SignUpCodeRequiredState { return SignUpCodeRequiredState(parcel) } override fun newArray(size: Int): Array<SignUpCodeRequiredState?> { return arrayOfNulls(size) } } } /** * Native Auth uses a state machine to denote state of and transitions within a flow. * SignUpPasswordRequiredState class represents a state where the user has to provide a password * to progress in the signup flow. * @property continuationToken: Continuation token to be passed in the next request * @property correlationId: Correlation ID taken from the previous API response and passed to the next request * @property username: Email address of the user * @property config Configuration used by Native Auth */ class SignUpPasswordRequiredState internal constructor( override val continuationToken: String, override val correlationId: String, private val username: String, private val config: NativeAuthPublicClientApplicationConfiguration ) : BaseState(continuationToken = continuationToken, correlationId = correlationId), State, Parcelable { private val TAG: String = SignUpPasswordRequiredState::class.java.simpleName constructor(parcel: Parcel) : this( continuationToken = parcel.readString() ?: "", correlationId = parcel.readString() ?: "UNSET", username = parcel.readString() ?: "", config = parcel.serializable<NativeAuthPublicClientApplicationConfiguration>() as NativeAuthPublicClientApplicationConfiguration ) interface SignUpSubmitPasswordCallback : Callback<SignUpSubmitPasswordResult> /** * Submits a password for the account to the server; callback variant. * * @param password the password to submit. * @param callback [com.microsoft.identity.nativeauth.statemachine.states.SignUpPasswordRequiredState.SignUpSubmitPasswordCallback] to receive the result on. * @return The results of the submit password action. */ fun submitPassword( password: CharArray, callback: SignUpSubmitPasswordCallback ) { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.submitPassword" ) NativeAuthPublicClientApplication.pcaScope.launch { try { val result = submitPassword(password) callback.onResult(result) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in submitPassword", e) callback.onError(e) } } } /** * Submits a password for the account to the server; Kotlin coroutines variant. * * @param password the password to submit. * @return The results of the submit password action. */ suspend fun submitPassword(password: CharArray): SignUpSubmitPasswordResult { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.submitPassword(password: CharArray)" ) return withContext(Dispatchers.IO) { val commandParameters = CommandParametersAdapter.createSignUpSubmitPasswordCommandParameters( config, config.oAuth2TokenCache, continuationToken, correlationId, password ) val command = SignUpSubmitPasswordCommand( commandParameters, NativeAuthMsalController(), PublicApiId.NATIVE_AUTH_SIGN_UP_SUBMIT_PASSWORD ) try { val rawCommandResult = CommandDispatcher.submitSilentReturningFuture(command).get() return@withContext when (val result = rawCommandResult.checkAndWrapCommandResultType<SignUpSubmitPasswordCommandResult>()) { is SignUpCommandResult.Complete -> { SignUpResult.Complete( nextState = SignInContinuationState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ) ) } is SignUpCommandResult.AttributesRequired -> { SignUpResult.AttributesRequired( nextState = SignUpAttributesRequiredState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ), requiredAttributes = result.requiredAttributes.toListOfRequiredUserAttribute() ) } is SignUpCommandResult.InvalidPassword -> { SignUpSubmitPasswordError( errorType = ErrorTypes.INVALID_PASSWORD, error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId, subError = result.subError ) } is INativeAuthCommandResult.Redirect -> { SignUpSubmitPasswordError( errorType = ErrorTypes.BROWSER_REQUIRED, error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId ) } // This should be caught earlier in the flow, so throwing UnexpectedError is SignUpCommandResult.UsernameAlreadyExists -> { Logger.warn( TAG, result.correlationId, "Submit password received unexpected result: $result" ) SignUpSubmitPasswordError( error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId ) } // This should be caught earlier in the flow, so throwing UnexpectedError is INativeAuthCommandResult.InvalidUsername -> { Logger.warn( TAG, result.correlationId, "Submit password received unexpected result: $result" ) SignUpSubmitPasswordError( error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId ) } is INativeAuthCommandResult.UnknownError -> { Logger.warn( TAG, result.correlationId, "Submit password received unexpected result: $result" ) SignUpSubmitPasswordError( errorMessage = result.errorDescription, error = result.error, correlationId = result.correlationId, exception = result.exception ) } } } finally { StringUtil.overwriteWithNull(commandParameters.password) } } } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(continuationToken) parcel.writeString(correlationId) parcel.writeString(username) parcel.writeSerializable(config) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<SignUpPasswordRequiredState> { override fun createFromParcel(parcel: Parcel): SignUpPasswordRequiredState { return SignUpPasswordRequiredState(parcel) } override fun newArray(size: Int): Array<SignUpPasswordRequiredState?> { return arrayOfNulls(size) } } } /** * Native Auth uses a state machine to denote state of and transitions within a flow. * SignUpAttributesRequiredState class represents a state where the user has to provide signup * attributes to progress in the signup flow. * @property continuationToken: Continuation token to be passed in the next request * @property correlationId: Correlation ID taken from the previous API response and passed to the next request * @property username: Email address of the user * @property config Configuration used by Native Auth */ class SignUpAttributesRequiredState internal constructor( override val continuationToken: String, override val correlationId: String, private val username: String, private val config: NativeAuthPublicClientApplicationConfiguration ) : BaseState(continuationToken = continuationToken, correlationId = correlationId), State, Parcelable { private val TAG: String = SignUpAttributesRequiredState::class.java.simpleName constructor(parcel: Parcel) : this( continuationToken = parcel.readString() ?: "", correlationId = parcel.readString() ?: "UNSET", username = parcel.readString() ?: "", config = parcel.serializable<NativeAuthPublicClientApplicationConfiguration>() as NativeAuthPublicClientApplicationConfiguration ) interface SignUpSubmitUserAttributesCallback : Callback<SignUpSubmitAttributesResult> /** * Submits the user attributes required to the server; callback variant. * * @param attributes mandatory attributes set in the tenant configuration. Should use [com.microsoft.identity.nativeauth.UserAttributes] to convert to a map. * @param callback [com.microsoft.identity.nativeauth.statemachine.states.SignUpAttributesRequiredState.SignUpSubmitUserAttributesCallback] to receive the result on. * @return The results of the submit user attributes action. */ fun submitAttributes( attributes: UserAttributes, callback: SignUpSubmitUserAttributesCallback ) { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.submitAttributes" ) NativeAuthPublicClientApplication.pcaScope.launch { try { val result = submitAttributes(attributes) callback.onResult(result) } catch (e: MsalException) { Logger.error(TAG, "Exception thrown in submitAttributes", e) callback.onError(e) } } } /** * Submits the user attributes required to the server; Kotlin coroutines variant. * * @param attributes mandatory attributes set in the tenant configuration. Should use [com.microsoft.identity.nativeauth.UserAttributes] to convert to a map. * @return The results of the submit user attributes action. */ suspend fun submitAttributes(attributes: UserAttributes): SignUpSubmitAttributesResult { LogSession.logMethodCall( tag = TAG, correlationId = correlationId, methodName = "${TAG}.submitAttributes(attributes: UserAttributes)" ) return withContext(Dispatchers.IO) { val commandParameters = CommandParametersAdapter.createSignUpStarSubmitUserAttributesCommandParameters( config, config.oAuth2TokenCache, continuationToken, correlationId, attributes.toMap() ) val command = SignUpSubmitUserAttributesCommand( commandParameters, NativeAuthMsalController(), PublicApiId.NATIVE_AUTH_SIGN_UP_SUBMIT_ATTRIBUTES ) val rawCommandResult = CommandDispatcher.submitSilentReturningFuture(command).get() return@withContext when (val result = rawCommandResult.checkAndWrapCommandResultType<SignUpSubmitUserAttributesCommandResult>()) { is SignUpCommandResult.AttributesRequired -> { SignUpResult.AttributesRequired( nextState = SignUpAttributesRequiredState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ), requiredAttributes = result.requiredAttributes.toListOfRequiredUserAttribute() ) } is SignUpCommandResult.Complete -> { SignUpResult.Complete( nextState = SignInContinuationState( continuationToken = result.continuationToken, correlationId = result.correlationId, username = username, config = config ) ) } is SignUpCommandResult.InvalidAttributes -> { SignUpSubmitAttributesError( errorType = SignUpErrorTypes.INVALID_ATTRIBUTES, error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId ) } is INativeAuthCommandResult.Redirect -> { SignUpSubmitAttributesError( errorType = ErrorTypes.BROWSER_REQUIRED, error = result.error, errorMessage = result.errorDescription, correlationId = result.correlationId ) } // This should be caught earlier in the flow, so throwing UnexpectedError is SignUpCommandResult.UsernameAlreadyExists -> { Logger.warn( TAG, result.correlationId, "Submit attributes received unexpected result: $result" ) SignUpSubmitAttributesError( errorMessage = result.errorDescription, error = result.error, correlationId = result.correlationId ) } is INativeAuthCommandResult.UnknownError -> { Logger.warn( TAG, result.correlationId, "Submit attributes received unexpected result: $result" ) SignUpSubmitAttributesError( errorMessage = result.errorDescription, error = result.error, correlationId = result.correlationId, exception = result.exception ) } } } } override fun writeToParcel(parcel: Parcel, flags: Int) { parcel.writeString(continuationToken) parcel.writeString(correlationId) parcel.writeString(username) parcel.writeSerializable(config) } override fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<SignUpAttributesRequiredState> { override fun createFromParcel(parcel: Parcel): SignUpAttributesRequiredState { return SignUpAttributesRequiredState(parcel) } override fun newArray(size: Int): Array<SignUpAttributesRequiredState?> { return arrayOfNulls(size) } } }
69
Java
124
214
d2deec34dfde6ea445309af3621f5642ea184881
31,905
microsoft-authentication-library-for-android
MIT License
plugins/toolkit/jetbrains-rider/src-241+/software/aws/toolkits/jetbrains/services/lambda/dotnet/DotNetSamProjectGeneratorRoot.kt
aws
91,485,909
false
null
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.lambda.dotnet import com.intellij.openapi.ui.DialogPanel import com.intellij.openapi.ui.ValidationInfo import com.intellij.ui.dsl.builder.Align import com.intellij.ui.dsl.builder.panel import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rider.model.RdProjectTemplate import com.jetbrains.rider.projectView.projectTemplates.NewProjectDialogContext import com.jetbrains.rider.projectView.projectTemplates.ProjectTemplatesSharedModel import com.jetbrains.rider.projectView.projectTemplates.StatusMessageType import com.jetbrains.rider.projectView.projectTemplates.StatusMessages import com.jetbrains.rider.projectView.projectTemplates.generators.ProjectTemplateGeneratorBase import software.aws.toolkits.jetbrains.services.lambda.BuiltInRuntimeGroups import software.aws.toolkits.jetbrains.services.lambda.RuntimeGroup import software.aws.toolkits.jetbrains.services.lambda.wizard.SamInitSelectionPanel import software.aws.toolkits.jetbrains.services.lambda.wizard.SamProjectGenerator import software.aws.toolkits.jetbrains.utils.DotNetRuntimeUtils import javax.swing.JComponent abstract class DotNetSamProjectGeneratorRoot( lifetime: Lifetime, private val context: NewProjectDialogContext, sharedModel: ProjectTemplatesSharedModel, ) : ProjectTemplateGeneratorBase( lifetime, context, sharedModel, createProject = true ) { companion object { private const val SAM_HELLO_WORLD_PROJECT_NAME = "HelloWorld" } override val defaultName = SAM_HELLO_WORLD_PROJECT_NAME // TODO: Decouple SamProjectGenerator from the framework wizards so we can re-use its panels private val generator = SamProjectGenerator() private val samPanel = SamInitSelectionPanel( generator.wizardFragments, // Only show templates for DotNet in Rider runtimeFilter = { RuntimeGroup.getById(BuiltInRuntimeGroups.Dotnet).supportedRuntimes.contains(it) }, // needed to rerun the validation when the wizard is changed wizardUpdateCallback = { validateData() } ) fun getSamPanel() = samPanel fun getSamGenerator() = generator init { /** * The project name is generated inside SAM CLI generator and cannot be re-defined via parameters. * Hardcode the project name to the generated one - "HelloWorld". */ projectNameProperty.set(SAM_HELLO_WORLD_PROJECT_NAME) sameDirectoryProperty.set(false) initSamPanel() } override fun getComponent(): JComponent { val component = super.getComponent() projectNameTextField?.component?.isEnabled = false sameDirectoryCheckbox?.component?.isEnabled = false return component } override fun createTemplateSpecificPanel(): DialogPanel { val panel = panel { row { cell(samPanel.mainPanel).align(Align.FILL).resizableColumn() }.resizableRow() } validateData() return panel } override fun checkIsAbleToExpand(template: RdProjectTemplate?, validations: Map<JComponent, ValidationInfo>) { // we don't care about template here. canExpand.set(validations.isEmpty()) } private fun validateData() { // first validateData comes from SamInitSelectionPanel constructor, so is null... @Suppress("UNNECESSARY_SAFE_CALL") samPanel?.validate()?.let { context.statusMessages.add(StatusMessages.Error(it.message)) return } context.statusMessages.removeIf { it.type == StatusMessageType.Error } } private fun initSamPanel() { samPanel.setRuntime(DotNetRuntimeUtils.getCurrentDotNetCoreRuntime()) } }
519
null
220
757
a81caf64a293b59056cef3f8a6f1c977be46937e
3,825
aws-toolkit-jetbrains
Apache License 2.0
domain/src/main/java/com/hanyeop/domain/usecase/album/UpdateAlbumUseCase.kt
HanYeop
486,591,905
false
null
package com.hanyeop.domain.usecase.album import com.hanyeop.domain.repository.AlbumRepository import javax.inject.Inject class UpdateAlbumUseCase @Inject constructor(private val albumRepository: AlbumRepository) { fun execute(id: Int, title: String, artist: String, genre: String, rating: Float, summary: String, content: String) = albumRepository.updateAlbum(id, title, artist, genre, rating, summary, content) }
0
Kotlin
0
5
e40550f67be100f61607eb201397ff1559fc6cc1
427
Memory-of-Music-android
Apache License 2.0
compiler/testData/diagnostics/tests/controlFlowAnalysis/smartCastInCatch.fir.kt
JetBrains
3,432,266
false
null
// SKIP_TXT // DUMP_CFG import kotlin.reflect.KClass fun exc(flag: Boolean) { if (flag) throw RuntimeException() } fun Any.notNull() = toString() fun test(flag: Boolean) { var x: Any? x = "" try { x = null exc(flag) x = 1 exc(!flag) x = "" } catch (e: Throwable) { // all bad - could come here from either call x.<!UNRESOLVED_REFERENCE!>length<!> x.<!UNRESOLVED_REFERENCE!>inc<!>() } } fun testGetClassThrows() { var x: KClass<String>? = String::class x as KClass<String> try { x = null x = String::class } catch (e: Throwable) { // bad - get class call can throw x<!UNSAFE_CALL!>.<!>notNull() } } fun testMemberReferenceThrows() { var x: Any? = "" x as Any try { x = null x = String::length } catch (ex: Throwable) { // bad - get callable reference throw x<!UNSAFE_CALL!>.<!>notNull() } } fun testExceptionBeforeLambda() { var x: String? = "" x as String try { x = null run { x = "" } } catch (ex: Throwable) { // bad - `run` could throw before running lambda x<!UNSAFE_CALL!>.<!>notNull() } } fun testExceptionWithinLocalFunction() { var x: Any = "" x as String try { fun local() { x = 1 } } catch (e: Exception) { // bad - `local` could be run and reset smartcasting x.<!UNRESOLVED_REFERENCE!>length<!> } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,526
kotlin
Apache License 2.0
app/src/main/java/com/replica/replicaisland/ChannelSystem.kt
jimandreas
290,957,495
false
null
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.replica.replicaisland import java.util.* class ChannelSystem : BaseObject() { private val mChannels: FixedSizeArray<Channel> private val mSearchDummy: Channel private var mRegisteredChannelCount: Int override fun reset() { for (x in 0 until CHANNEL_COUNT) { mChannels[x]!!.name = null mChannels[x]!!.value = null } mRegisteredChannelCount = 0 } fun registerChannel(name: String?): Channel? { var result: Channel? = null mSearchDummy.name = name val index = mChannels.find(mSearchDummy, false) if (index == -1) { // Add a new channel. // TODO: assert(mRegisteredChannelCount < CHANNEL_COUNT) { "Channel pool exhausted!" } if (mRegisteredChannelCount < CHANNEL_COUNT) { result = mChannels[mRegisteredChannelCount] mRegisteredChannelCount++ result!!.name = name mChannels.sort(true) } } else { result = mChannels[index] } return result } class Channel { var name: String? = null @JvmField var value: Any? = null } class ChannelFloatValue { @JvmField var value = 0f } class ChannelBooleanValue { @JvmField var value = false } /** Comparator for channels. */ private class ChannelComparator : Comparator<Channel?> { override fun compare(object1: Channel?, object2: Channel?): Int { var result = 0 if (object1 == null && object2 != null) { result = 1 } else if (object1 != null && object2 == null) { result = -1 } else if (object1 != null && object2 != null) { if (object1.name == null && object2.name != null) { result = 1 } else if (object1.name != null && object2.name == null) { result = -1 } else if (object1.name != null && object2.name != null) { result = object1.name!!.compareTo(object2.name!!) } } return result } } companion object { private const val CHANNEL_COUNT = 8 private val sChannelComparator = ChannelComparator() } init { mChannels = FixedSizeArray(CHANNEL_COUNT) mChannels.setComparator(sChannelComparator) mSearchDummy = Channel() for (x in 0 until CHANNEL_COUNT) { mChannels.add(Channel()) } mRegisteredChannelCount = 0 } }
0
Kotlin
1
3
4a303601d526374cb419ee664eb14ed9868175ac
3,267
ReplicaIslandKotlin
Apache License 2.0
app/src/main/java/org/vmaier/coderswag/controller/ProductsActivity.kt
vlmaier
202,518,175
false
null
package org.vmaier.coderswag.controller import android.content.res.Configuration import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.GridLayoutManager import org.vmaier.coderswag.R import org.vmaier.coderswag.adapters.ProductAdapter import org.vmaier.coderswag.databinding.ActivityProductsBinding import org.vmaier.coderswag.services.DataService import org.vmaier.coderswag.utilities.EXTRA_CATEGORY class ProductsActivity : AppCompatActivity() { lateinit var adapter : ProductAdapter private lateinit var binding: ActivityProductsBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_products) binding = ActivityProductsBinding.inflate(layoutInflater) val category = intent.getStringExtra(EXTRA_CATEGORY) adapter = ProductAdapter(this, DataService.getProducts(category)) binding.productListView.adapter = adapter val orientation = resources.configuration.orientation val screenSize = resources.configuration.screenWidthDp var spanCount = if (orientation == Configuration.ORIENTATION_LANDSCAPE) 3 else 2 if (screenSize > 720) { spanCount = 3 } val layoutManager = GridLayoutManager(this, spanCount) binding.productListView.layoutManager = layoutManager binding.productListView.setHasFixedSize(true) } }
0
Kotlin
0
0
19d3d9ac99bf10871c00a10398f1de949567976f
1,484
coder-swag
The Unlicense
src/test/kotlin/ru/mail/im/motli/processor/PaletteProcessorTest.kt
mail-ru-im
176,909,552
false
null
package ru.mail.im.motli.processor import org.junit.Assert.* import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import ru.mail.im.motli.config.AppConfig import ru.mail.im.motli.config.AppConfigDto import ru.mail.im.motli.resource.ThemeSet import java.nio.charset.StandardCharsets class PaletteProcessorTest { @get:Rule var tmpFolder = TemporaryFolder() lateinit var config: AppConfig @Before fun setUp() { val paletteFile = tmpFolder.newFile() paletteFile.writeText(""" { "version": 1, "themes": { "green": { "primary": "#FF00FF", "secondary": "#00FF00" }, "blue": { "primary": "#AABBCC", "secondary": "#CCBBAA" } } } """.trimIndent(), StandardCharsets.UTF_8) config = AppConfig(paletteFile.parentFile, AppConfigDto(null, paletteFile.name, null, listOf("green", "blue"), null)) } @Test fun fill() { val themes = ThemeSet(config) PaletteProcessor(config).fill(themes) var theme = themes.getTheme("green") assertEquals(2, theme.colors.size) assertEquals("primary", theme.colors[0].name) assertEquals("#FF00FF", theme.colors[0].value) assertEquals("secondary", theme.colors[1].name) assertEquals("#00FF00", theme.colors[1].value) theme = themes.getTheme("blue") assertEquals(2, theme.colors.size) assertEquals("primary", theme.colors[0].name) assertEquals("#AABBCC", theme.colors[0].value) assertEquals("secondary", theme.colors[1].name) assertEquals("#CCBBAA", theme.colors[1].value) } }
0
Kotlin
1
5
f1ee6fafbb8d84ec8bff2a9de0adac69df4b4fc6
1,943
motli
MIT License
PreferencesManager/src/main/kotlin/fr/simon/marquis/preferencesmanager/model/BackupContainer.kt
LossyDragon
158,134,761
true
{"Kotlin": 200691}
/* * Copyright (C) 2013 <NAME> (http://www.simon-marquis.fr) * * 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 fr.simon.marquis.preferencesmanager.model import java.text.DateFormat import java.util.Date data class BackupContainer( val pkgName: String, val backupList: MutableList<BackupContainerInfo> ) data class BackupContainerInfo( val backupDate: String, // Date of backup from millis val backupFile: String, // The path of the backup file val backupXmlName: String, // The xml file of the package backup val size: Long // Size of the file ) { fun timeSinceBackup(): String { val date = Date().apply { time = backupDate.toLong() } return DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.MEDIUM).format(date) } }
0
Kotlin
1
4
c86fcce7fd501edad48ea5bb9c72648d06d345ea
1,316
Android-PreferencesManager
Apache License 2.0
app/src/main/java/com/example/android/databinding/basicsample/ui/SolutionActivity.kt
josh-vega
175,691,113
false
null
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.databinding.basicsample.ui import android.arch.lifecycle.ViewModelProviders import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.example.android.databinding.basicsample.R import com.example.android.databinding.basicsample.data.SimpleViewModelSolution import com.example.android.databinding.basicsample.databinding.SolutionBinding /** * Final codelab solution. */ class SolutionActivity : AppCompatActivity() { // Obtain ViewModel from ViewModelProviders private val viewModel by lazy { ViewModelProviders.of(this).get(SimpleViewModelSolution::class.java) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: SolutionBinding = DataBindingUtil.setContentView(this, R.layout.solution) binding.viewmodel = viewModel } }
0
Kotlin
0
0
671193a5daefcfddaad21676fe1bd19765af69b8
1,561
android-databinding-master
Apache License 2.0
src/test/kotlin/no/nb/bikube/newspaper/controller/TitleControllerTest.kt
NationalLibraryOfNorway
694,135,748
false
null
package no.nb.bikube.newspaper.controller import com.ninjasquad.springmockk.MockkBean import io.mockk.Called import io.mockk.every import io.mockk.verify import no.nb.bikube.core.exception.BadRequestBodyException import no.nb.bikube.core.exception.RecordAlreadyExistsException import no.nb.bikube.core.model.Language import no.nb.bikube.core.model.Publisher import no.nb.bikube.core.model.PublisherPlace import no.nb.bikube.newspaper.NewspaperMockData.Companion.newspaperTitleInputDtoMockA import no.nb.bikube.newspaper.NewspaperMockData.Companion.newspaperTitleMockA import no.nb.bikube.newspaper.service.CollectionsService import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.ActiveProfiles import reactor.core.publisher.Mono import reactor.kotlin.test.test import java.time.LocalDate @SpringBootTest @ActiveProfiles("test") class TitleControllerTest { @Autowired private lateinit var titleController: TitleController @MockkBean private lateinit var collectionsService: CollectionsService @Test fun `createTitle should return 200 OK with the created title`() { every { collectionsService.createPublisher(any()) } returns Mono.empty() every { collectionsService.createPublisherPlace(any()) } returns Mono.empty() every { collectionsService.createLanguage(any()) } returns Mono.empty() every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } @Test fun `createTitle should return 400 bad request if request body object title is null or empty`() { titleController.createTitle(newspaperTitleInputDtoMockA.copy(name = null)) .test() .expectErrorMatches { it is BadRequestBodyException && it.message == "Title name cannot be null or empty" } .verify() titleController.createTitle(newspaperTitleInputDtoMockA.copy(name = "")) .test() .expectErrorMatches { it is BadRequestBodyException && it.message == "Title name cannot be null or empty" } .verify() } @Test fun `createTitle should return BadRequestBodyException if startDate is after endDate`() { val startDate = LocalDate.of(2020, 1, 1) val endDate = LocalDate.of(2019, 1, 1) titleController.createTitle(newspaperTitleInputDtoMockA.copy(startDate = startDate, endDate = endDate)) .test() .expectErrorMatches { it is BadRequestBodyException && it.message == "Start date cannot be after end date" } .verify() } @Test fun `createTitle should call create publisher if publisher is present on request body`() { every { collectionsService.createPublisher(any()) } returns Mono.just(Publisher("Pub", "1")) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA.copy(publisher = "Pub", publisherPlace = null)) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } @Test fun `createTitle should call createPublisherPlace if publisherPlace is present on request body`() { every { collectionsService.createPublisherPlace(any()) } returns Mono.just(PublisherPlace("Pub", "1")) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA.copy(publisherPlace = "Pub")) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } @Test fun `createTitle should call createLanguage if language is present on request body`() { every { collectionsService.createLanguage(any()) } returns Mono.just(Language("nob", "1")) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA.copy(language = "nob", publisherPlace = null)) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } @Test fun `createTitle should not call on createPublisher, createPublisherPlace or createLanguage if not present on request body`() { val titleInput = newspaperTitleInputDtoMockA.copy(publisher = null, publisherPlace = null, language = null) val title = newspaperTitleMockA.copy(publisher = null, publisherPlace = null, language = null) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(title) titleController.createTitle(titleInput) .test() .expectSubscription() .assertNext { Assertions.assertEquals(title, it.body) } .verifyComplete() verify { collectionsService.createPublisher(any()) wasNot Called } verify { collectionsService.createPublisherPlace(any()) wasNot Called } verify { collectionsService.createLanguage(any()) wasNot Called } } @Test fun `createTitle should continue when createPublisher receives a 409 conflict`() { every { collectionsService.createPublisher(any()) } returns Mono.error( RecordAlreadyExistsException("Publisher place 'Schibsted' already exists") ) every { collectionsService.createPublisherPlace(any()) } returns Mono.just(PublisherPlace("Oslo", "1")) every { collectionsService.createLanguage(any()) } returns Mono.just(Language("nob", "1")) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA.copy(publisher = "Schibsted")) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } @Test fun `createTitle should continue when createPublisherPlace receives a 409 conflict`() { every { collectionsService.createPublisher(any()) } returns Mono.just(Publisher("Schibsted", "1")) every { collectionsService.createPublisherPlace(any()) } returns Mono.error( RecordAlreadyExistsException("Publisher place 'Oslo' already exists") ) every { collectionsService.createLanguage(any()) } returns Mono.just(Language("nob", "1")) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA.copy(publisherPlace = "Oslo")) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } @Test fun `createTitle should continue when createLanguage receives a 409 conflict`() { every { collectionsService.createPublisher(any()) } returns Mono.just(Publisher("Schibsted", "1")) every { collectionsService.createPublisherPlace(any()) } returns Mono.just(PublisherPlace("Oslo", "1")) every { collectionsService.createLanguage(any()) } returns Mono.error( RecordAlreadyExistsException("Language 'nob' already exists") ) every { collectionsService.createNewspaperTitle(any()) } returns Mono.just(newspaperTitleMockA.copy()) titleController.createTitle(newspaperTitleInputDtoMockA.copy(language = "nob")) .test() .expectSubscription() .assertNext { Assertions.assertEquals(newspaperTitleMockA, it.body) } .verifyComplete() } }
2
null
0
3
1b5c81e1450c8467922df7065bdedf06b6106699
8,586
bikube
Apache License 2.0
apollo-compiler/src/test/graphql/com/example/arguments_simple/TestQuery.kt
apollostack
69,469,299
false
null
// AUTO-GENERATED FILE. DO NOT MODIFY. // // This class was automatically generated by Apollo GraphQL plugin from the GraphQL queries it found. // It should not be modified by hand. // package com.example.arguments_simple import com.apollographql.apollo.api.Input import com.apollographql.apollo.api.Operation import com.apollographql.apollo.api.OperationName import com.apollographql.apollo.api.Query import com.apollographql.apollo.api.Response import com.apollographql.apollo.api.ResponseField import com.apollographql.apollo.api.ScalarTypeAdapters import com.apollographql.apollo.api.ScalarTypeAdapters.DEFAULT import com.apollographql.apollo.api.internal.InputFieldMarshaller import com.apollographql.apollo.api.internal.QueryDocumentMinifier import com.apollographql.apollo.api.internal.ResponseFieldMapper import com.apollographql.apollo.api.internal.ResponseFieldMarshaller import com.apollographql.apollo.api.internal.ResponseReader import com.apollographql.apollo.api.internal.SimpleOperationResponseParser import com.example.arguments_simple.fragment.HeroDetails import com.example.arguments_simple.type.Episode import java.io.IOException import kotlin.Any import kotlin.Array import kotlin.Boolean import kotlin.Int import kotlin.String import kotlin.Suppress import kotlin.collections.List import kotlin.collections.Map import kotlin.jvm.Throws import kotlin.jvm.Transient import okio.BufferedSource @Suppress("NAME_SHADOWING", "UNUSED_ANONYMOUS_PARAMETER", "LocalVariableName", "RemoveExplicitTypeArguments", "NestedLambdaShadowedImplicitParameter") data class TestQuery( val episode: Input<Episode> = Input.absent(), val includeName: Boolean, val friendsCount: Int, val listOfListOfStringArgs: List<List<String?>> ) : Query<TestQuery.Data, TestQuery.Data, Operation.Variables> { @Transient private val variables: Operation.Variables = object : Operation.Variables() { override fun valueMap(): Map<String, Any?> = mutableMapOf<String, Any?>().apply { if (episode.defined) this["episode"] = this@TestQuery.episode.value this["IncludeName"] = this@TestQuery.includeName this["friendsCount"] = this@TestQuery.friendsCount this["listOfListOfStringArgs"] = this@TestQuery.listOfListOfStringArgs } override fun marshaller(): InputFieldMarshaller = InputFieldMarshaller { writer -> if (this@TestQuery.episode.defined) { writer.writeString("episode", this@TestQuery.episode.value?.rawValue) } writer.writeBoolean("IncludeName", this@TestQuery.includeName) writer.writeInt("friendsCount", this@TestQuery.friendsCount) writer.writeList("listOfListOfStringArgs") { listItemWriter -> this@TestQuery.listOfListOfStringArgs.forEach { value -> listItemWriter.writeList { listItemWriter -> value.forEach { value -> listItemWriter.writeString(value) } } } } } } override fun operationId(): String = OPERATION_ID override fun queryDocument(): String = QUERY_DOCUMENT override fun wrapData(data: Data?): Data? = data override fun variables(): Operation.Variables = variables override fun name(): OperationName = OPERATION_NAME override fun responseFieldMapper(): ResponseFieldMapper<Data> = ResponseFieldMapper { Data(it) } @Throws(IOException::class) override fun parse(source: BufferedSource, scalarTypeAdapters: ScalarTypeAdapters): Response<Data> = SimpleOperationResponseParser.parse(source, this, scalarTypeAdapters) @Throws(IOException::class) override fun parse(source: BufferedSource): Response<Data> = parse(source, DEFAULT) data class Hero( val __typename: String = "Character", /** * The name of the character */ val name: String?, val fragments: Fragments ) { fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller { writer -> writer.writeString(RESPONSE_FIELDS[0], this@Hero.__typename) writer.writeString(RESPONSE_FIELDS[1], this@Hero.name) this@Hero.fragments.marshaller().marshal(writer) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forString("__typename", "__typename", null, false, null), ResponseField.forString("name", "name", null, true, listOf( ResponseField.Condition.booleanCondition("IncludeName", false) )), ResponseField.forString("__typename", "__typename", null, false, null) ) operator fun invoke(reader: ResponseReader): Hero = reader.run { val __typename = readString(RESPONSE_FIELDS[0]) val name = readString(RESPONSE_FIELDS[1]) val fragments = Fragments(reader) Hero( __typename = __typename, name = name, fragments = fragments ) } } data class Fragments( val heroDetails: HeroDetails ) { fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller { writer -> writer.writeFragment(this@Fragments.heroDetails.marshaller()) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forFragment("__typename", "__typename", listOf( ResponseField.Condition.typeCondition(arrayOf("Human", "Droid")) )) ) operator fun invoke(reader: ResponseReader): Fragments = reader.run { val heroDetails = readFragment<HeroDetails>(RESPONSE_FIELDS[0]) { reader -> HeroDetails(reader) } Fragments( heroDetails = heroDetails ) } } } } data class HeroWithReview( val __typename: String = "Human", /** * What this human calls themselves */ val name: String ) { fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller { writer -> writer.writeString(RESPONSE_FIELDS[0], this@HeroWithReview.__typename) writer.writeString(RESPONSE_FIELDS[1], this@HeroWithReview.name) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forString("__typename", "__typename", null, false, null), ResponseField.forString("name", "name", null, false, null) ) operator fun invoke(reader: ResponseReader): HeroWithReview = reader.run { val __typename = readString(RESPONSE_FIELDS[0]) val name = readString(RESPONSE_FIELDS[1]) HeroWithReview( __typename = __typename, name = name ) } } } data class Data( val hero: Hero?, val heroWithReview: HeroWithReview? ) : Operation.Data { override fun marshaller(): ResponseFieldMarshaller = ResponseFieldMarshaller { writer -> writer.writeObject(RESPONSE_FIELDS[0], this@Data.hero?.marshaller()) writer.writeObject(RESPONSE_FIELDS[1], this@Data.heroWithReview?.marshaller()) } companion object { private val RESPONSE_FIELDS: Array<ResponseField> = arrayOf( ResponseField.forObject("hero", "hero", mapOf<String, Any>( "episode" to mapOf<String, Any>( "kind" to "Variable", "variableName" to "episode"), "listOfListOfStringArgs" to mapOf<String, Any>( "kind" to "Variable", "variableName" to "listOfListOfStringArgs")), true, null), ResponseField.forObject("heroWithReview", "heroWithReview", mapOf<String, Any>( "episode" to mapOf<String, Any>( "kind" to "Variable", "variableName" to "episode"), "review" to emptyMap<String, Any>()), true, null) ) operator fun invoke(reader: ResponseReader): Data = reader.run { val hero = readObject<Hero>(RESPONSE_FIELDS[0]) { reader -> Hero(reader) } val heroWithReview = readObject<HeroWithReview>(RESPONSE_FIELDS[1]) { reader -> HeroWithReview(reader) } Data( hero = hero, heroWithReview = heroWithReview ) } } } companion object { const val OPERATION_ID: String = "89afe30dd0fa5ddce3d0b743d3adf68e55a48d0c11d10e495c0ec095949e6d04" val QUERY_DOCUMENT: String = QueryDocumentMinifier.minify( """ |query TestQuery(${'$'}episode: Episode, ${'$'}IncludeName: Boolean!, ${'$'}friendsCount: Int!, ${'$'}listOfListOfStringArgs: [[String]!]!) { | hero(episode: ${'$'}episode, listOfListOfStringArgs: ${'$'}listOfListOfStringArgs) { | __typename | name @include(if: ${'$'}IncludeName) | ...HeroDetails | } | heroWithReview(episode: ${'$'}episode, review: {}) { | __typename | name | } |} |fragment HeroDetails on Character { | __typename | friendsConnection(first: ${'$'}friendsCount) { | __typename | totalCount | edges { | __typename | node { | __typename | name @include(if: ${'$'}IncludeName) | } | } | } |} """.trimMargin() ) val OPERATION_NAME: OperationName = OperationName { "TestQuery" } } }
5
null
531
2,897
f16ef0f4020af7a07c200f0fdcf1dac977d63637
9,383
apollo-android
MIT License
app/src/main/java/com/example/multilivedata/ui/news/NewsViewModel.kt
mhdatie
128,706,323
false
{"Kotlin": 32588}
package com.example.multilivedata.ui.news import android.arch.lifecycle.LiveData import android.arch.lifecycle.MutableLiveData import android.arch.lifecycle.Transformations import com.example.multilivedata.network.common.Response import com.example.multilivedata.network.common.ResponseStatus import com.example.multilivedata.network.nytimes.common.CategoryDef import com.example.multilivedata.network.nytimes.mostpopular.MostPopularListing import com.example.multilivedata.network.nytimes.mostpopular.NytMostPopularService import retrofit2.Call import retrofit2.Callback import javax.inject.Inject typealias NewsResponse = Response<MostPopularListing> typealias RetrofitResponse = retrofit2.Response<NewsResponse> @NewsScope class NewsViewModel @Inject constructor(private val apiClient: NytMostPopularService) { private val news = MutableLiveData<NewsResponse>() var newsFilter = NewsFilter() // default filter val listing: LiveData<MostPopularListing> = Transformations.map(news, NewsResponse::data) val responseStatus: LiveData<ResponseStatus> = Transformations.map(news, NewsResponse::responseStatus) fun fetchNews() { performCall() } fun fetchNews(filter: NewsFilter) { newsFilter = filter performCall() } private fun performCall() { val call = when (newsFilter.category) { CategoryDef.MOST_EMAILED -> apiClient.getMostEmailed(newsFilter.section, newsFilter.timePeriod) CategoryDef.MOST_SHARED -> apiClient.getMostShared(newsFilter.section, newsFilter.timePeriod) CategoryDef.MOST_VIEWED -> apiClient.getMostViewed(newsFilter.section, newsFilter.timePeriod) else -> null } ?: return news.value = Response.isLoading() call.enqueue(object : Callback<NewsResponse> { override fun onResponse(call: Call<NewsResponse>?, response: RetrofitResponse?) { val responseBody = response?.body() ?: return news.postValue(responseBody) } override fun onFailure(call: Call<NewsResponse>?, t: Throwable?) { news.postValue(Response.hasFailed(t)) } }) } fun mapToNewsItem(it: MostPopularListing): List<NewsItem> = it.results.map { val imgUrl = it.media.firstOrNull()?.metadata?.lastOrNull()?.url ?: "" NewsItem(it.title, imgUrl, it.url) } }
0
Kotlin
0
0
15b2cdee8da8226723ec2f5076ef0ce13e625ee1
2,435
WeatherNewsMvvm
MIT License
cams-module-publis/src/main/java/com/linwei/cams/module/publis/ui/publis/view/PublisView.kt
WeiShuaiDev
390,640,743
false
null
package com.linwei.cams.module.publis.ui.publis.view import com.linwei.cams.component.mvvm.mvvm.view.MvvmView import com.linwei.cams.module.publis.ui.publis.viewmodel.PublisViewModel interface PublisView: MvvmView<PublisViewModel> { }
0
Kotlin
0
3
37ffb7142ce1141c7b09ef69664c535150d25aaa
236
CamsModular
Apache License 2.0
ee-design_ui_des_asm/src/main/kotlin/ee/design/ui/des/AsmDesExt.kt
eugeis
80,671,314
false
null
package ee.design.ui.des import ee.common.ext.toCamelCase import ee.lang.GenerationContext import ee.lang.nL import ee.lang.tab import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.FieldNode fun ClassNode.toDesEnum(context: GenerationContext, indent: String = ""): String { val newIndent = "$indent${tab}" val fieldDesc = "L$name;" return """${indent}object ${name.substringAfterLast("/")} : EnumType() { ${fields.filter { it.desc.equals(fieldDesc) }.joinToString(nL) { it.toDesLit(context, newIndent) }} $indent}""" } fun ClassNode.toDesWidget(context: GenerationContext, indent: String = ""): String { val newIndent = "$indent${tab}" return """${indent}object ${name.substringAfterLast("/")} : Widget() { ${fields.filter { !it.name.startsWith("$") && !it.name.startsWith("_") }.joinToString(nL) { it.toDesProp(context, newIndent) }} $indent}""" } fun FieldNode.toDesLit(context: GenerationContext, indent: String = ""): String { return """${indent}val ${name.toLowerCase().toCamelCase().capitalize()} = lit()""" } fun FieldNode.toDesProp(context: GenerationContext, indent: String = ""): String { return """${indent}val ${name} = prop()""" }
0
Kotlin
0
0
b51b29d3ca4c48592b29f700c4ea6510a0298929
1,206
ee
Apache License 2.0
urlparser/src/commonMain/kotlin/com/nevermindsoftware/urlparser/tld/TLDSource.kt
jamesphilipps
274,070,170
false
{"Kotlin": 34879, "Shell": 600}
package com.nevermindsoftware.urlparser.tld import com.nevermindsoftware.urlparser.SuffixRule /** * Interface specifying a provider of TLD SuffixRules. It should return a list of SuffixRules. Caching is down to the * implementation and is not required, but the TLDSource will be queried on each usage of the parse methods of a UrlParser */ interface TLDSource { /** * Get a list of TLD suffix rules as per the Mozilla Suffix List specifications */ fun get(): List<SuffixRule> } expect class ClasspathTLDSource : TLDSource { }
0
Kotlin
5
3
53a0ca261849e971a8ccbf288bdeb05ec0cbf58b
551
urlparser
MIT License