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
daogenerator/src/main/kotlin/se/plilja/springdaogen/engine/dao/ViewQueryableGenerator.kt
plilja
164,498,962
false
null
package se.plilja.springdaogen.engine.dao import org.springframework.beans.factory.annotation.Autowired import org.springframework.jdbc.core.RowMapper import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate import org.springframework.stereotype.Repository import se.plilja.springdaogen.config.Config import se.plilja.springdaogen.copyable.columnClass import se.plilja.springdaogen.copyable.queryable import se.plilja.springdaogen.engine.model.Left import se.plilja.springdaogen.engine.model.View import se.plilja.springdaogen.engine.sql.* import se.plilja.springdaogen.syntaxgenerator.ClassGenerator import se.plilja.springdaogen.util.snakeCase import java.math.BigDecimal import java.sql.Blob import java.sql.Clob import java.sql.NClob import java.time.OffsetDateTime import java.util.* import kotlin.collections.ArrayList fun generateViewQueryable(config: Config, view: View): ClassGenerator { println("Generating queryable for view '${view.name}', queryable will be named '${view.queryableName()}'.") val g = ClassGenerator(view.queryableName(), config.daoOutputPackage, config.daoOutputFolder) if (!config.daosAreAbstract) { g.addClassAnnotation("@Repository") g.addImport(Repository::class.java) } g.extends = "Queryable<${view.entityName()}>" val columnsConstantNames = ArrayList<String>() for (column in view.columns) { val type = column.type() when (type) { is Left -> { if (!type.value.packageName.contains("java.lang")) { g.addImport(type.value) } } } val name = "COLUMN_${snakeCase(column.name).toUpperCase()}" val (columnTypeDecl, init) = columnConstantInitializer(view, column, config) g.addConstant( name, columnTypeDecl, init ) columnsConstantNames.add(name) } g.addImport(Arrays::class.java) g.addImport(java.util.List::class.java) g.addConstant( "ALL_COLUMNS_LIST", "List<Column<${view.entityName()}, ?>>", "Arrays.asList(\n${columnsConstantNames.joinToString(",\n")})" ) g.addPrivateConstant("ALL_COLUMNS", "String", columnsList(view, config.databaseDialect)) g.addPrivateConstant( "ROW_MAPPER", "RowMapper<${view.entityName()}>", rowMapper(view, g, config) ) g.addImport(RowMapper::class.java) if (config.daosAreAbstract) { g.isAbstract = true } else { g.addImport(Autowired::class.java) } g.addCustomConstructor( """ @Autowired public ${g.name}(NamedParameterJdbcTemplate jdbcTemplate) { super(${view.entityName()}.class, jdbcTemplate); } """ ) g.addImport(NamedParameterJdbcTemplate::class.java) g.addCustomMethod( """ @Override protected RowMapper<${view.entityName()}> getRowMapper() { return ROW_MAPPER; } """ ) g.addCustomMethod( """ @Override protected String getSelectManySql(int maxSelectCount) { return String.format(${selectMany(view, config.databaseDialect)}, maxSelectCount); } """ ) g.addCustomMethod( """ @Override protected String getCountSql() { return ${count(view, config.databaseDialect)}; } """ ) g.addCustomMethod( """ @Override protected List<Column<${view.entityName()}, ?>> getColumnsList() { return ALL_COLUMNS_LIST; } """ ) g.addCustomMethod( """ @Override protected String getQueryOrderBySql(int maxAllowedCount, String whereClause, String orderBy) { return ${selectManyQuery(view, config.databaseDialect)}; } """ ) g.addCustomMethod( """ @Override protected String getQueryPageOrderBySql(long start, int pageSize, String whereClause, String orderBy) { return ${selectPageQuery(view, config.databaseDialect)} } """ ) g.addCustomMethod( """ @Override protected int getSelectAllDefaultMaxCount() { return ${config.maxSelectAllCount}; } """ ) val mayNeedImport = listOf( UUID::class.java, Clob::class.java, NClob::class.java, Blob::class.java, BigDecimal::class.java, OffsetDateTime::class.java ) for (column in view.columns) { if (column.rawType() in mayNeedImport) { g.addImport(column.rawType()) } } if (config.entityOutputPackage != config.daoOutputPackage) { g.addImport("${config.entityOutputPackage}.${view.entityName()}") } if (config.frameworkOutputPackage != config.daoOutputPackage) { ensureImported(g, config) { queryable(config.frameworkOutputPackage, config) } ensureImported(g, config) { columnClass(config.frameworkOutputPackage) } } return g }
1
null
1
1
e9ddf578c59eb83cd4ec29dddfd86e387adcfe71
5,253
spring-dao-codegen
MIT License
api/src/test/kotlin/pl/bas/microtwitter/controllers/AppControllerTest.kt
Humberd
105,806,448
false
{"YAML": 2, "Text": 1, "Ignore List": 3, "Groovy": 1, "Markdown": 3, "XML": 13, "JSON with Comments": 2, "JSON": 6, "Dockerfile": 4, "JavaScript": 2, "EditorConfig": 1, "HTML": 43, "SCSS": 55, "SVG": 1, "Batchfile": 1, "Shell": 1, "Maven POM": 1, "INI": 1, "Java Properties": 6, "Kotlin": 49, "Java": 1}
package pl.bas.microtwitter.controllers import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.client.TestRestTemplate import org.springframework.http.HttpStatus import org.springframework.test.context.junit.jupiter.SpringExtension @ExtendWith(SpringExtension::class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) internal class AppControllerTest { @Autowired lateinit var http: TestRestTemplate @Test fun getStatus() { val response = http.getForEntity("/app/status", String::class.java) assertEquals(HttpStatus.OK, response.statusCode) assertTrue(response.body?.length!! > 0) } @Test fun ping() { val response = http.getForEntity("/app/ping", String::class.java) assertEquals(HttpStatus.OK, response.statusCode) assertEquals("pong", response.body) } }
0
Kotlin
0
3
f0b33295f1b18d553480bb46ed50b813000dbbd4
1,161
MicroTwitter
MIT License
src/main/kotlin/org/bloqly/machine/service/DeltaService.kt
abaracadaor
147,365,768
false
null
package org.bloqly.machine.service import org.bloqly.machine.repository.BlockRepository import org.bloqly.machine.repository.VoteRepository import org.bloqly.machine.vo.block.BlockRangeRequest import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service class DeltaService( private val voteRepository: VoteRepository, private val spaceService: SpaceService, private val blockRepository: BlockRepository ) { @Transactional(readOnly = true) fun getDeltas(): List<BlockRangeRequest> { return spaceService.findAll() .filter { blockRepository.existsBySpaceId(it.id) } .mapNotNull { space -> voteRepository.findLastForSpace(space.id) } .map { vote -> val lastBlock = blockRepository.getLastBlock(vote.spaceId) BlockRangeRequest( spaceId = vote.spaceId, startHeight = lastBlock.libHeight + 1, endHeight = vote.height ) } .filter { it.startHeight < it.endHeight - 1 } } }
1
null
1
1
cfe046f6d93ebc51d12b2fecdbf0215181152a03
1,153
bloqly
MIT License
keepers/src/commonMain/kotlin/com/arkivanov/mvikotlin/keepers/statekeeper/StateKeeperRegistryExt.kt
wiltonlazary
383,849,539
true
{"Kotlin": 399490, "Swift": 11949, "Java": 7528, "Groovy": 115}
package com.arkivanov.mvikotlin.keepers.statekeeper /** * A convenience method for [StateKeeperRegistry.get] */ @ExperimentalStateKeeperApi inline fun <T : Any, reified S : T> StateKeeperRegistry<T>.get(key: String = S::class.toString()): StateKeeper<S> = get(S::class, key)
0
null
0
0
c686e168e1ff2c0845ae1bfd4712a6827b2db735
282
MVIKotlin
Apache License 2.0
fuzzer/fuzzing_output/crashing_tests/verified/minimized/localClassMember.kt-837253612.kt_minimized.kt
ItsLastDay
102,885,402
false
null
fun box(): (String)? { return ((Local::result) ?: (((Local::result)) ?: ((Local::result)))).call(Local(), "OK") }
2
null
1
6
56f50fc307709443bb0c53972d0c239e709ce8f2
113
KotlinFuzzer
MIT License
src/main/kotlin/io/github/cafeteriaguild/coffeecomputers/ScreenSizes.kt
CafeteriaGuild
279,180,738
false
{"Gradle": 2, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "Java": 1, "JSON": 8, "Kotlin": 10}
package io.github.cafeteriaguild.coffeecomputers object ScreenSizes { const val computerWidth = 51 * 9 + 4 const val computerHeight = 19 * 6 + 4 const val computerOuterWidth = computerWidth + 24 const val computerOuterHeight = computerHeight + 24 const val turtleWidth = 39 * 9 + 4 const val turtleHeight = 13 * 6 + 4 const val turtleOuterWidth = turtleWidth + 24 const val turtleOuterHeight = turtleHeight + 24 const val pocketComputerWidth = 26 * 9 + 4 const val pocketComputerHeight = 20 * 6 + 4 const val pocketComputerOuterWidth = pocketComputerWidth + 24 const val pocketComputerOuterHeight = pocketComputerHeight + 24 }
0
Kotlin
0
3
9f9575de518619edf62f97e60d32b7df84d07f02
677
CoffeeComputers
Apache License 2.0
src/test/kotlin/me/consuegra/algorithms/KLongestCommonPrefixTest.kt
aconsuegra
91,884,046
false
null
package me.consuegra.algorithms import org.junit.Assert.* import org.junit.Test import org.hamcrest.CoreMatchers.`is` as iz class KLongestCommonPrefixTest { val longestCommonPrefix = KLongestCommonPrefix() @Test fun testNoStrings() { assertThat(longestCommonPrefix.longestCommonPrefix(arrayOf<String>()), iz("")) } @Test fun testEmptyString() { assertThat(longestCommonPrefix.longestCommonPrefix(arrayOf("")), iz("")) } @Test fun test1String() { assertThat(longestCommonPrefix.longestCommonPrefix(arrayOf("abc")), iz("abc")) } @Test fun test2Strings() { assertThat(longestCommonPrefix.longestCommonPrefix(arrayOf("abcde", "abc")), iz("abc")) } @Test fun test4Strings() { assertThat(longestCommonPrefix.longestCommonPrefix(arrayOf("aaaaa", "aaa", "aab", "a")), iz("a")) } @Test fun test5Strings() { assertThat(longestCommonPrefix.longestCommonPrefix(arrayOf("aaaaa", "aaa", "aab", "a", "b")), iz("")) } }
1
null
1
7
7be2cbb64fe52c9990b209cae21859e54f16171b
1,072
algorithms-playground
MIT License
buildSrc/src/versions.kt
irialopez
160,354,029
false
null
const val VERSION_GRADLE = "4.10.2" const val VERSION_KOTLIN = "1.3.10" const val SDK_MIN = 14 const val SDK_TARGET = 28 const val BUILD_TOOLS = "28.0.3" internal const val VERSION_ANDROID_PLUGIN = "3.2.1" const val VERSION_ANDROIDX = "1.0.0" const val VERSION_ESPRESSO = "3.1.0" const val VERSION_RUNNER = "1.1.0" const val VERSION_RULES = "1.1.0" internal const val VERSION_PICASSO = "2.71828" internal const val VERSION_TRUTH = "0.42" internal const val VERSION_JUNIT = "4.12" internal const val VERSION_GIT_PUBLISH = "0.3.3" internal const val VERSION_BINTRAY_RELEASE = "0.9"
1
null
1
1
3e1d2503998938b22a24a3bc88f8cd77721db304
582
socialview
Apache License 2.0
plugins/git4idea/src/git4idea/rebase/interactive/dialog/ChangeEntryStateActions.kt
slouca10
239,728,750
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.rebase.interactive.dialog import com.intellij.ide.DataManager import com.intellij.ide.ui.laf.darcula.ui.DarculaButtonPainter import com.intellij.openapi.actionSystem.* import com.intellij.openapi.actionSystem.ex.CustomComponentAction import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import com.intellij.ui.AnActionButton import com.intellij.ui.ComponentUtil import com.intellij.ui.TableUtil import com.intellij.util.ui.JBUI import com.intellij.util.ui.components.BorderLayoutPanel import git4idea.i18n.GitBundle import git4idea.rebase.GitRebaseEntry import java.awt.Component import java.awt.Dimension import java.awt.Insets import java.awt.event.InputEvent import java.awt.event.KeyEvent import javax.swing.Icon import javax.swing.JButton import javax.swing.KeyStroke internal open class ChangeEntryStateSimpleAction( protected val action: GitRebaseEntry.Action, title: String, description: String, icon: Icon?, protected val table: GitRebaseCommitsTableView ) : AnActionButton(title, description, icon), DumbAware { constructor(action: GitRebaseEntry.Action, icon: Icon?, table: GitRebaseCommitsTableView) : this(action, action.name.capitalize(), action.name.capitalize(), icon, table) init { val keyStroke = KeyStroke.getKeyStroke( KeyEvent.getExtendedKeyCodeForChar(action.mnemonic.toInt()), InputEvent.ALT_MASK ) shortcutSet = CustomShortcutSet(KeyboardShortcut(keyStroke, null)) this.registerCustomShortcutSet(table, null) } override fun actionPerformed(e: AnActionEvent) { table.selectedRows.forEach { row -> table.setValueAt(action, row, GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN) } } override fun updateButton(e: AnActionEvent) { super.updateButton(e) actionIsEnabled(e, true) if (table.editingRow != -1 || table.selectedRowCount == 0) { actionIsEnabled(e, false) } } protected open fun actionIsEnabled(e: AnActionEvent, isEnabled: Boolean) { e.presentation.isEnabled = isEnabled } } internal open class ChangeEntryStateButtonAction( action: GitRebaseEntry.Action, table: GitRebaseCommitsTableView ) : ChangeEntryStateSimpleAction(action, null, table), CustomComponentAction, DumbAware { companion object { private val BUTTON_HEIGHT = JBUI.scale(28) } protected val button = object : JButton(action.name.capitalize()) { init { preferredSize = Dimension(preferredSize.width, BUTTON_HEIGHT) border = object : DarculaButtonPainter() { override fun getBorderInsets(c: Component?): Insets { return JBUI.emptyInsets() } } isFocusable = false displayedMnemonicIndex = 0 addActionListener { val toolbar = ComponentUtil.getParentOfType(ActionToolbar::class.java, this) val dataContext = toolbar?.toolbarDataContext ?: DataManager.getInstance().getDataContext(this) actionPerformed( AnActionEvent.createFromAnAction(this@ChangeEntryStateButtonAction, null, GitInteractiveRebaseDialog.PLACE, dataContext) ) } } } override fun actionIsEnabled(e: AnActionEvent, isEnabled: Boolean) { super.actionIsEnabled(e, isEnabled) button.isEnabled = isEnabled } override fun createCustomComponent(presentation: Presentation, place: String) = BorderLayoutPanel().addToCenter(button).apply { border = JBUI.Borders.emptyLeft(6) } } internal class FixupAction(table: GitRebaseCommitsTableView) : ChangeEntryStateButtonAction(GitRebaseEntry.Action.FIXUP, table) { override fun actionPerformed(e: AnActionEvent) { val selectedRows = table.selectedRows if (selectedRows.size == 1) { table.setValueAt(action, selectedRows.first(), GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN) } else { selectedRows.drop(1).forEach { row -> table.setValueAt(action, row, GitRebaseCommitsTableModel.COMMIT_ICON_COLUMN) } } } } internal class RewordAction(table: GitRebaseCommitsTableView) : ChangeEntryStateButtonAction(GitRebaseEntry.Action.REWORD, table) { override fun updateButton(e: AnActionEvent) { super.updateButton(e) if (table.selectedRowCount != 1) { actionIsEnabled(e, false) } } override fun actionPerformed(e: AnActionEvent) { TableUtil.editCellAt(table, table.selectedRows.single(), GitRebaseCommitsTableModel.SUBJECT_COLUMN) } } internal class ShowGitRebaseCommandsDialog(private val project: Project, private val table: GitRebaseCommitsTableView) : DumbAwareAction(GitBundle.getString("rebase.interactive.dialog.view.git.commands.text")) { private fun getEntries(): List<GitRebaseEntry> = table.model.entries.map { it.entry } override fun actionPerformed(e: AnActionEvent) { val dialog = GitRebaseCommandsDialog(project, getEntries()) dialog.show() } }
1
null
1
1
3c61291873b63095c9672a7b388f126cd5eed7b6
5,051
intellij-community
Apache License 2.0
src/main/kotlin/com/atlassian/performance/tools/jiraactions/api/w3c/PerformanceResourceTiming.kt
atlassian
162,422,950
false
{"Kotlin": 214499, "Java": 1959}
package com.atlassian.performance.tools.jiraactions.api.w3c import java.time.Duration /** * Represents the [PerformanceResourceTiming](https://www.w3.org/TR/resource-timing-2/#dom-performanceresourcetiming). */ class PerformanceResourceTiming internal constructor( val entry: PerformanceEntry, val initiatorType: String, val nextHopProtocol: String, val workerStart: Duration, val redirectStart: Duration, val redirectEnd: Duration, val fetchStart: Duration, val domainLookupStart: Duration, val domainLookupEnd: Duration, val connectStart: Duration, val connectEnd: Duration, val secureConnectionStart: Duration, val requestStart: Duration, val responseStart: Duration, val responseEnd: Duration, val transferSize: Long, val encodedBodySize: Long, val decodedBodySize: Long, /** * Represents the [serverTiming attribute](https://www.w3.org/TR/2023/WD-server-timing-20230411/#servertiming-attribute) * * @return Null if blocked, e.g. by same-origin policy. * Empty if not blocked, but server didn't send any `Server-Timing` headers. * @since 3.24.0 */ val serverTiming: List<PerformanceServerTiming>? )
8
Kotlin
31
26
10b363eda1e171f8342eaeeb6deac843b1d34df3
1,225
jira-actions
Apache License 2.0
Presentation/src/main/java/com/hf/presentation/mapper/Mapper.kt
biodunalfet
192,399,583
false
null
package com.hf.presentation.mapper interface Mapper<V, D> { fun mapToView(type: D): V }
1
null
5
4
e01a1561ed87dd638d18f50661c3b3e809944f73
95
StarWarsChar
Apache License 2.0
test-suite-kotlin/src/test/kotlin/io/micronaut/kafka/docs/consumer/topics/ProductListener.kt
micronaut-projects
165,680,104
false
{"Gradle": 13, "Java Properties": 2, "Markdown": 5, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Java": 225, "XML": 8, "Gradle Kotlin DSL": 3, "INI": 4, "Kotlin": 72, "Groovy": 143, "TOML": 1, "AsciiDoc": 35, "YAML": 14, "JSON": 2}
package io.micronaut.kafka.docs.consumer.topics import io.micronaut.configuration.kafka.annotation.KafkaKey import io.micronaut.configuration.kafka.annotation.KafkaListener import io.micronaut.configuration.kafka.annotation.Topic import io.micronaut.context.annotation.Requires import org.slf4j.LoggerFactory @Requires(property = "spec.name", value = "TopicsProductListenerTest") @KafkaListener class ProductListener { companion object { private val LOG = LoggerFactory.getLogger(ProductListener::class.java) } // tag::multiTopics[] @Topic("fun-products", "awesome-products") fun receiveMultiTopics(@KafkaKey brand: String, name: String) { LOG.info("Got Product - {} by {}", name, brand) } // end::multiTopics[] // tag::patternTopics[] @Topic(patterns = ["products-\\w+"]) fun receivePatternTopics(@KafkaKey brand: String, name: String) { LOG.info("Got Product - {} by {}", name, brand) } // end::patternTopics[] }
46
Java
101
84
6daae3aca505d0328aacab0215c0d9ef6724d859
992
micronaut-kafka
Apache License 2.0
app/src/main/java/com/android/demoeditor/screens/DeveloperDetailsFragment.kt
manojpedvi
736,993,827
true
{"Java Properties": 3, "Gradle": 6, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 23, "Ignore List": 6, "XML": 253, "INI": 4, "Proguard": 2, "CMake": 2, "C++": 18, "Unix Assembly": 10, "Motorola 68K Assembly": 4, "Kotlin": 193, "C": 1, "Java": 154, "JSON": 23, "RenderScript": 6}
package com.android.demoeditor.screens import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.os.Handler import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Toast import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.navigation.findNavController import com.android.demoeditor.R import com.android.demoeditor.databinding.FragmentDeveloperDetailsBinding class DeveloperDetailsFragment : Fragment() { private val TAG = this::class.java.name private lateinit var binding: FragmentDeveloperDetailsBinding private val handler = Handler() private val nameStr = " <NAME>".toCharArray() private var animText = "" private var nameIdx = 0; override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate( layoutInflater, R.layout.fragment_developer_details, container, false ) setUpImageView() setupAnimationTextView() setupToolbar() binding.mail.setOnClickListener { emailShareIntent() } binding.linkedin.setOnClickListener { linkedinIntent() } handler.postDelayed(object : Runnable { override fun run() { //Call your function here if (nameIdx in 0..nameStr.size - 2) { ++nameIdx animText += nameStr[nameIdx] } else { nameIdx = 0 animText = "" } animateText() handler.postDelayed(this, 550)//1 sec delay } }, 0) // Inflate the layout for this fragment return binding.root; } private fun setupAnimationTextView() { binding.developerName.apply { animateText(getText(R.string.developer_name)) } } private fun alert(text: String) { Toast.makeText(context, text, Toast.LENGTH_SHORT) } private fun animateText() { binding.developerName.animateText(animText) } private fun setUpImageView() { // val radius = resources.getDimension(R.dimen.developer_details_for_all_corner_radius) val radius = 12f val shapeAppearanceModel = binding.developerImg.shapeAppearanceModel.toBuilder() .setAllCornerSizes(radius) .build() binding.developerImg.shapeAppearanceModel = shapeAppearanceModel } /** * Inflating menu inside Fragment Toolbar */ private fun setupToolbar() { binding.toolbar.apply { setNavigationOnClickListener { it.findNavController().navigateUp() } } } /**Intents*/ private fun emailShareIntent() { val shareEmailIntent = Intent(Intent.ACTION_SEND ) .apply { data = Uri.parse("mailto:"); // only email apps should handle this putExtra( Intent.ACTION_SENDTO, "<EMAIL>" ); type = "text/plain"; putExtra(Intent.EXTRA_SUBJECT, "Mail For Foto Editor "); } try { activity!!.startActivity(shareEmailIntent) } catch (ex: ActivityNotFoundException) { Toast.makeText( context, "Email have not been installed.", Toast.LENGTH_SHORT ).show() } } private fun linkedinIntent(){ val profile_url = "https://www.linkedin.com/in/wasim-akram-biswas-753b77204" val shareLinkedinIntent = Intent(Intent.ACTION_VIEW, Uri.parse(profile_url)) .apply { setPackage("com.linkedin.android") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } try { activity!!.startActivity(shareLinkedinIntent) } catch (ex: ActivityNotFoundException) { Toast.makeText( context, "Linkedin have not been installed.", Toast.LENGTH_SHORT ).show() } } }
0
null
0
0
e47637b8c821539c520d657805cd2151961aa095
4,407
Foto-Editor
MIT License
systemUIAnim/src/com/android/systemui/animation/FontVariationUtils.kt
LawnchairLauncher
83,799,439
false
null
package com.android.systemui.animation private const val TAG_WGHT = "wght" private const val TAG_WDTH = "wdth" private const val TAG_OPSZ = "opsz" private const val TAG_ROND = "ROND" class FontVariationUtils { private var mWeight = -1 private var mWidth = -1 private var mOpticalSize = -1 private var mRoundness = -1 private var isUpdated = false /* * generate fontVariationSettings string, used for key in typefaceCache in TextAnimator * the order of axes should align to the order of parameters * if every axis remains unchanged, return "" */ fun updateFontVariation( weight: Int = -1, width: Int = -1, opticalSize: Int = -1, roundness: Int = -1 ): String { isUpdated = false if (weight >= 0 && mWeight != weight) { isUpdated = true mWeight = weight } if (width >= 0 && mWidth != width) { isUpdated = true mWidth = width } if (opticalSize >= 0 && mOpticalSize != opticalSize) { isUpdated = true mOpticalSize = opticalSize } if (roundness >= 0 && mRoundness != roundness) { isUpdated = true mRoundness = roundness } var resultString = "" if (mWeight >= 0) { resultString += "'$TAG_WGHT' $mWeight" } if (mWidth >= 0) { resultString += (if (resultString.isBlank()) "" else ", ") + "'$TAG_WDTH' $mWidth" } if (mOpticalSize >= 0) { resultString += (if (resultString.isBlank()) "" else ", ") + "'$TAG_OPSZ' $mOpticalSize" } if (mRoundness >= 0) { resultString += (if (resultString.isBlank()) "" else ", ") + "'$TAG_ROND' $mRoundness" } return if (isUpdated) resultString else "" } }
388
null
1200
9,200
d91399d2e4c6acbeef9c0704043f269115bb688b
1,867
lawnchair
Apache License 2.0
dbflow-tests/src/main/java/com/raizlabs/android/dbflow/prepackaged/PrepackagedDB.kt
ultraon
100,583,356
true
{"Java": 710076, "Kotlin": 466605}
package com.raizlabs.android.dbflow.prepackaged import com.raizlabs.android.dbflow.annotation.Column import com.raizlabs.android.dbflow.annotation.Database import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel @Database(name = PrepackagedDB.NAME, version = PrepackagedDB.VERSION) object PrepackagedDB { const val NAME = "prepackaged" const val VERSION = 1 } @Table(database = PrepackagedDB::class) class Dog : BaseModel() { @PrimaryKey var id: Int = 0 @Column var breed: String? = null @Column var color: String? = null }
1
Java
0
0
9e30167cf9a3e0aff04aee01dd2d27bc8e10dcb0
671
DBFlow
MIT License
app/src/main/java/com/kickstarter/ui/activities/compose/login/SetPasswordScreen.kt
kickstarter
76,278,501
false
{"Kotlin": 5269841, "Java": 317201, "Ruby": 22177, "Shell": 6325, "Makefile": 3750}
package com.kickstarter.ui.activities.compose.login import android.content.res.Configuration import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column 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.rememberScrollState import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Scaffold import androidx.compose.material.ScaffoldState import androidx.compose.material.SnackbarHost import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.MoreVert import androidx.compose.material.rememberScaffoldState import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import com.kickstarter.R import com.kickstarter.libs.utils.extensions.validPassword import com.kickstarter.ui.compose.designsystem.KSErrorSnackbar import com.kickstarter.ui.compose.designsystem.KSHiddenTextInput import com.kickstarter.ui.compose.designsystem.KSLinearProgressIndicator import com.kickstarter.ui.compose.designsystem.KSPrimaryGreenButton import com.kickstarter.ui.compose.designsystem.KSTheme import com.kickstarter.ui.toolbars.compose.TopToolBar @Composable @Preview(name = "Light", uiMode = Configuration.UI_MODE_NIGHT_NO) @Preview(name = "Dark", uiMode = Configuration.UI_MODE_NIGHT_YES) fun SetPasswordPreview() { KSTheme { SetPasswordScreen( onSaveButtonClicked = {}, showProgressBar = false, isFormSubmitting = false, onTermsOfUseClicked = { }, onPrivacyPolicyClicked = { }, onCookiePolicyClicked = { }, onHelpClicked = { }, scaffoldState = rememberScaffoldState() ) } } enum class SetPasswordScreenTestTag { PAGE_TITLE, SAVE_BUTTON, OPTIONS_ICON, PROGRESS_BAR, PAGE_DISCLAIMER, NEW_PASSWORD_EDIT_TEXT, CONFIRM_PASSWORD_EDIT_TEXT, WARNING_TEXT, } @Composable fun SetPasswordScreen( onSaveButtonClicked: (newPass: String) -> Unit, showProgressBar: Boolean, headline: String? = stringResource(id = R.string.We_will_be_discontinuing_the_ability_to_log_in_via_FB), isFormSubmitting: Boolean, onTermsOfUseClicked: () -> Unit, onPrivacyPolicyClicked: () -> Unit, onCookiePolicyClicked: () -> Unit, onHelpClicked: () -> Unit, scaffoldState: ScaffoldState ) { var expanded by remember { mutableStateOf(false) } var newPasswordLine1 by rememberSaveable { mutableStateOf("") } var newPasswordLine2 by rememberSaveable { mutableStateOf("") } val acceptButtonEnabled = when { !isFormSubmitting && newPasswordLine1.validPassword() && newPasswordLine2.validPassword() && newPasswordLine1 == newPasswordLine2 -> true else -> false } val warningText = when { newPasswordLine1.validPassword() && newPasswordLine2.isNotEmpty() && newPasswordLine2 != newPasswordLine1 -> { stringResource(id = R.string.Passwords_matching_message) } newPasswordLine1.isNotEmpty() && newPasswordLine1.length < 6 -> { stringResource(id = R.string.Password_min_length_message) } else -> "" } val focusManager = LocalFocusManager.current Scaffold( scaffoldState = scaffoldState, topBar = { TopToolBar( title = stringResource(id = R.string.Set_your_password), titleColor = KSTheme.colors.kds_support_700, titleModifier = Modifier.testTag(SetPasswordScreenTestTag.PAGE_TITLE.name), leftIcon = null, leftOnClickAction = null, backgroundColor = KSTheme.colors.kds_white, right = { IconButton( modifier = Modifier.testTag(SetPasswordScreenTestTag.OPTIONS_ICON.name), onClick = { expanded = !expanded }, enabled = true ) { Box { Icon( imageVector = Icons.Default.MoreVert, contentDescription = stringResource( id = R.string.general_navigation_accessibility_button_help_menu_label ), tint = KSTheme.colors.kds_black ) KSLoginDropdownMenu( expanded = expanded, onDismissed = { expanded = !expanded }, onTermsOfUseClicked = onTermsOfUseClicked, onPrivacyPolicyClicked = onPrivacyPolicyClicked, onCookiePolicyClicked = onCookiePolicyClicked, onHelpClicked = onHelpClicked ) } } } ) }, snackbarHost = { SnackbarHost( hostState = scaffoldState.snackbarHostState, snackbar = { data -> KSErrorSnackbar(text = data.message) } ) } ) { padding -> Column( Modifier .background(KSTheme.colors.kds_white) .fillMaxSize() .verticalScroll(rememberScrollState()) .padding(padding) ) { AnimatedVisibility(visible = showProgressBar) { KSLinearProgressIndicator( modifier = Modifier .fillMaxWidth() .testTag(SetPasswordScreenTestTag.PROGRESS_BAR.name) ) } if (headline != null) { Text( modifier = Modifier .padding(KSTheme.dimensions.paddingMedium) .testTag(SetPasswordScreenTestTag.PAGE_DISCLAIMER.name), text = headline, style = KSTheme.typography.body2, color = KSTheme.colors.kds_support_700 ) } Column( Modifier .background(color = KSTheme.colors.kds_white) .padding(KSTheme.dimensions.paddingMedium) .fillMaxWidth() ) { KSHiddenTextInput( modifier = Modifier .fillMaxWidth() .testTag(SetPasswordScreenTestTag.NEW_PASSWORD_EDIT_TEXT.name), onValueChanged = { newPasswordLine1 = it }, label = stringResource(id = R.string.New_password), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next), keyboardActions = KeyboardActions( onNext = { focusManager.moveFocus( focusDirection = FocusDirection.Down ) } ) ) Spacer(modifier = Modifier.height(KSTheme.dimensions.listItemSpacingMedium)) KSHiddenTextInput( modifier = Modifier .fillMaxWidth() .testTag(SetPasswordScreenTestTag.CONFIRM_PASSWORD_EDIT_TEXT.name), onValueChanged = { newPasswordLine2 = it }, label = stringResource(id = R.string.Confirm_password), keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done), keyboardActions = KeyboardActions( onDone = { focusManager.clearFocus() } ) ) Divider(color = KSTheme.colors.kds_support_300) AnimatedVisibility(visible = warningText.isNotEmpty()) { Text( modifier = Modifier .padding(KSTheme.dimensions.paddingMedium) .testTag(SetPasswordScreenTestTag.WARNING_TEXT.name), text = warningText, style = KSTheme.typography.body2, color = KSTheme.colors.kds_support_700 ) } Spacer(modifier = Modifier.height(KSTheme.dimensions.minButtonHeight)) KSPrimaryGreenButton( modifier = Modifier.testTag(SetPasswordScreenTestTag.SAVE_BUTTON.name), text = stringResource(id = R.string.Save), onClickAction = { onSaveButtonClicked.invoke(newPasswordLine1) }, isEnabled = acceptButtonEnabled ) } } } }
8
Kotlin
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
10,104
android-oss
Apache License 2.0
qoc-core/src/main/java/com/example/coreandroid/sources/network/HTTPService.kt
theblissprogrammer
142,545,857
false
null
package com.example.coreandroid.sources.network import android.net.Uri import com.example.coreandroid.sources.common.CompletionResponse import com.example.coreandroid.sources.common.CompletionResponse.Companion.failure import com.example.coreandroid.sources.common.CompletionResponse.Companion.success import com.example.coreandroid.sources.enums.NetworkMethod import com.example.coreandroid.sources.errors.NetworkError import okhttp3.* import java.util.concurrent.TimeUnit /** * Created by ahmedsaad on 2018-02-08. * Copyright © 2017. All rights reserved. */ data class ServerResponse (val data: String, val headers: Map<String, String>, val statusCode: Int) interface HTTPServiceType { fun get(url: String, parameters: Map<String, Any?>? = null, headers: Map<String, String>? = null): CompletionResponse<ServerResponse, NetworkError> } class HTTPService: HTTPServiceType { private val sessionManager : OkHttpClient = OkHttpClient().newBuilder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS).build() override fun get(url: String, parameters: Map<String, Any?>?, headers: Map<String, String>?): CompletionResponse<ServerResponse, NetworkError> { val uri = Uri.parse(url) .buildUpon() try { parameters?.forEach { if (it.value != null) uri.appendQueryParameter(it.key, it.value.toString()) } } catch (error: Exception) { return failure( NetworkError( statusCode = 0, internalError = error ) ) } val urlRequest = Request.Builder() .url(uri.build().toString()) .method(NetworkMethod.GET.name, null) headers?.forEach { urlRequest.addHeader(it.key, it.value) } val response = sessionManager.newCall(urlRequest.build()).execute() // Retrieve the data val data = response.body()?.string() // Convert header values to string dictionary val responseHeaders = response.headers().toMultimap().mapValues { it.value.first() } val statusCode = response.code() if (response.isSuccessful) { return success( ServerResponse( data = data ?: "", headers = responseHeaders, statusCode = statusCode ) ) } else { val error = NetworkError( urlRequest = null, statusCode = statusCode, headerValues = responseHeaders, serverData = data ?: "") return failure(error) } } }
1
null
1
1
803929a63b5c4bf1c7c8af3740357186f00ee956
2,821
sample-app-android
MIT License
library/src/main/java/pl/aprilapps/easypicker/ChooserType.kt
abhinav12k
487,720,078
true
{"Kotlin": 34817, "Java": 133}
package pl.aprilapps.easypicker enum class ChooserType { CAMERA_AND_GALLERY, CAMERA_AND_DOCUMENTS, CAMERA_AND_GALLERY_AND_DOCUMENTS }
1
Kotlin
1
1
277a231ccc206ed2e1b42fd6983f429df1ed5213
138
EasyPicker
Apache License 2.0
analysis/low-level-api-fir/testData/contextCollector/withTestCompilerPluginEnabled/callShapeBasedInjector_extraSafeCall.kt
JetBrains
3,432,266
false
null
// WITH_FIR_TEST_COMPILER_PLUGIN import kotlin.reflect.KClass interface DataFrame<out T> annotation class Refine @Refine fun <T, R> DataFrame<T>.add(columnName: String, expression: () -> R): DataFrame<Any?>? = TODO() fun test_1(df: DataFrame<*>?) { val df1_toStringSafe = df?.add("column") { 1 }?.toString() <expr>df1_toStringSafe</expr> }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
353
kotlin
Apache License 2.0
app/src/main/java/io/eodc/planit/adapter/AssignmentTypeAdapter.kt
eodc
135,878,365
false
null
package io.eodc.planit.adapter import android.content.Context import androidx.annotation.IdRes import androidx.annotation.LayoutRes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.ImageView import android.widget.TextView import io.eodc.planit.R /** * Adapter for interfacing [AssignmentType] with a Spinner * * @author 2n */ class AssignmentTypeAdapter /** * Constructs a new AssignmentTypeAdapter * * @param mContext The context to pull strings, colors, etc. * @param mResource The layout to use for the item view * @param textViewId The id of a TextView inside the layout specified * @param mTypes A list of [AssignmentType] to interface into the Spinner */ (private val mContext: Context, @param:LayoutRes private val mResource: Int, @IdRes textViewId: Int, private val mTypes: List<AssignmentType>) : ArrayAdapter<AssignmentType>(mContext, mResource, textViewId, mTypes) { override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View { return getCustomView(position) } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View { return getCustomView(position) } /** * Equivalent of [android.support.v7.widget.RecyclerView.Adapter.onBindViewHolder]; * Binds information from [AssignmentType] to the view * * @param position Position to get from the list of objects * @return A view with all information and icons bound to it */ private fun getCustomView(position: Int): View { val v: View = LayoutInflater.from(mContext).inflate(mResource, null) val holder = ViewHolder() holder.icon = v.findViewById(R.id.ic_type) holder.title = v.findViewById(R.id.textHeaderTitle) val type = mTypes[position] holder.icon!!.setImageResource(type.iconId) holder.title!!.text = type.name return v } /** * A "holder" for the information of the view */ internal class ViewHolder { var icon: ImageView? = null var title: TextView? = null } }
1
null
1
1
fe1bb83b1682835a26a87b4d46773726a03b0250
2,186
PlanIt
Apache License 2.0
src/main/java/com/razorpay/sampleapp/kotlin/PaymentActivity.kt
razorpay
65,271,132
false
null
package com.razorpay.sampleapp.kotlin import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Button import com.razorpay.sampleapp.R class PaymentActivity: Activity() { val activity = this override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_layout_payment) val button : Button = findViewById(R.id.pay_btn) button.setOnClickListener { val intent = Intent(this,PaymentOptions::class.java) startActivity(intent) } } }
14
null
9
8
fcd817f87e137354b3b77dc68fd3ddbb25f583cc
612
razorpay-android-custom-sample-app
MIT License
app/src/main/java/com/vo/vozilla/mapactivity/presentation/converters/ParkingToMarkerConverter.kt
MichBogus
159,330,891
false
null
package com.vo.vozilla.mapactivity.presentation.converters import com.google.android.gms.maps.model.MarkerOptions import com.vo.vozilla.mapactivity.domain.ParkingSpace import com.vo.vozilla.repository.network.mapobjects.models.parking.Parking interface ParkingToMarkerConverter { fun convert(parking: List<Parking>): List<Pair<ParkingSpace, MarkerOptions>> fun getPinBackgroundByParkingSpace(space: ParkingSpace): Int }
0
Kotlin
0
0
4a1758b3b3529ff72d58069939dc6244397d6437
431
Vozilla
Apache License 2.0
app/src/main/java/com/anonymouser/book/view/register/RegisterContract.kt
LeLe673893702
178,763,822
false
null
package com.anonymouser.book.view.register import com.anonymouser.base.BasePresenter import com.newler.putonghuapractice.base.BaseView interface RegisterContract { interface Presenter: BasePresenter { fun register(username: String, password: String) } interface View:BaseView { fun registerSucceed() } }
1
null
1
1
4abbe49ec5fc9ee3bdb93c49a76ef7158d353a67
341
FanTuan
Apache License 2.0
jetbrains-core/src/software/aws/toolkits/jetbrains/services/lambda/sam/SamOptions.kt
JetBrains
223,485,227
true
{"Gradle Kotlin DSL": 21, "Markdown": 16, "Java Properties": 2, "Shell": 1, "Text": 12, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 3, "YAML": 28, "XML": 96, "Kotlin": 1102, "JSON": 54, "Java": 9, "SVG": 64, "TOML": 1, "INI": 1, "CODEOWNERS": 1, "Maven POM": 4, "Dockerfile": 14, "JavaScript": 3, "Python": 5, "Go": 1, "Go Module": 1, "Microsoft Visual Studio Solution": 6, "C#": 79}
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.lambda.sam import com.intellij.util.xmlb.annotations.Tag @Tag("sam") data class SamOptions( var dockerNetwork: String? = null, var buildInContainer: Boolean = false, var skipImagePull: Boolean = false )
6
Kotlin
4
9
ccee3307fe58ad48f93cd780d4378c336ee20548
380
aws-toolkit-jetbrains
Apache License 2.0
kotlin-mui-icons/src/main/generated/mui/icons/material/InboxRounded.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/InboxRounded") package mui.icons.material @JsName("default") external val InboxRounded: SvgIconComponent
10
Kotlin
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
188
kotlin-wrappers
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Sledding.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.Sledding: ImageVector get() { if (_sledding != null) { return _sledding!! } _sledding = Builder(name = "Sledding", defaultWidth = 512.0.dp, defaultHeight = 512.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) { moveTo(23.9f, 21.73f) arcToRelative(3.889f, 3.889f, 0.0f, false, true, -5.24f, 1.877f) lineTo(0.566f, 14.9f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.867f, -1.8f) lineToRelative(18.094f, 8.7f) arcToRelative(1.894f, 1.894f, 0.0f, false, false, 2.571f, -0.939f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.8f, 0.865f) close() moveTo(5.0f, 6.0f) horizontalLineToRelative(7.566f) lineTo(8.714f, 11.062f) arcTo(3.0f, 3.0f, 0.0f, false, false, 11.0f, 16.0f) horizontalLineToRelative(4.379f) arcToRelative(1.007f, 1.007f, 0.0f, false, true, 0.978f, 0.792f) lineToRelative(0.3f, 1.417f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 1.955f, -0.417f) lineToRelative(-0.3f, -1.418f) arcTo(3.015f, 3.015f, 0.0f, false, false, 15.382f, 14.0f) horizontalLineTo(11.0f) arcToRelative(0.985f, 0.985f, 0.0f, false, true, -0.907f, -0.579f) arcToRelative(1.016f, 1.016f, 0.0f, false, true, 0.177f, -1.108f) lineToRelative(4.388f, -5.764f) lineToRelative(1.131f, 0.722f) arcToRelative(1.19f, 1.19f, 0.0f, false, true, -0.118f, 1.468f) lineToRelative(-1.285f, 1.647f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.579f, 1.229f) lineToRelative(1.276f, -1.637f) arcToRelative(3.1f, 3.1f, 0.0f, false, false, -0.127f, -4.211f) arcToRelative(1.083f, 1.083f, 0.0f, false, false, -0.151f, -0.119f) lineToRelative(-1.348f, -0.861f) arcTo(4.988f, 4.988f, 0.0f, false, false, 12.927f, 4.0f) horizontalLineTo(5.0f) arcTo(1.0f, 1.0f, 0.0f, false, false, 5.0f, 6.0f) close() moveTo(18.5f, 5.0f) arcTo(2.5f, 2.5f, 0.0f, true, false, 16.0f, 2.5f) arcTo(2.5f, 2.5f, 0.0f, false, false, 18.5f, 5.0f) close() } } .build() return _sledding!! } private var _sledding: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,399
icons
MIT License
beckon-rx2/src/main/java/com/technocreatives/beckon/rx2/BeckonClientEx.kt
technocreatives
364,517,134
false
null
package com.technocreatives.beckon.rx2 import arrow.core.Either import arrow.core.identity import arrow.core.left import arrow.core.right import com.lenguyenthanh.rxarrow.filterZ import com.lenguyenthanh.rxarrow.flatMapObservableEither import com.lenguyenthanh.rxarrow.flatMapSingleEither import com.lenguyenthanh.rxarrow.flatMapSingleZ import com.lenguyenthanh.rxarrow.flatMapZ import com.lenguyenthanh.rxarrow.z import com.technocreatives.beckon.BeckonDeviceError import com.technocreatives.beckon.BeckonException import com.technocreatives.beckon.BeckonResult import com.technocreatives.beckon.BeckonState import com.technocreatives.beckon.ConnectionError import com.technocreatives.beckon.Descriptor import com.technocreatives.beckon.MacAddress import com.technocreatives.beckon.SavedMetadata import com.technocreatives.beckon.ScanResult import com.technocreatives.beckon.ScannerSetting import com.technocreatives.beckon.State import io.reactivex.Observable import io.reactivex.Single import timber.log.Timber fun BeckonClientRx.devicesStates(addresses: List<String>): Observable<List<Either<BeckonDeviceError, BeckonState<State>>>> { Timber.d("deviceStates $addresses") if (addresses.isEmpty()) { return Observable.never() } val devices = addresses.map { deviceStates(it) } return Observable.combineLatest(devices) { Timber.d("deviceStates combineLatest $it") it.map { it as Either<BeckonDeviceError, BeckonState<State>> }.toList() } } fun BeckonClientRx.deviceStates(address: MacAddress): Observable<Either<BeckonDeviceError, BeckonState<State>>> { return findSavedDeviceE(address) .flatMapObservableEither { findConnectedDeviceO(it) } .flatMapZ { it.deviceStates() } } fun BeckonClientRx.findSavedDeviceE(macAddress: MacAddress): Single<Either<BeckonDeviceError.SavedDeviceNotFound, SavedMetadata>> { return findSavedDevice(macAddress).z { BeckonDeviceError.SavedDeviceNotFound(macAddress) } } fun BeckonClientRx.scanAndConnect( conditions: Observable<Boolean>, setting: ScannerSetting, descriptor: Descriptor ): Observable<BeckonResult<BeckonDeviceRx>> { val searchStream = search(conditions, setting, descriptor).map { it.mapLeft { BeckonException(it) } } val scanStream = scan(conditions, setting) .flatMapSingleEither { safeConnect(it, descriptor) } return Observable.merge(scanStream, searchStream) } fun BeckonClientRx.safeConnect( result: ScanResult, descriptor: Descriptor ): Single<BeckonResult<BeckonDeviceRx>> { return connect(result, descriptor).map { it.right() as BeckonResult<BeckonDeviceRx> } .doOnSuccess { Timber.d("safe Connect $it") } .onErrorReturn { it.left() } } fun BeckonClientRx.scan( conditions: Observable<Boolean>, setting: ScannerSetting ): Observable<BeckonResult<ScanResult>> { return conditions .switchMap { if (it) { Timber.d("Scan conditions are meet, start scanning") startScan(setting) } else { Timber.d("Scan conditions are not meet, stop scanning") stopScan() Observable.empty() } } .distinct { it.macAddress } .z(::identity) .doOnNext { Timber.d("Scan found $it") } .doOnDispose { Timber.d("Scan stream is disposed, stop scanning") stopScan() } } fun BeckonClientRx.search( conditions: Observable<Boolean>, setting: ScannerSetting, descriptor: Descriptor ): Observable<Either<ConnectionError, BeckonDeviceRx>> { return conditions .switchMap { if (it) { Timber.d("Scan conditions are meet, start searching") search(setting, descriptor) } else { Timber.d("Scan conditions are not meet, stop searching") Observable.empty() } } .doOnNext { Timber.d("Search found $it") } } fun BeckonClientRx.scanAndSave( conditions: Observable<Boolean>, setting: ScannerSetting, descriptor: Descriptor, filter: (State) -> Boolean ): Observable<BeckonResult<MacAddress>> { return scanAndConnect(conditions.distinctUntilChanged(), setting, descriptor) .doOnNext { Timber.d("Scan And Connect: $it") } .flatMapZ { it.deviceStates() } // .doOnNext { Timber.d("Device state: $it") } .filterZ { deviceState -> Timber.d("Device state: ${deviceState.state}") filter(deviceState.state) } .flatMapSingleZ { save(it.metadata.macAddress) } .doOnNext { Timber.d("scanAndSave found $it") } } fun BeckonClientRx.connectSavedDevice(macAddress: MacAddress): Single<BeckonDeviceRx> { return findSavedDevice(macAddress).flatMap { connect(it) } }
1
Kotlin
1
8
2e252df19c02104821c393225ee8d5abefa07b74
4,870
beckon-android
Apache License 2.0
app/src/main/java/com/fulldive/wallet/interactors/balances/BalancesInteractor.kt
imversed
473,994,295
true
{"Java": 9874648, "Kotlin": 515378}
package com.fulldive.wallet.interactors.balances import com.fulldive.wallet.di.modules.DefaultInteractorsModule import com.fulldive.wallet.extensions.or import com.fulldive.wallet.interactors.chains.binance.BinanceInteractor import com.fulldive.wallet.interactors.chains.grpc.GrpcInteractor import com.fulldive.wallet.interactors.chains.okex.OkexInteractor import com.fulldive.wallet.models.BaseChain import com.fulldive.wallet.models.WalletBalance import com.joom.lightsaber.ProvidedBy import io.reactivex.Completable import io.reactivex.Single import javax.inject.Inject @ProvidedBy(DefaultInteractorsModule::class) class BalancesInteractor @Inject constructor( private val balancesRepository: BalancesRepository, private val binanceInteractor: BinanceInteractor, private val okexInteractor: OkexInteractor, private val grpcInteractor: GrpcInteractor ) { fun getBalance(accountId: Long, denom: String): Single<WalletBalance> { return balancesRepository.getBalance(accountId, denom) } fun getBalances(accountId: Long): Single<List<WalletBalance>> { return balancesRepository.getBalances(accountId) // TODO: add filter for zero balances. and add zero balance for main denom if it doesn't exists. vesting // .map { balances -> // var items = balances // .mapNotNull { coin -> // safe { // coin // .takeIf { // it.denom.equals(chain.mainDenom, true) || it.amount.toInt() > 0 // } // ?.let { Coin(it.denom, it.amount) } // } // } // if (!items.any { it.denom == chain.mainDenom }) { // items = listOf(Coin(chain.mainDenom, "0")) + items // } // items // } // .flatMapCompletable(Function<List<Balance?>, CompletableSource> { balances: List<Balance?>? -> // Completable.fromCallable { // if (getBaseDao().mGRpcAccount != null && !getBaseDao().mGRpcAccount.getTypeUrl() // .contains(Auth.BaseAccount.getDescriptor().fullName) // ) { // WUtil.onParseVestingAccount(getBaseDao(), getBaseChain(), balances) // } // true // } // }) } fun deleteBalances(accountId: Long): Completable { return balancesRepository.deleteBalances(accountId) } fun requestBalances( chain: BaseChain, address: String, accountId: Long = 0L ): Single<List<WalletBalance>> { return when (chain) { BaseChain.BNB_MAIN -> { binanceInteractor.requestAccount(address) .map { accountInfo -> accountInfo .balances ?.map { coin -> WalletBalance.create( accountId = accountId, symbol = coin.symbol, balance = coin.free, locked = coin.locked, frozen = coin.frozen, ) } .or(emptyList()) } } BaseChain.OKEX_MAIN -> { okexInteractor .requestAccountBalance(address) .map { accountToken -> accountToken .data.currencies ?.map { currency -> WalletBalance.create( accountId = accountId, symbol = currency.symbol, balance = currency.available, locked = currency.locked, ) } .or(emptyList()) } } else -> { grpcInteractor.requestBalances(chain, address).map { coins -> coins.mapNotNull { coin -> WalletBalance.create( accountId = accountId, symbol = coin.denom, balance = coin.amount ) } } } } .flatMap { balances -> if (accountId > 0L) { balancesRepository.updateBalances(accountId, balances) } else { Completable.complete() } .toSingleDefault(balances) } } fun updateBalances(accountId: Long, balances: List<WalletBalance>): Completable { return balancesRepository.updateBalances(accountId, balances) } }
0
Java
0
2
5fddbefcdc6acf7cadb6f7a7ab2edccee9f57851
5,048
imversed-wallet-android
MIT License
pipextension/src/main/kotlin/xyz/doikki/videoplayer/pipextension/simple/widget/controller/SimpleViewController.kt
7449
721,554,528
false
{"Kotlin": 56633}
package xyz.doikki.videoplayer.pipextension.simple.widget.controller import android.content.Context import android.view.LayoutInflater import android.view.animation.Animation import androidx.core.view.isVisible import xyz.doikki.videocontroller.component.CompleteView import xyz.doikki.videocontroller.component.ErrorView import xyz.doikki.videocontroller.component.GestureView import xyz.doikki.videocontroller.component.PrepareView import xyz.doikki.videocontroller.component.TitleView import xyz.doikki.videocontroller.component.VodControlView import xyz.doikki.videoplayer.pipextension.VideoManager import xyz.doikki.videoplayer.pipextension.databinding.VideoLayoutPlayOperateViewBinding import xyz.doikki.videoplayer.pipextension.isSingleVideoItem import xyz.doikki.videoplayer.pipextension.simple.develop.SimpleVideoComponent import xyz.doikki.videoplayer.pipextension.simple.develop.SimpleVideoController import xyz.doikki.videoplayer.pipextension.simple.develop.SimpleVideoState internal class SimpleViewController(context: Context) : SimpleVideoController(context) { private val completeView = CompleteView(context) private val errorView = ErrorView(context) private val prepareView = PrepareView(context) private val titleView = TitleView(context) private val vodView = VodControlView(context) private val gestureView = GestureView(context) private val widgetView = SimpleWidgetView(context) fun addControlComponents(title: String) { prepareView.setClickStart() titleView.setTitle(title) addControlComponent( completeView, errorView, prepareView, titleView, vodView, gestureView, preloadComponent ) addControlComponent(widgetView) setEnableInNormal(true) } override fun onBackPressed(): Boolean { if (controlWrapper?.isFullScreen == true) { return stopFullScreen() } return super.onBackPressed() } internal class SimpleWidgetView(context: Context) : SimpleVideoComponent(context) { private val viewBinding = VideoLayoutPlayOperateViewBinding .inflate(LayoutInflater.from(context), this, true) init { viewBinding.next.isVisible = !isSingleVideoItem viewBinding.prev.isVisible = !isSingleVideoItem viewBinding.rotation.setOnClickListener { VideoManager.refreshRotation() } viewBinding.scale.setOnClickListener { VideoManager.refreshScreenScale() } viewBinding.pip.setOnClickListener { VideoManager.entryPipMode() } viewBinding.next.setOnClickListener { VideoManager.videoPlayNext() } viewBinding.prev.setOnClickListener { VideoManager.videoPlayPrev() } } override fun onVisibilityChanged(isVisible: Boolean, anim: Animation) { viewBinding.root.isVisible = isVisible startAnimation(anim) } override fun onPlayStateChanged(state: SimpleVideoState) { viewBinding.root.isVisible = false } } }
0
Kotlin
0
0
60d6ae83b231ecb3c9e590eb6c01374b13109124
3,117
dkvideo_extension
Apache License 2.0
libs/main/polynomial/src/commonBenchmarks/kotlin/main.kt
lounres
516,842,873
false
{"Kotlin": 1745926, "MDX": 22785, "TypeScript": 14785, "CSS": 6651, "JavaScript": 6563}
/* * Copyright © 2023 <NAME> * All rights reserved. Licensed under the Apache License, Version 2.0. See the license in file LICENSE */ @file:Suppress("unused") package dev.lounres.kone.polynomial.benchmarks //import dev.lounres.kone.algebraic.field //import dev.lounres.kone.context.invoke //import dev.lounres.kone.polynomial.ListPolynomial //import dev.lounres.kone.polynomial.listPolynomialSpace //import kotlinx.benchmark.* // //@State(Scope.Benchmark) //class ListPolynomialBenchmark { // @Benchmark // fun stupidTest(blackhole: Blackhole) = Double.field.listPolynomialSpace { // val polynomial = ListPolynomial(1.1, 1.1) // blackhole.consume(polynomial pow 16u) // } //} //
23
Kotlin
0
5
1d3fad2e9cb1a158571b93410f023d1bdca20b40
708
Kone
Apache License 2.0
spring-reactive-kotlin/src/main/kotlin/com/baeldung/reactive.flow/Event.kt
Baeldung
260,481,121
false
null
package com.baeldung.reactive.flow import org.springframework.data.mongodb.core.mapping.Document @Document data class Event(val id: String, val name: String)
14
null
294
465
f1ef5d5ded3f7ddc647f1b6119f211068f704577
160
kotlin-tutorials
MIT License
plugins/ksp/testData/api/javaModifiers.kt
android
263,405,600
true
null
// TEST PROCESSOR: JavaModifierProcessor // EXPECTED: // C: PUBLIC ABSTRACT // staticStr: PRIVATE // s1: FINAL JAVA_TRANSIENT // i1: PROTECTED JAVA_STATIC JAVA_VOLATILE // intFun: JAVA_SYNCHRONIZED JAVA_DEFAULT // foo: ABSTRACT JAVA_STRICT // END // FILE: a.kt annotation class Test @Test class Foo : C() { } // FILE: C.java public abstract class C { private String staticStr = "str" final transient String s1; protected static volatile int i1; default synchronized int intFun() { return 1; } abstract strictfp void foo() {} }
1
Kotlin
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
567
kotlin
Apache License 2.0
app/src/main/java/com/example/tempconverter/view/MainActivity.kt
rabsouza
211,225,020
false
null
package com.example.tempconverter.view import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.example.tempconverter.R import com.example.tempconverter.business.TemperatureCelciusBusiness import com.example.tempconverter.business.TemperatureFahrenheitBusiness import com.example.tempconverter.model.Temperature import com.example.tempconverter.model.Type import com.example.tempconverter.model.format import com.example.tempconverter.presentation.TemperatureContract import com.example.tempconverter.presentation.TemperaturePresenter import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), TemperatureContract.View { lateinit var presenter: TemperaturePresenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) presenter = TemperaturePresenter( this, TemperatureCelciusBusiness(), TemperatureFahrenheitBusiness() ) btnConverterTemp.setOnClickListener { val value = txtTempValue.text.toString().replace(",",".") when { txtTempValue.text.isNullOrBlank() -> { txtTempValue.error = "Você deve informar uma temperatura!" txtTempValue.requestFocus() } rbtTempCelcius.isChecked -> { val temperature = Temperature(value.toDouble(), Type.CELCIUS) presenter.onConverterTemperatureClick(temperature) } else -> { val temperature = Temperature(value.toDouble(), Type.FARENHEIT) presenter.onConverterTemperatureClick(temperature) } } } } override fun showResult(temperature: Double) { txtTempValue.setText(temperature.format(2)) } }
0
Kotlin
0
0
53752da910155945341e6560f2155cec1f27ea5f
1,986
TempConverter
Apache License 2.0
feature-forecast/src/main/java/de/niklasbednarczyk/nbweather/feature/forecast/screens/overview/ForecastOverviewViewModel.kt
NiklasBednarczyk
529,683,941
false
{"Kotlin": 1065284}
package de.niklasbednarczyk.nbweather.feature.forecast.screens.overview import dagger.hilt.android.lifecycle.HiltViewModel import de.niklasbednarczyk.nbweather.core.data.localremote.models.resource.NBResource import de.niklasbednarczyk.nbweather.core.data.localremote.models.resource.NBResource.Companion.flatMapLatestResource import de.niklasbednarczyk.nbweather.core.data.localremote.models.resource.NBResource.Companion.mapResource import de.niklasbednarczyk.nbweather.core.ui.screen.viewmodel.NBViewModel import de.niklasbednarczyk.nbweather.core.ui.swiperefresh.NBSwipeRefreshFlow import de.niklasbednarczyk.nbweather.data.geocoding.repositories.GeocodingRepository import de.niklasbednarczyk.nbweather.data.onecall.repositories.OneCallRepository import de.niklasbednarczyk.nbweather.feature.forecast.screens.overview.models.ForecastOverviewItem import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import javax.inject.Inject @HiltViewModel class ForecastOverviewViewModel @Inject constructor( private val geocodingRepository: GeocodingRepository, private val oneCallRepository: OneCallRepository ) : NBViewModel<ForecastOverviewUiState>(ForecastOverviewUiState()) { val itemsFlow = object : NBSwipeRefreshFlow<List<ForecastOverviewItem>>() { override fun getFlow(forceUpdate: Boolean): Flow<NBResource<List<ForecastOverviewItem>>> { return geocodingRepository.getCurrentLocation() .flatMapLatestResource { currentLocation -> if (currentLocation == null) return@flatMapLatestResource flowOf(NBResource.Loading) val latitude = currentLocation.latitude val longitude = currentLocation.longitude oneCallRepository.getOneCall( latitude = latitude, longitude = longitude, forceUpdate = forceUpdate ).mapResource { oneCall -> ForecastOverviewItem.from( oneCall = oneCall ) } } } } init { collectFlow( { geocodingRepository.getCurrentLocation() }, { oldUiState, output -> oldUiState.copy(locationResource = output) } ) collectFlow( { itemsFlow() }, { oldUiState, output -> oldUiState.copy(itemsResource = output) } ) } }
14
Kotlin
0
1
aa09037fa77f495d6dbf5cdde88e4c2872fc1cf8
2,482
NBWeather
MIT License
shared/src/iosMain/kotlin/com/frybits/arbor/ios/ConsoleBranch.kt
pablobaxter
189,710,395
false
null
package com.frybits.arbor.ios import com.frybits.arbor.Branch import com.frybits.arbor.Level import platform.Foundation.NSLog /** * Frybits * Created by Pablo Baxter (Github: pablobaxter) * * iOS Console logging branch */ class ConsoleBranch : Branch { /** * Base constructor. Defaults to listen only to [Level.Info] logs and accepts all tags */ constructor() : super(Level.Info, listOf()) /** * Constructor accepting the [Level] to filter on. Accepts all tags * * @param level Allow all logs up to this level */ constructor(level: Level) : super(level, listOf()) /** * Constructor accepting a [List] of [String] tags to filter on. [Level] is defaulted to [Level.Info] * * @param tags List of strings that are expected. All other tags will be ignored */ constructor(tags: List<String>) : super(Level.Info, tags) /** * Constructor accepting both a [level] and [tags] parameter. For allowing only selected logs * * @param level Allow all logs up to this level * @param tags List of strings that are expected. All other tags will be ignored */ constructor(level: Level, tags: List<String>) : super(level, tags) override fun onAdd() { //Do nothing } override fun onRemove() { //Do nothing } override fun onLog(level: Level, tag: String, message: String?, throwable: Throwable?) { when (level) { Level.Verbose, Level.Debug, Level.Info -> { println("${level.name}::$tag::${message ?: ""}") throwable?.printStackTrace() } Level.Warn, Level.Error -> { NSLog("${level.name}::$tag::${message ?: ""}\n") throwable?.printStackTrace() } } } }
0
Kotlin
0
1
101d138d0f13ee10d94c6736a97b15bcc2c8a17b
1,820
Arbor
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/cloudfront/CfnDistributionCookiesPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.cloudfront import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import kotlin.collections.Collection import kotlin.collections.MutableList import software.amazon.awscdk.services.cloudfront.CfnDistribution /** * This field is deprecated. * * We recommend that you use a cache policy or an origin request policy instead of this field. * * If you want to include cookies in the cache key, use a cache policy. For more information, see * [Creating cache * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) * in the *Amazon CloudFront Developer Guide* . * * If you want to send cookies to the origin but not include them in the cache key, use an origin * request policy. For more information, see [Creating origin request * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) * in the *Amazon CloudFront Developer Guide* . * * A complex type that specifies whether you want CloudFront to forward cookies to the origin and, * if so, which ones. For more information about forwarding cookies to the origin, see [How CloudFront * Forwards, Caches, and Logs * Cookies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Cookies.html) in the * *Amazon CloudFront Developer Guide* . * * 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.*; * CookiesProperty cookiesProperty = CookiesProperty.builder() * .forward("forward") * // the properties below are optional * .whitelistedNames(List.of("whitelistedNames")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-cloudfront-distribution-cookies.html) */ @CdkDslMarker public class CfnDistributionCookiesPropertyDsl { private val cdkBuilder: CfnDistribution.CookiesProperty.Builder = CfnDistribution.CookiesProperty.builder() private val _whitelistedNames: MutableList<String> = mutableListOf() /** * @param forward This field is deprecated. * We recommend that you use a cache policy or an origin request policy instead of this field. * * If you want to include cookies in the cache key, use a cache policy. For more information, see * [Creating cache * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) * in the *Amazon CloudFront Developer Guide* . * * If you want to send cookies to the origin but not include them in the cache key, use origin * request policy. For more information, see [Creating origin request * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) * in the *Amazon CloudFront Developer Guide* . * * Specifies which cookies to forward to the origin for this cache behavior: all, none, or the * list of cookies specified in the `WhitelistedNames` complex type. * * Amazon S3 doesn't process cookies. When the cache behavior is forwarding requests to an Amazon * S3 origin, specify none for the `Forward` element. */ public fun forward(forward: String) { cdkBuilder.forward(forward) } /** * @param whitelistedNames This field is deprecated. * We recommend that you use a cache policy or an origin request policy instead of this field. * * If you want to include cookies in the cache key, use a cache policy. For more information, see * [Creating cache * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) * in the *Amazon CloudFront Developer Guide* . * * If you want to send cookies to the origin but not include them in the cache key, use an origin * request policy. For more information, see [Creating origin request * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) * in the *Amazon CloudFront Developer Guide* . * * Required if you specify `whitelist` for the value of `Forward` . A complex type that specifies * how many different cookies you want CloudFront to forward to the origin for this cache behavior * and, if you want to forward selected cookies, the names of those cookies. * * If you specify `all` or `none` for the value of `Forward` , omit `WhitelistedNames` . If you * change the value of `Forward` from `whitelist` to `all` or `none` and you don't delete the * `WhitelistedNames` element and its child elements, CloudFront deletes them automatically. * * For the current limit on the number of cookie names that you can whitelist for each cache * behavior, see [CloudFront * Limits](https://docs.aws.amazon.com/general/latest/gr/xrefaws_service_limits.html#limits_cloudfront) * in the *AWS General Reference* . */ public fun whitelistedNames(vararg whitelistedNames: String) { _whitelistedNames.addAll(listOf(*whitelistedNames)) } /** * @param whitelistedNames This field is deprecated. * We recommend that you use a cache policy or an origin request policy instead of this field. * * If you want to include cookies in the cache key, use a cache policy. For more information, see * [Creating cache * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html#cache-key-create-cache-policy) * in the *Amazon CloudFront Developer Guide* . * * If you want to send cookies to the origin but not include them in the cache key, use an origin * request policy. For more information, see [Creating origin request * policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-origin-requests.html#origin-request-create-origin-request-policy) * in the *Amazon CloudFront Developer Guide* . * * Required if you specify `whitelist` for the value of `Forward` . A complex type that specifies * how many different cookies you want CloudFront to forward to the origin for this cache behavior * and, if you want to forward selected cookies, the names of those cookies. * * If you specify `all` or `none` for the value of `Forward` , omit `WhitelistedNames` . If you * change the value of `Forward` from `whitelist` to `all` or `none` and you don't delete the * `WhitelistedNames` element and its child elements, CloudFront deletes them automatically. * * For the current limit on the number of cookie names that you can whitelist for each cache * behavior, see [CloudFront * Limits](https://docs.aws.amazon.com/general/latest/gr/xrefaws_service_limits.html#limits_cloudfront) * in the *AWS General Reference* . */ public fun whitelistedNames(whitelistedNames: Collection<String>) { _whitelistedNames.addAll(whitelistedNames) } public fun build(): CfnDistribution.CookiesProperty { if(_whitelistedNames.isNotEmpty()) cdkBuilder.whitelistedNames(_whitelistedNames) return cdkBuilder.build() } }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
7,571
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/kotlin/ch/empa/openbisio/propertyassignment/PropertyAssignmentVariants.kt
empa-scientific-it
618,383,912
false
null
/* * Copyright 2023 <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. * */ package ch.empa.openbisio.propertyassignment import ch.empa.openbisio.propertytype.PropertyTypeDTO import kotlinx.serialization.Serializable @Serializable sealed class PropertyAssignmentVariants { @Serializable data class NominalAssignment(val name: String) : PropertyAssignmentVariants() @Serializable data class LocalAssignment(val propertyType: PropertyTypeDTO) : PropertyAssignmentVariants() } //object PropertyAssignmentVariantsDeserializer : JsonContentPolymorphicSerializer<Payment>(Payment::class) { // override fun selectDeserializer(content: JsonElement) = when { // "reason" in content.jsonObject -> RefundedPayment.serializer() // else -> SuccessfulPayment.serializer() // } //}
0
Kotlin
0
0
f61b168531320739a3450e9c3f0bb2a0f0299ce0
1,323
instanceio
Apache License 2.0
src/test/kotlin/uk/co/skipoles/eventmodeller/visualisation/image/AvoidBoxesPathRouterTest.kt
skipoleschris
506,202,133
false
{"Kotlin": 119832}
package uk.co.skipoles.eventmodeller.visualisation.image import io.kotest.matchers.collections.shouldContainExactly import java.util.stream.Stream import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.MethodSource @TestInstance(TestInstance.Lifecycle.PER_CLASS) class AvoidBoxesPathRouterTest { private val box = AvoidanceBox(100, 100, 100, 100) private val boxes = listOf(box) private val topLeft = box.topLeftLinePoint() private val topRight = box.topRightLinePoint() private val bottomLeft = box.bottomLeftLinePoint() private val bottomRight = box.bottomRightLinePoint() private val topLtoR = box.topLinePoints(true) private val bottomLtoR = box.bottomLinePoints(true) private val leftTtoB = box.leftLinePoints(true) private val rightTtoB = box.rightLinePoints(true) private val topRtoL = box.topLinePoints(false) private val bottomRtoL = box.bottomLinePoints(false) private val leftBtoT = box.leftLinePoints(false) private val rightBtoT = box.rightLinePoints(false) private val leftUpper = Point(99, 125) private val leftTop = Point(125, 99) private val rightTop = Point(175, 99) private val rightUpper = Point(201, 125) private val rightLower = Point(201, 175) private val rightBottom = Point(175, 201) private val leftBottom = Point(125, 201) private val leftLower = Point(99, 175) @Test fun `paths not needing routing are not changed`() { val path1 = Path(Point(50, 50), Point(250, 50)) val path2 = Path(Point(50, 50), Point(50, 250)) AvoidBoxesPathRouter.routeAroundBoxes(listOf(path1, path2), boxes) shouldContainExactly listOf(path1, path2) } @ParameterizedTest @MethodSource("leftUpperEntries") fun `paths entering via the left upper should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun leftUpperEntries() = Stream.of( ExpectedReroute(Path(leftUpper, leftTop), topLeft), ExpectedReroute(Path(leftUpper, rightTop), topLeft), ExpectedReroute(Path(leftUpper, rightUpper), topLtoR), ExpectedReroute(Path(leftUpper, rightLower), topLtoR), ExpectedReroute(Path(leftUpper, rightBottom), bottomLeft), ExpectedReroute(Path(leftUpper, leftBottom), bottomLeft)) @ParameterizedTest @MethodSource("leftTopEntries") fun `paths entering via the left top should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun leftTopEntries() = Stream.of( ExpectedReroute(Path(leftTop, rightUpper), topRight), ExpectedReroute(Path(leftTop, rightLower), topRight), ExpectedReroute(Path(leftTop, rightBottom), leftTtoB), ExpectedReroute(Path(leftTop, leftBottom), leftTtoB), ExpectedReroute(Path(leftTop, leftLower), topLeft), ExpectedReroute(Path(leftTop, leftUpper), topLeft)) @ParameterizedTest @MethodSource("rightTopEntries") fun `paths entering via the right top should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun rightTopEntries() = Stream.of( ExpectedReroute(Path(rightTop, rightUpper), topRight), ExpectedReroute(Path(rightTop, rightLower), topRight), ExpectedReroute(Path(rightTop, rightBottom), rightTtoB), ExpectedReroute(Path(rightTop, leftBottom), rightTtoB), ExpectedReroute(Path(rightTop, leftLower), topLeft), ExpectedReroute(Path(rightTop, leftUpper), topLeft)) @ParameterizedTest @MethodSource("rightUpperEntries") fun `paths entering via the right upper should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun rightUpperEntries() = Stream.of( ExpectedReroute(Path(rightUpper, rightBottom), bottomRight), ExpectedReroute(Path(rightUpper, leftBottom), bottomRight), ExpectedReroute(Path(rightUpper, leftLower), topRtoL), ExpectedReroute(Path(rightUpper, leftUpper), topRtoL), ExpectedReroute(Path(rightUpper, leftTop), topRight), ExpectedReroute(Path(rightUpper, rightTop), topRight)) @ParameterizedTest @MethodSource("rightLowerEntries") fun `paths entering via the right lower should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun rightLowerEntries() = Stream.of( ExpectedReroute(Path(rightLower, rightBottom), bottomRight), ExpectedReroute(Path(rightLower, leftBottom), bottomRight), ExpectedReroute(Path(rightLower, leftLower), bottomRtoL), ExpectedReroute(Path(rightLower, leftUpper), bottomRtoL), ExpectedReroute(Path(rightLower, leftTop), topRight), ExpectedReroute(Path(rightLower, rightTop), topRight)) @ParameterizedTest @MethodSource("rightBottomEntries") fun `paths entering via the right bottom should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun rightBottomEntries() = Stream.of( ExpectedReroute(Path(rightBottom, leftLower), bottomLeft), ExpectedReroute(Path(rightBottom, leftUpper), bottomLeft), ExpectedReroute(Path(rightBottom, leftTop), rightBtoT), ExpectedReroute(Path(rightBottom, rightTop), rightBtoT), ExpectedReroute(Path(rightBottom, rightUpper), bottomRight), ExpectedReroute(Path(rightBottom, rightLower), bottomRight)) @ParameterizedTest @MethodSource("leftBottomEntries") fun `paths entering via the left bottom should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun leftBottomEntries() = Stream.of( ExpectedReroute(Path(leftBottom, leftLower), bottomLeft), ExpectedReroute(Path(leftBottom, leftUpper), bottomLeft), ExpectedReroute(Path(leftBottom, leftTop), leftBtoT), ExpectedReroute(Path(leftBottom, rightTop), leftBtoT), ExpectedReroute(Path(leftBottom, rightUpper), bottomRight), ExpectedReroute(Path(leftBottom, rightLower), bottomRight)) @ParameterizedTest @MethodSource("leftLowerEntries") fun `paths entering via the left lower should be rerouted correctly`(data: ExpectedReroute) { val outputPath = data.inputPath.insertAfter(data.inputPath.elements.first(), data.expectedAddition) AvoidBoxesPathRouter.routeAroundBoxes(listOf(data.inputPath), boxes) shouldContainExactly listOf(outputPath) } private fun leftLowerEntries() = Stream.of( ExpectedReroute(Path(leftLower, leftTop), topLeft), ExpectedReroute(Path(leftLower, rightTop), topLeft), ExpectedReroute(Path(leftLower, rightUpper), bottomLtoR), ExpectedReroute(Path(leftLower, rightLower), bottomLtoR), ExpectedReroute(Path(leftLower, rightBottom), bottomLeft), ExpectedReroute(Path(leftLower, leftBottom), bottomLeft)) data class ExpectedReroute(val inputPath: Path, val expectedAddition: PathElement) @Test fun `paths can be routed around multiple boxes`() { val box1 = AvoidanceBox(100, 100, 100, 100) val box2 = AvoidanceBox(300, 300, 100, 100) val multipleBoxes = listOf(box1, box2) val path = Path(Point(0, 150), Point(500, 350)) val expectedPoint1 = box1.bottomLeftLinePoint() val expectedPoint2 = box2.topRightLinePoint() val expectedPath = path .insertAfter(path.elements[0], expectedPoint1) .insertAfter(expectedPoint1, expectedPoint2) AvoidBoxesPathRouter.routeAroundBoxes(listOf(path), multipleBoxes) shouldContainExactly listOf(expectedPath) } }
0
Kotlin
0
0
4e7fe756d0c203cd7e781cc40c2b16776aa9f3ab
9,208
event-modeller
Apache License 2.0
kotlin-antd/src/main/kotlin/antd/modal/ConfirmDialog.kt
oxiadenine
206,398,615
false
{"Kotlin": 1619835, "HTML": 1515}
package antd.modal import react.* external object ConfirmDialogComponent : Component<ConfirmDialogProps, State> { override fun render(): ReactElement? } external interface ConfirmDialogProps : ModalFuncProps, Props { var afterClose: (() -> Unit)? var close: (args: Array<Any>) -> Unit override var autoFocusButton: String? /* "ok" | "cancel" */ var rootPrefixCls: String? }
1
Kotlin
8
50
e0017a108b36025630c354c7663256347e867251
397
kotlin-js-wrappers
Apache License 2.0
src/main/java/space/impact/space/api/events/TeleportEvent.kt
GT-IMPACT
596,182,208
false
null
package space.impact.space.api.events import cpw.mods.fml.common.eventhandler.Cancelable import net.minecraft.entity.Entity import net.minecraftforge.event.entity.EntityEvent @Cancelable class TeleportEvent(val entity: Entity?, val x: Int, val y: Int, val z: Int, val dim: Int) : EntityEvent(entity)
0
Kotlin
0
0
bc08703a93b60d0150f38995c74f61f41613da20
301
S.P.A.C.E
MIT License
src/main/kotlin/org/monsim/api/play/Roller.kt
jimdmorgan
310,986,865
false
{"Maven POM": 1, "Ignore List": 1, "Text": 1, "Markdown": 1, "Kotlin": 122, "Java": 2}
package org.monsim.api.play import org.monsim.bean.DiceRoll import org.monsim.bean.RollLogic import org.monsim.bean.domain.Card import org.monsim.bean.domain.Game import org.monsim.bean.domain.Group import org.monsim.bean.domain.Pile import org.monsim.bean.domain.Space interface Roller { fun roll(game: Game) fun mayRoll(game: Game): Boolean fun rollLogic(diceRoll: DiceRoll, game: Game): RollLogic fun applyRollLogic(rollLogic: RollLogic, game: Game): Unit }
1
null
1
1
0c97854234c874a6e5fa4b649ec0ca7719d77c21
481
monsim
MIT License
feature/home/src/main/java/com/conf/mad/todo/home/HomeViewModel.kt
MobileAppDeveloperConference
709,286,274
false
{"Kotlin": 122200}
/* * MIT License * Copyright 2023 MADConference * * 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.conf.mad.todo.home import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.conf.mad.todo.home.model.HomeMenu import com.conf.mad.todo.home.model.HomeUiState import com.conf.mad.todo.home.model.TaskStatus import com.conf.mad.todo.home.model.TaskUiModel import com.conf.mad.todo.task.repository.TaskRepository import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.collections.immutable.toPersistentList import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @HiltViewModel class HomeViewModel @Inject constructor( private val repository: TaskRepository ) : ViewModel() { private val _uiState = MutableStateFlow(HomeUiState()) val uiState = _uiState.asStateFlow() init { viewModelScope.launch { combine( repository.getTodoTasks(), repository.getCompletedTasks(), uiState ) { todoTasks, completedTasks, uiState -> Triple(todoTasks, completedTasks, uiState) }.collect { (todos, completed, uiState) -> _uiState.update { it.copy( todoTasks = todos.filter { task -> if (!uiState.isOnlyFavoriteTaskVisible) { return@filter true } task.isFavorite }.map(TaskUiModel::of).map { task -> if (it.doneTasks.find { doneTask -> doneTask.id == task.id } != null) { task.copy(status = TaskStatus.DONE) } else { task } }.toPersistentList(), completedTasks = completed.filter { task -> if (!uiState.isOnlyFavoriteTaskVisible) { return@filter true } task.isFavorite }.map(TaskUiModel::of).toPersistentList() ) } } } } fun onToggleCompletedTaskVisibility() { _uiState.update { it.copy(isCompletedTaskVisible = !it.isCompletedTaskVisible) } } fun onTaskChanged(item: HomeMenu) { _uiState.update { it.copy(currentDestination = item) } } fun onFavoriteChanged(id: Long, isFavorite: Boolean) { viewModelScope.launch { repository.updateFavorite(id, isFavorite) } } fun onCompletedChanged(id: Long, isCompleted: Boolean) { if (isCompleted) { _uiState.update { val task = it.todoTasks.find { task -> task.id == id } ?: return@update it it.copy( doneTasks = (it.doneTasks + task).toPersistentList() ) } } viewModelScope.launch { if (isCompleted) { delay(500) } repository.updateCompleted(id, isCompleted) _uiState.update { it.copy( doneTasks = it.doneTasks.filter { task -> task.id != id }.toPersistentList() ) } } } fun onSelectTaskToDelete(task: TaskUiModel) { _uiState.update { it.copy(taskToDelete = task) } } fun onDeleteTask() { viewModelScope.launch { val task = uiState.value.taskToDelete ?: return@launch repository.deleteTask(task.asDomain()) _uiState.update { it.copy(taskToDelete = null) } } } fun onDismissDeleteDialog() { _uiState.update { it.copy(taskToDelete = null) } } }
9
Kotlin
3
35
7076043390857ef25498b4e41add5c1f82abe28b
5,205
android
MIT License
utils/src/main/kotlin/dev/abla/utils/BackingField.kt
AndreBaltazar8
259,757,875
false
{"Gradle Kotlin DSL": 10, "Markdown": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Kotlin": 81, "INI": 1, "Java": 1, "ANTLR": 2, "XML": 10}
package dev.abla.utils import java.lang.ref.ReferenceQueue import java.util.concurrent.ConcurrentHashMap import kotlin.concurrent.thread import kotlin.reflect.KProperty class BackingField<K, V>(val default: () -> V) { companion object { fun <K, V> nullable() = BackingField<K, V?> { null } private val backingFieldsMap = ConcurrentHashMap<ReferenceQueue<*>, BackingField<*, *>>() init { thread(isDaemon = true) { while (true) { for ((queue, backingField) in backingFieldsMap) { val reference = queue.poll() ?: continue backingField.map.remove(reference) } Thread.sleep(10) } } } } private val referenceQueue = ReferenceQueue<K>() private val map = ConcurrentHashMap<IdentityWeakReference<K>, V>() operator fun getValue(thisRef: K, property: KProperty<*>): V = map[thisRef.identity()] ?: default() operator fun setValue(thisRef: K, property: KProperty<*>, value: V) { if (value == null) map.remove(thisRef.identity()) else map[thisRef.identity()] = value } init { backingFieldsMap[referenceQueue] = this } private fun K.identity() = IdentityWeakReference(this, referenceQueue) }
0
Kotlin
1
3
f14350cebfe7ca116c4884d136bfe36f7c7f47b7
1,379
ablac
MIT License
compiler/testData/diagnostics/tests/multiplatform/actualAnnotationsNotMatchExpect/valueParameters.kt
JetBrains
3,432,266
false
null
// MODULE: m1-common // FILE: common.kt @Target(AnnotationTarget.VALUE_PARAMETER) annotation class Ann expect fun inMethod(@Ann arg: String) expect class InConstructor(@Ann arg: String) expect fun withIncopatibility<!NO_ACTUAL_FOR_EXPECT{JVM}!>(@Ann p1: String, @Ann p2: String)<!> // MODULE: m1-jvm()()(m1-common) // FILE: jvm.kt actual fun <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>inMethod<!>(arg: String) {} actual class InConstructor <!ACTUAL_ANNOTATIONS_NOT_MATCH_EXPECT!>actual constructor(arg: String)<!> {} actual fun withIncopatibility<!ACTUAL_WITHOUT_EXPECT!>(p1: String)<!> {}
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
592
kotlin
Apache License 2.0
app/src/main/kotlin/com/ttvnp/ttj_asset_android_client/presentation/ui/data/NotificationType.kt
ttvnp
109,772,404
false
null
package com.ttvnp.ttj_asset_android_client.presentation.ui.data enum class NotificationType(val rawValue: String) { NOTIFICATION_TYPE_DEFAULT(""), NOTIFICATION_TYPE_RECEIVE_PAYMENT("receive_payment") }
5
Kotlin
1
1
3a99c9d5b8362dbc5785c8849b8680405acb6a3a
211
ttj-asset-android-client
Apache License 1.1
app/src/main/java/github/alexzhirkevich/studentbsuby/ui/screens/drawer/hostel/HostelScreen.kt
alexzhirkevich
452,910,975
false
null
package github.alexzhirkevich.studentbsuby.ui.screens.drawer.hostel import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Place import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.zIndex import androidx.hilt.navigation.compose.hiltViewModel import com.google.accompanist.insets.navigationBarsWithImePadding import com.google.accompanist.insets.statusBarsHeight import com.google.accompanist.swiperefresh.SwipeRefresh import com.google.accompanist.swiperefresh.rememberSwipeRefreshState import com.skydoves.landscapist.glide.GlideImage import github.alexzhirkevich.studentbsuby.R import github.alexzhirkevich.studentbsuby.data.models.HostelAdvert import github.alexzhirkevich.studentbsuby.repo.HostelState import github.alexzhirkevich.studentbsuby.ui.common.BsuProgressBar import github.alexzhirkevich.studentbsuby.ui.common.BsuProgressBarSwipeRefreshIndicator import github.alexzhirkevich.studentbsuby.ui.common.NavigationMenuButton import github.alexzhirkevich.studentbsuby.ui.common.ErrorScreen import github.alexzhirkevich.studentbsuby.util.DataState import github.alexzhirkevich.studentbsuby.util.Updatable import github.alexzhirkevich.studentbsuby.util.bsuBackgroundPattern import github.alexzhirkevich.studentbsuby.util.communication.collectAsState import github.alexzhirkevich.studentbsuby.util.valueOrNull import me.onebone.toolbar.CollapsingToolbarScaffold import me.onebone.toolbar.ExperimentalToolbarApi import me.onebone.toolbar.ScrollStrategy import me.onebone.toolbar.rememberCollapsingToolbarScaffoldState @ExperimentalToolbarApi @ExperimentalMaterialApi @Composable fun HostelScreen( isTablet : Boolean, onMenuClicked : () -> Unit, hostelViewModel: HostelViewModel = hiltViewModel() ) { val state by hostelViewModel.hostelStateCommunication .collectAsState() when (state) { is DataState.Success<*> -> { when (val value = state.valueOrNull()) { is HostelState.Provided -> ProvidedHostelScreen( isTablet = isTablet, address = value.address, onMenuClicked = onMenuClicked, onShowOnMapClicked = { hostelViewModel.handle(HostelEvent.ShowHostelOnMapClicked( value )) }, image = hostelViewModel.getHostelImage(value), updater = hostelViewModel ) is HostelState.NotProvided -> NonProvidedHostelScreen( isTablet, ads = value.adverts, viewModel = hostelViewModel, onMenuClicked = onMenuClicked ) } } is DataState.Loading -> LoadingHostelScreen( isTablet = isTablet, onMenuClicked = onMenuClicked, ) is DataState.Empty -> ErrorScreen( isTablet=isTablet, toolbarText = stringResource(id = R.string.hostel), onMenuClicked = onMenuClicked, updater = hostelViewModel, error = stringResource(id = R.string.error_load_timetable) ) is DataState.Error -> ErrorScreen( isTablet = isTablet, toolbarText = stringResource(id = R.string.hostel), onMenuClicked = onMenuClicked, updater = hostelViewModel, error = stringResource(id = (state as DataState.Error).message) ) } } @Composable fun LoadingHostelScreen( isTablet: Boolean, onMenuClicked: () -> Unit = {} ) { Box( Modifier .fillMaxSize() .bsuBackgroundPattern( MaterialTheme.colors.primary.copy(alpha = .05f), true ), ) { Column( Modifier .background(MaterialTheme.colors.secondary) .zIndex(2f) ) { Spacer(modifier = Modifier.statusBarsHeight()) TopAppBar( elevation = 0.dp, backgroundColor = Color.Transparent ) { if (!isTablet) { NavigationMenuButton(onClick = onMenuClicked) } Text( text = stringResource(id = R.string.hostel), color = MaterialTheme.colors.onSecondary, style = MaterialTheme.typography.subtitle1 ) } } BsuProgressBar( modifier = Modifier.align(Alignment.Center), tint = MaterialTheme.colors.primary ) } } @ExperimentalToolbarApi @Composable private fun ProvidedHostelScreen( isTablet: Boolean, address : String, onMenuClicked: () -> Unit, onShowOnMapClicked : () -> Unit, image : String?=null, updater : Updatable ) { val scaffoldState = rememberCollapsingToolbarScaffoldState() val refreshState = rememberSwipeRefreshState( isRefreshing = updater.isUpdating.collectAsState().value ) LaunchedEffect(Unit) { scaffoldState.toolbarState.collapse(0) scaffoldState.toolbarState.expand(500) } CollapsingToolbarScaffold( modifier = Modifier.fillMaxSize(), state = scaffoldState, enabled = false, scrollStrategy = ScrollStrategy.ExitUntilCollapsed, toolbarModifier = Modifier.background(MaterialTheme.colors.secondary), toolbar = { Column(Modifier.zIndex(2f)) { Spacer(modifier = Modifier.statusBarsHeight()) TopAppBar( backgroundColor = Color.Transparent, elevation = 0.dp ) { if (!isTablet) { NavigationMenuButton(onClick = onMenuClicked) } AnimatedVisibility(visible = scaffoldState.toolbarState.progress == 0f) { Text( text = stringResource(id = R.string.hostel), color = MaterialTheme.colors.onSecondary, style = MaterialTheme.typography.subtitle1 ) } } } image?.let { GlideImage( imageModel = it, modifier = Modifier .fillMaxWidth() .aspectRatio(1.4f) .alpha(scaffoldState.toolbarState.progress), loading = { BsuProgressBar( modifier = Modifier.align(Alignment.Center), tint = MaterialTheme.colors.primary ) } ) } }) { SwipeRefresh( state = refreshState, swipeEnabled = scaffoldState.toolbarState.progress == 1f, onRefresh = updater::update, indicator = { state,offset-> BsuProgressBarSwipeRefreshIndicator(state = state, trigger = offset) }, modifier = Modifier .fillMaxSize() .bsuBackgroundPattern( MaterialTheme.colors.primary.copy(alpha = .05f), true ) ) { Column( Modifier .graphicsLayer { translationY = refreshState.indicatorOffset } .fillMaxSize() .verticalScroll(rememberScrollState()), horizontalAlignment = Alignment.CenterHorizontally ) { Card( modifier = Modifier .padding( horizontal = 30.dp, vertical = 30.dp ) .widthIn(max = 400.dp), elevation = 3.dp, backgroundColor = MaterialTheme.colors.secondary, ) { Column( modifier = Modifier .padding(20.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text( text = stringResource(id = R.string.hostel_provided), style = MaterialTheme.typography.h2, textAlign = TextAlign.Center ) Spacer(modifier = Modifier.height(10.dp)) Text( text = address, textAlign = TextAlign.Center, style = MaterialTheme.typography.subtitle1 ) } } Button( onClick = onShowOnMapClicked, ) { Row( verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.Default.Place, tint = MaterialTheme.colors.onPrimary, contentDescription = "Show on map" ) Spacer(modifier = Modifier.width(10.dp)) Text( text = stringResource(id = R.string.show_on_map), color = MaterialTheme.colors.onPrimary ) } } } } } } @ExperimentalMaterialApi @Composable private fun NonProvidedHostelScreen( isTablet: Boolean, ads : List<HostelAdvert>, viewModel: HostelViewModel, onMenuClicked: () -> Unit, ) { var needShowDialog by rememberSaveable { mutableStateOf(true) } if (needShowDialog) { Dialog(onDismissRequest = { needShowDialog = false }) { Card(backgroundColor = MaterialTheme.colors.secondary) { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding( horizontal = 10.dp, vertical = 5.dp ) ) { Text( text = stringResource(id = R.string.hostel_not_provided), style = MaterialTheme.typography.subtitle1, textAlign = TextAlign.Center, ) Spacer(modifier = Modifier.height(10.dp)) Text( text = stringResource(id = R.string.hostel_not_provided_ext), style = MaterialTheme.typography.body1, textAlign = TextAlign.Center, ) Spacer(modifier = Modifier.height(10.dp)) TextButton( onClick = { needShowDialog=false }, modifier = Modifier .fillMaxWidth() ) { Text( text = stringResource(id = R.string.close), color = MaterialTheme.colors.onSecondary ) } } } } } val scaffoldState = rememberCollapsingToolbarScaffoldState() val refreshState = rememberSwipeRefreshState( isRefreshing = viewModel.isUpdating.collectAsState().value ) Column { Spacer( modifier = Modifier .zIndex(2f) .fillMaxWidth() .statusBarsHeight() .background(MaterialTheme.colors.secondary) ) CollapsingToolbarScaffold( modifier = Modifier .fillMaxSize() .zIndex(1f), state = scaffoldState, scrollStrategy = ScrollStrategy.EnterAlwaysCollapsed, toolbarModifier = Modifier.background(MaterialTheme.colors.secondary), toolbar = { Column( modifier = Modifier.animateContentSize() ) { TopAppBar( backgroundColor = Color.Transparent, elevation = 1.dp ) { if (!isTablet) { NavigationMenuButton(onClick = onMenuClicked) } Text( text = stringResource(id = R.string.hostel), color = MaterialTheme.colors.onSecondary, style = MaterialTheme.typography.subtitle1 ) } } }) { SwipeRefresh( state = refreshState, onRefresh = viewModel::update, indicator = { state, offset -> BsuProgressBarSwipeRefreshIndicator(state = state, trigger = offset) }, modifier = Modifier .fillMaxSize() .bsuBackgroundPattern( MaterialTheme.colors.primary.copy(alpha = .05f), true ) ) { LazyColumn( modifier = Modifier .fillMaxSize() .graphicsLayer { translationY = refreshState.indicatorOffset } ) { items(ads.size) { HostelAdWidget( modifier = Modifier .padding(5.dp), ad = ads[it], onLocateClicked = { viewModel.handle(HostelEvent.ShowAdOnMapClicked(ads[it])) }, onCallClicked = { viewModel.handle(HostelEvent.CallClicked(ads[it])) } ) } item { Spacer(modifier = Modifier.navigationBarsWithImePadding()) } } } } } }
0
null
0
5
bf04ce772bb3d9485dffd5d3abf252be1754ce51
15,418
student-bsu-by
MIT License
timelytextview/src/main/java/com/github/adnansm/timelytextview/model/number/Zero.kt
chadmorrow
344,404,738
true
{"Kotlin": 16626}
package com.github.adnansm.timelytextview.model.number import com.github.adnansm.timelytextview.model.core.Figure object Zero : Figure(arrayOf( floatArrayOf(0.24585635359116f, 0.552486187845304f), floatArrayOf(0.24585635359116f, 0.331491712707182f), floatArrayOf(0.370165745856354f, 0.0994475138121547f), floatArrayOf(0.552486187845304f, 0.0994475138121547f), floatArrayOf(0.734806629834254f, 0.0994475138121547f), floatArrayOf(0.861878453038674f, 0.331491712707182f), floatArrayOf(0.861878453038674f, 0.552486187845304f), floatArrayOf(0.861878453038674f, 0.773480662983425f), floatArrayOf(0.734806629834254f, 0.994475138121547f), floatArrayOf(0.552486187845304f, 0.994475138121547f), floatArrayOf(0.370165745856354f, 0.994475138121547f), floatArrayOf(0.24585635359116f, 0.773480662983425f), floatArrayOf(0.24585635359116f, 0.552486187845304f) )) { val instance: Zero = Zero }
0
Kotlin
0
0
7a9ac1db142939ac32f6fab6b362ccb5d3d5df52
936
TimelyTextView
Apache License 2.0
src/test/java/org/jetbrains/plugins/ideavim/action/change/change/number/ChangeNumberIncActionTest.kt
JetBrains
1,459,486
false
null
/* * Copyright 2003-2023 The IdeaVim authors * * Use of this source code is governed by an MIT-style * license that can be found in the LICENSE.txt file or at * https://opensource.org/licenses/MIT. */ package org.jetbrains.plugins.ideavim.action.change.change.number import com.maddyhome.idea.vim.command.VimStateMachine import com.maddyhome.idea.vim.helper.VimBehaviorDiffers import org.jetbrains.plugins.ideavim.VimTestCase import org.junit.jupiter.api.Test class ChangeNumberIncActionTest : VimTestCase() { @VimBehaviorDiffers(originalVimAfter = "11X0") @Test fun `test inc fancy number`() { doTest("<C-A>", "1${c}0X0", "10X1", VimStateMachine.Mode.COMMAND, VimStateMachine.SubMode.NONE) } }
6
null
749
9,241
66b01b0b0d48ffec7b0148465b85e43dfbc908d3
716
ideavim
MIT License
app/src/main/java/com/example/kbbikamusbesarbahasaindonesia/presentation/words/WordFragment.kt
arrazyfathan
469,381,116
false
null
package com.example.kbbikamusbesarbahasaindonesia.presentation.words import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Bundle import android.view.* import android.widget.Toast import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import com.example.kbbikamusbesarbahasaindonesia.R import com.example.kbbikamusbesarbahasaindonesia.core.data.Resource import com.example.kbbikamusbesarbahasaindonesia.core.data.source.local.KosaKata import com.example.kbbikamusbesarbahasaindonesia.core.domain.model.ListWordModel import com.example.kbbikamusbesarbahasaindonesia.core.domain.model.WordModel import com.example.kbbikamusbesarbahasaindonesia.databinding.FragmentWordBinding import com.example.kbbikamusbesarbahasaindonesia.presentation.adapter.KosaKataAdapter import com.example.kbbikamusbesarbahasaindonesia.presentation.detail.DetailActivity import com.example.kbbikamusbesarbahasaindonesia.utils.toJson import com.example.kbbikamusbesarbahasaindonesia.utils.viewBinding import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import com.jakewharton.rxbinding4.widget.textChanges import org.koin.androidx.viewmodel.ext.android.viewModel import java.io.IOException class WordFragment : Fragment(R.layout.fragment_word) { private val binding by viewBinding(FragmentWordBinding::bind) private val viewModel: WordViewModel by viewModel() private lateinit var adapter: KosaKataAdapter @SuppressLint("CheckResult", "NotifyDataSetChanged") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val jsonFileString = getJsonDataFromAsset(requireActivity(), "entries.json") val gson = GsonBuilder().create() val listKosaKata = object : TypeToken<KosaKata>() {}.type val list: KosaKata = gson.fromJson(jsonFileString, listKosaKata) binding.rvListKosaKata.layoutManager = LinearLayoutManager(requireContext()) adapter = KosaKataAdapter(list) { getMeaningOfWord(it) } binding.rvListKosaKata.adapter = adapter binding.editTextSearchWord.textChanges() .skipInitialValue() .subscribe { text -> if (text.toString().isEmpty()) { binding.rvListKosaKata.adapter = KosaKataAdapter(list) { getMeaningOfWord(it) } adapter.notifyDataSetChanged() } else { adapter.filter.filter(text) binding.rvListKosaKata.adapter = KosaKataAdapter(adapter.kataFilterList) { getMeaningOfWord(it) } } } } private fun getMeaningOfWord(word: String) { viewModel.getMeaningOfWord(word).observe(viewLifecycleOwner) { result -> if (result != null) { when (result) { is Resource.Loading -> showLoadingState(true) is Resource.Success -> { showLoadingState(false) navigateToDetail(result, word) } is Resource.Error -> { binding.loadingState.visibility = View.GONE Toast.makeText( requireContext(), "${result.message}", Toast.LENGTH_SHORT, ).show() } } } } } private fun navigateToDetail(result: Resource.Success<List<WordModel>>, word: String) { val listWordModel = ListWordModel( word = word, listWords = result.data!!, ).toJson() startActivity( Intent(requireActivity(), DetailActivity::class.java).putExtra( "data", listWordModel, ), ) } private fun getJsonDataFromAsset(context: Context, fileName: String): String? { val jsonString: String try { jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() } } catch (ioException: IOException) { ioException.printStackTrace() return null } return jsonString } private fun showLoadingState(state: Boolean) { if (state) { binding.loadingState.visibility = View.VISIBLE } else { binding.loadingState.visibility = View.GONE } } }
0
Kotlin
1
5
52bebe8c7b86e03959cfffb66ee245ed92969e1f
4,675
kbbi
Apache License 2.0
domain/src/main/java/com/depromeet/threedays/domain/usecase/auth/CreateMemberUserCase.kt
depromeet12th
548,194,728
false
null
package com.depromeet.threedays.domain.usecase.auth import com.depromeet.threedays.domain.entity.auth.SignupMember import com.depromeet.threedays.domain.entity.member.AuthenticationProvider import com.depromeet.threedays.domain.exception.ThreeDaysException import com.depromeet.threedays.domain.repository.AuthRepository import javax.inject.Inject class CreateMemberUserCase @Inject constructor( private val authRepository: AuthRepository ) { suspend operator fun invoke( certificationSubject: AuthenticationProvider, socialToken: String ): Result<SignupMember> { return authRepository.createMember( certificationSubject = certificationSubject, socialToken = socialToken ).onSuccess { authRepository.saveTokensToLocal(it.token) }.onFailure { throw it as ThreeDaysException } } }
0
Kotlin
1
15
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
893
three-days-android
MIT License
domain/src/main/java/com/depromeet/threedays/domain/usecase/auth/CreateMemberUserCase.kt
depromeet12th
548,194,728
false
null
package com.depromeet.threedays.domain.usecase.auth import com.depromeet.threedays.domain.entity.auth.SignupMember import com.depromeet.threedays.domain.entity.member.AuthenticationProvider import com.depromeet.threedays.domain.exception.ThreeDaysException import com.depromeet.threedays.domain.repository.AuthRepository import javax.inject.Inject class CreateMemberUserCase @Inject constructor( private val authRepository: AuthRepository ) { suspend operator fun invoke( certificationSubject: AuthenticationProvider, socialToken: String ): Result<SignupMember> { return authRepository.createMember( certificationSubject = certificationSubject, socialToken = socialToken ).onSuccess { authRepository.saveTokensToLocal(it.token) }.onFailure { throw it as ThreeDaysException } } }
0
Kotlin
1
15
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
893
three-days-android
MIT License
src/main/kotlin/day13/part1/Part1.kt
bagguley
329,976,670
false
null
package day13.part1 import day13.data fun main() { val timetable = data val depart = timetable[0].toInt() val busses = timetable[1].split(",").filter{ it != "x"}.map { it.toInt() } val x = busses.map{calc(depart, it)}.minByOrNull { it.second } val wait = x!!.second - depart println(x.first * wait) } fun calc(depart: Int, bus: Int): Pair<Int,Int> { return bus to if (depart % bus == 0) { depart } else { ((depart / bus) + 1) * bus } }
0
Kotlin
0
0
6afa1b890924e9459f37c604b4b67a8f2e95c6f2
493
adventofcode2020
MIT License
app/src/main/java/app/klimatic/data/remote/service/WeatherService.kt
developer-shivam
374,342,429
false
null
package app.klimatic.data.remote.service import app.klimatic.data.remote.weather.WeatherResponse import retrofit2.http.GET import retrofit2.http.Query interface WeatherService { @GET("/v1/forecast.json") suspend fun fetchWeather( @Query("q") query: String? ): WeatherResponse }
0
Kotlin
2
34
a46582676223c4faaba5e8dad436dbc46da70f8b
301
Klimatic
Apache License 2.0
app/src/main/java/io/swiftfest/www/swiftfest/views/agenda/ScheduleAdapterItemHeader.kt
shalomhalbert
131,078,678
true
{"Kotlin": 102537}
package com.mentalmachines.droidcon_boston.views.agenda import android.view.View import android.widget.TextView import com.mentalmachines.droidcon_boston.R import eu.davidea.flexibleadapter.FlexibleAdapter import eu.davidea.flexibleadapter.items.AbstractHeaderItem import eu.davidea.viewholders.FlexibleViewHolder /** * Sticky header for schedule view */ class ScheduleAdapterItemHeader internal constructor(private val sessionTime: String) : AbstractHeaderItem<ScheduleAdapterItemHeader.ViewHolder>() { override fun equals(other: Any?): Boolean { if (other is ScheduleAdapterItemHeader) { val inItem = other as ScheduleAdapterItemHeader? return this.sessionTime == inItem!!.sessionTime } return false } override fun hashCode(): Int { return sessionTime.hashCode() } override fun getLayoutRes(): Int { return R.layout.schedule_item_header } override fun createViewHolder(view: View, adapter: FlexibleAdapter<*>): ViewHolder { return ScheduleAdapterItemHeader.ViewHolder(view, adapter, true) } override fun bindViewHolder(adapter: FlexibleAdapter<*>, holder: ScheduleAdapterItemHeader.ViewHolder, position: Int, payloads: List<*>) { holder.header.text = sessionTime } class ViewHolder : FlexibleViewHolder { lateinit var header: TextView constructor(view: View, adapter: FlexibleAdapter<*>) : super(view, adapter) { findViews(view) } internal constructor(view: View, adapter: FlexibleAdapter<*>, stickyHeader: Boolean) : super(view, adapter, stickyHeader) { findViews(view) } private fun findViews(parent: View) { header = parent.findViewById(R.id.header_text) } } }
16
Kotlin
0
0
cafff8220bae5b169ee565e6f6e399dbc845840b
1,933
conference-app-android
MIT License
app/src/main/java/com/qornanali/footballclubkt/feature/detailteam/DisplayDetailTeamActivity.kt
qornanali
135,668,811
false
{"Kotlin": 113046, "Java": 114}
package com.qornanali.footballclubkt.feature.detailteam import android.database.sqlite.SQLiteConstraintException import android.support.design.widget.TabLayout import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v4.view.ViewPager import android.support.v7.widget.Toolbar import android.view.Menu import android.view.MenuItem import com.google.gson.Gson import com.qornanali.footballclub_kotlin.R import com.qornanali.footballclubkt.adapter.PagerAdapter import com.qornanali.footballclubkt.data.ApiRepository import com.qornanali.footballclubkt.data.database import com.qornanali.footballclubkt.feature.BaseActivity import com.qornanali.footballclubkt.model.FavoriteTeam import com.qornanali.footballclubkt.model.Team import org.jetbrains.anko.db.classParser import org.jetbrains.anko.db.select import org.jetbrains.anko.find import org.jetbrains.anko.toast class DisplayDetailTeamActivity : BaseActivity<DisplayDetailTeamAPresenter, DisplayDetailTeamAView>(), DisplayDetailTeamAView { private lateinit var viewPager: ViewPager private lateinit var toolbar: Toolbar private lateinit var tabLayout: TabLayout private lateinit var pagerAdapter: PagerAdapter private var favoriteMenu: MenuItem? = null var team: Team? = null override fun attachLayout(): Int { return R.layout.activity_detailteam } override fun onInitializeViews() { team = intent.extras.getSerializable("team") as Team toolbar = find(R.id.toolbar) viewPager = find(R.id.view_pager) tabLayout = find(R.id.tab_layout) pagerAdapter = PagerAdapter(supportFragmentManager) setSupportActionBar(toolbar) supportActionBar?.setDisplayShowHomeEnabled(true) supportActionBar?.setDisplayHomeAsUpEnabled(true) viewPager.adapter = pagerAdapter tabLayout.setupWithViewPager(viewPager) presenter.loadTeamInfo(team) presenter.setTabs(resources) } override fun attachPresenter(): DisplayDetailTeamAPresenter { return DisplayDetailTeamAPresenter(Gson(), ApiRepository(), this) } override fun displayActionBarTitle(title: String?) { supportActionBar?.title = title } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_detail_event, menu) favoriteMenu = menu?.getItem(0) if (checkFavorited()) { setMenuItemIcon(favoriteMenu, R.drawable.ic_action_star_2) } return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when (item?.itemId) { android.R.id.home -> finish() R.id.m_action_favorites -> { val statusFavorited = checkFavorited() if (statusFavorited) { presenter.removeFromFavorite(team?.idTeam, database) } else { presenter.addToFavorite(team, database) } } else -> { return super.onOptionsItemSelected(item) } } return true } override fun displayTabs(fragments: List<Fragment>, titles: List<String>) { for (i in 0..fragments.size - 1) { pagerAdapter.addFragment(fragment = fragments.get(i), title = titles.get(i)) } pagerAdapter.notifyDataSetChanged() } private fun setMenuItemIcon(menuItem: MenuItem?, drawable: Int) { menuItem?.icon = ContextCompat.getDrawable(this, drawable) } override fun showError(message: CharSequence?) { if (message != null) { toast(message) } } override fun successRemovedFromFavorite() { toast(resources.getString(R.string.removed_from_favorites)) setMenuItemIcon(favoriteMenu, R.drawable.ic_action_star) } override fun successAddedToFavorite() { toast(resources.getString(R.string.added_to_favorites)) setMenuItemIcon(favoriteMenu, R.drawable.ic_action_star_2) } private fun checkFavorited(): Boolean { var favorited = false try { database.use { val q = select(FavoriteTeam.TABLE_FAVORITETEAM, FavoriteTeam.FIELD_IDTEAM) .whereArgs("(FIELD_IDTEAM = {value})", "value" to (team?.idTeam ?: "")) val listFavorites = q.parseList(classParser<String>()) favorited = !listFavorites.isEmpty() } } catch (e: SQLiteConstraintException) { showError(e.message) } return favorited } }
0
Kotlin
0
2
19f4e5511b6b90d47844defcf01d72537b641d3f
4,683
FootballClub-Kotlin
Apache License 2.0
app/src/main/java/com/jordantuffery/githubreader/viewcontroler/MainActivity.kt
TufferyJordan
131,753,901
false
null
package com.jordantuffery.githubreader.viewcontroler import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.support.v7.app.AppCompatActivity import com.jordantuffery.githubreader.GithubInterface import com.jordantuffery.githubreader.R import com.jordantuffery.githubreader.model.User import com.jordantuffery.githubreader.model.UserDetails import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), UserDetailsListener, UserAvatarListener { private val github = GithubInterface() private val user = User.GOOGLE private var userDetails: UserDetails? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onStart() { super.onStart() // fetch UI data github.requestUserDetails(user, this) user_blog_button.setOnClickListener { if (userDetails != null) { val intent = Intent(this, BlogActivity::class.java).apply { val blogUrl = userDetails?.blog if (blogUrl != null) { putExtra(EXTRA_BLOG_URL, blogUrl) } } startActivity(intent) } } user_repo_button.setOnClickListener { if (userDetails != null) { val intent = Intent(this, ReposActivity::class.java).apply { val reposUrl = userDetails?.repos_url if (reposUrl != null) { putExtra(EXTRA_REPOS_URL, reposUrl) } } startActivity(intent) } } } override fun onReceiveUserDetails(userDetails: UserDetails) { this.userDetails = userDetails if (userDetails.avatar_url != null) { github.requestAvatarFromUserDetails(userDetails.avatar_url, this) } user_name_text.text = userDetails.name user_url_text.text = user.short_url user_location_text.text = userDetails.location } override fun onReceiveUserAvatar(avatar: Bitmap) { user_avatar_image.setImageBitmap(avatar) } companion object { const val EXTRA_BLOG_URL = "EXTRA_BLOG_URL" const val EXTRA_REPOS_URL = "EXTRA_REPOS_URL" } } interface UserDetailsListener { fun onReceiveUserDetails(userDetails: UserDetails) } interface UserAvatarListener { fun onReceiveUserAvatar(avatar: Bitmap) }
0
Kotlin
0
0
93ccbc7c11561fabd0dc5abdefa5c4ada092a381
2,593
github-app
Apache License 2.0
kmath-geometry/src/commonMain/kotlin/space/kscience/kmath/geometry/euclidean3d/Float32Space3D.kt
SciProgCentre
129,486,382
false
null
package space.kscience.visionforge.solid import kotlinx.serialization.KSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import space.kscience.kmath.geometry.GeometrySpace import space.kscience.kmath.geometry.Vector3D import space.kscience.kmath.operations.ScaleOperations import kotlin.math.pow import kotlin.math.sqrt @Serializable(Float32Euclidean3DSpace.VectorSerializer::class) public interface Float32Vector3D: Vector3D<Float> public object Float32Euclidean3DSpace : GeometrySpace<Float32Vector3D>, ScaleOperations<Float32Vector3D>{ @Serializable @SerialName("Float32Vector3D") private data class Vector3DImpl( override val x: Float, override val y: Float, override val z: Float, ) : Float32Vector3D public object VectorSerializer : KSerializer<Float32Vector3D> { private val proxySerializer = Vector3DImpl.serializer() override val descriptor: SerialDescriptor get() = proxySerializer.descriptor override fun deserialize(decoder: Decoder): Float32Vector3D = decoder.decodeSerializableValue(proxySerializer) override fun serialize(encoder: Encoder, value: Float32Vector3D) { val vector = value as? Vector3DImpl ?: Vector3DImpl(value.x, value.y, value.z) encoder.encodeSerializableValue(proxySerializer, vector) } } public fun vector(x: Float, y: Float, z: Float): Float32Vector3D = Vector3DImpl(x, y, z) public fun vector(x: Number, y: Number, z: Number): Float32Vector3D = vector(x.toFloat(), y.toFloat(), z.toFloat()) override val zero: Float32Vector3D by lazy { vector(0.0, 0.0, 0.0) } override fun norm(arg: Float32Vector3D): Double = sqrt(arg.x.pow(2) + arg.y.pow(2) + arg.z.pow(2)).toDouble() public fun Float32Vector3D.norm(): Double = norm(this) override fun Float32Vector3D.unaryMinus(): Float32Vector3D = vector(-x, -y, -z) override fun Float32Vector3D.distanceTo(other: Float32Vector3D): Double = (this - other).norm() override fun add(left: Float32Vector3D, right: Float32Vector3D): Float32Vector3D = vector(left.x + right.x, left.y + right.y, left.z + right.z) override fun scale(a: Float32Vector3D, value: Double): Float32Vector3D = vector(a.x * value, a.y * value, a.z * value) override fun Float32Vector3D.dot(other: Float32Vector3D): Double = (x * other.x + y * other.y + z * other.z).toDouble() private fun leviCivita(i: Int, j: Int, k: Int): Int = when { // even permutation i == 0 && j == 1 && k == 2 -> 1 i == 1 && j == 2 && k == 0 -> 1 i == 2 && j == 0 && k == 1 -> 1 // odd permutations i == 2 && j == 1 && k == 0 -> -1 i == 0 && j == 2 && k == 1 -> -1 i == 1 && j == 0 && k == 2 -> -1 else -> 0 } /** * Compute vector product of [first] and [second]. The basis is assumed to be right-handed. */ public fun vectorProduct( first: Float32Vector3D, second: Float32Vector3D, ): Float32Vector3D { var x = 0.0 var y = 0.0 var z = 0.0 for (j in (0..2)) { for (k in (0..2)) { x += leviCivita(0, j, k) * first[j] * second[k] y += leviCivita(1, j, k) * first[j] * second[k] z += leviCivita(2, j, k) * first[j] * second[k] } } return vector(x, y, z) } /** * Vector product in a right-handed basis */ public infix fun Float32Vector3D.cross(other: Float32Vector3D): Float32Vector3D = vectorProduct(this, other) public val xAxis: Float32Vector3D = vector(1.0, 0.0, 0.0) public val yAxis: Float32Vector3D = vector(0.0, 1.0, 0.0) public val zAxis: Float32Vector3D = vector(0.0, 0.0, 1.0) } public fun Float32Vector3D(x: Number, y: Number, z: Number): Float32Vector3D = Float32Euclidean3DSpace.vector(x,y,z)
91
null
6
600
83d9e1f0afb3024101a2f90a99b54f2a8b6e4212
4,111
kmath
Apache License 2.0
music/src/main/kotlin/dev/schlaubi/mikmusic/player/queue/FriendlyException.kt
DRSchlaubi
409,332,765
false
null
package dev.schlaubi.mikmusic.player.queue import dev.schlaubi.lavakord.rest.TrackResponse class FriendlyException(severity: TrackResponse.Error.Severity, message: String) : RuntimeException("$severity: $message")
23
Kotlin
11
31
ada5a2d41fa4f9aa4f6b387eaee5ba200d7e6e11
220
mikbot
MIT License
gui/src/main/kotlin/array/gui/arrayedit/KapValueEditor.kt
codereport
710,528,332
false
{"Kotlin": 1966545, "JavaScript": 7748, "HTML": 6917, "CSS": 6534, "Shell": 1164}
package array.gui.arrayedit import array.FormatStyle import javafx.event.EventHandler import javafx.scene.control.TextField import javafx.scene.input.KeyCode import org.controlsfx.control.spreadsheet.SpreadsheetCellEditor import org.controlsfx.control.spreadsheet.SpreadsheetView class KapValueEditor(view: SpreadsheetView?) : SpreadsheetCellEditor(view) { private val textField = TextField() /*************************************************************************** * * Public Methods * * */ override fun startEdit(value: Any?, format: String, vararg options: Any) { if (value is APLValueSpreadsheetCell) { textField.text = value.value.formatted(FormatStyle.READABLE) } attachEnterEscapeEventHandler() textField.requestFocus() textField.selectAll() } override fun getControlValue(): String { return textField.text } override fun end() { textField.onKeyPressed = null } override fun getEditor(): TextField { return textField } private fun attachEnterEscapeEventHandler() { textField.onKeyPressed = EventHandler { event -> if (event.getCode() === KeyCode.ENTER) { endEdit(true) } else if (event.getCode() === KeyCode.ESCAPE) { endEdit(false) } } } }
0
Kotlin
0
1
36cfadd119c5e495acf7eb47281754ab4a226472
1,378
kap
MIT License
core/data/src/main/kotlin/flow/data/impl/repository/RatingRepositoryImpl.kt
andrikeev
503,060,387
false
null
package flow.data.impl.repository import flow.data.api.repository.RatingRepository import flow.securestorage.SecureStorage import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.onStart import javax.inject.Inject internal class RatingRepositoryImpl @Inject constructor( private val secureStorage: SecureStorage, ) : RatingRepository { private val mutableRatingDisabledFlow = MutableSharedFlow<Boolean>() override suspend fun getLaunchCount(): Int { return secureStorage.getRatingLaunchCount() } override suspend fun setLaunchCount(value: Int) { secureStorage.setRatingLaunchCount(value) } override fun observeRatingRequestDisabled(): Flow<Boolean> { return mutableRatingDisabledFlow.onStart { emit(secureStorage.getRatingDisabled()) } } override suspend fun disableRatingRequest() { mutableRatingDisabledFlow.emit(true) secureStorage.setRatingDisabled(true) } override suspend fun isRatingRequestPostponed(): Boolean { return secureStorage.getRatingPostponed() } override suspend fun postponeRatingRequest() { secureStorage.setRatingPostponed(true) } }
1
Kotlin
1
1
1e546ea667f2bef8fbc2d0b2b0bb05023f749b6f
1,254
Flow
MIT License
app/src/main/java/eu/insertcode/traveltipsii/AppData.kt
MrTheGood
124,196,192
false
null
/* * Copyright 2018 Maarten de Goede * * 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 eu.insertcode.traveltipsii import eu.insertcode.traveltipsii.repository.CityRepository /** * Created by maarten on 2018-03-09. * Copyright © 2018 insertCode.eu. All rights reserved. */ object AppData { val cities = arrayListOf<CityRepository>() fun getCity(id: Int) = cities.first { it.id == id } }
0
Kotlin
0
0
08844bfc576dba8080a378ef43265c3bb18d18d4
951
traveltips_ii_android
Apache License 2.0
src/test/kotlin/com/viartemev/requestmapper/model/PopupItemSpek.kt
WouterG
149,575,720
true
{"Kotlin": 109029, "JavaScript": 152}
package com.viartemev.requestmapper.model import org.amshove.kluent.shouldEqual import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on object PopupItemSpek : Spek({ describe("PopupItem") { on("toPath on popup without params") { it("should return path without method") { PopupPath("GET /api/v1").toPath() shouldEqual Path("/api/v1") } } on("toPath on popup with params") { it("should return path without method and params") { PopupPath("GET /api/v1 params=something").toPath() shouldEqual Path("/api/v1") } } } })
0
Kotlin
0
0
9530e0b42d8daab119ab4fe7404301511dda450a
732
requestmapper
MIT License
j2k/testData/fileOrElement/binaryExpression/multiplePlusMinus.kt
JakeWharton
99,388,807
false
null
1 + 2 + 3 - 4 + 5
284
null
5162
83
4383335168338df9bbbe2a63cb213a68d0858104
18
kotlin
Apache License 2.0
app/src/main/java/be/mygod/reactmap/SiteController.kt
Mygod
681,443,066
false
null
package be.mygod.reactmap import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Intent import android.os.Build import androidx.activity.ComponentActivity import androidx.activity.result.contract.ActivityResultContracts import androidx.core.app.NotificationCompat import androidx.core.content.getSystemService import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner class SiteController(private val activity: ComponentActivity) : DefaultLifecycleObserver { companion object { private const val CHANNEL_ID = "control" } private val nm = activity.getSystemService<NotificationManager>()!! init { activity.lifecycle.addObserver(this) if (Build.VERSION.SDK_INT >= 26) nm.createNotificationChannel( NotificationChannel(CHANNEL_ID, "Full screen site controls", NotificationManager.IMPORTANCE_LOW).apply { lockscreenVisibility = NotificationCompat.VISIBILITY_SECRET }) } private val requestPermission = activity.registerForActivityResult(ActivityResultContracts.RequestPermission()) { if (it && started) nm.notify(1, NotificationCompat.Builder(activity, CHANNEL_ID).apply { setWhen(0) color = activity.getColor(R.color.main_blue) setCategory(NotificationCompat.CATEGORY_SERVICE) setContentTitle(title) setContentText("Tap to configure") setSmallIcon(R.drawable.ic_reactmap) setOngoing(true) priority = NotificationCompat.PRIORITY_LOW setVisibility(NotificationCompat.VISIBILITY_SECRET) setContentIntent(PendingIntent.getActivity(activity, 0, Intent(activity, MainActivity::class.java).setAction(MainActivity.ACTION_CONFIGURE), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)) addAction(android.R.drawable.ic_delete, "Restart game", PendingIntent.getActivity(activity, 1, Intent(activity, MainActivity::class.java).setAction(MainActivity.ACTION_RESTART_GAME), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)) }.build()) } private var started = false var title: String? = null set(value) { field = value if (started) requestPermission.launch(android.Manifest.permission.POST_NOTIFICATIONS) } override fun onStart(owner: LifecycleOwner) { started = true if (title != null) requestPermission.launch(android.Manifest.permission.POST_NOTIFICATIONS) } override fun onStop(owner: LifecycleOwner) { started = false nm.cancel(1) } }
0
Kotlin
2
0
dd30ef6e7c635c58b751e2857fa44c02cca1fe2b
2,775
reactmap-android
Apache License 2.0
apps/bolt/src/main/kotlin/io/enkrypt/bolt/processors/ChartsProcessor.kt
nnn-gif
146,397,677
true
{"JavaScript": 2017563, "TypeScript": 208285, "Vue": 183725, "Kotlin": 149231, "CSS": 52410, "HCL": 50576, "Shell": 36220, "Dockerfile": 5195, "Python": 1891, "HTML": 818}
package io.enkrypt.bolt.processors import com.mongodb.client.MongoCollection import com.mongodb.client.MongoDatabase import com.mongodb.client.model.ReplaceOptions import com.mongodb.client.model.UpdateOneModel import com.mongodb.client.model.UpdateOptions import io.enkrypt.bolt.kafka.processors.MongoProcessor import io.enkrypt.bolt.kafka.serdes.BigIntegerSerde import io.enkrypt.bolt.kafka.serdes.DateSerde import io.enkrypt.bolt.kafka.serdes.RLPBlockStatisticsSerde import io.enkrypt.bolt.kafka.serdes.RLPBlockSummarySerde import mu.KotlinLogging import org.apache.kafka.common.serialization.Serdes import org.apache.kafka.streams.KafkaStreams import org.apache.kafka.streams.KeyValue import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.StreamsConfig import org.apache.kafka.streams.kstream.* import org.apache.kafka.streams.processor.Cancellable import org.apache.kafka.streams.processor.ProcessorContext import org.apache.kafka.streams.processor.PunctuationType import org.bson.Document import org.ethereum.util.ByteUtil import org.koin.standalone.get import org.koin.standalone.inject import java.math.BigInteger import java.util.Calendar import java.util.Date import java.util.Properties import java.util.TimeZone /** * This processor processes different statistics. */ class ChartsProcessor : AbstractBaseProcessor() { override val id: String = "charts-processor" private val kafkaProps: Properties = Properties() .apply { putAll(baseKafkaProps.toMap()) put(StreamsConfig.APPLICATION_ID_CONFIG, id) put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 2) } override val logger = KotlinLogging.logger {} override fun onPrepareProcessor() { // Serdes val blockSummarySerde = RLPBlockSummarySerde() val blockStatisticsSerde = RLPBlockStatisticsSerde() val bigIntegerSerde = BigIntegerSerde() val dateSerde = DateSerde() // Create stream builder val builder = StreamsBuilder() val (blocks) = appConfig.kafka.topicsConfig val blocksStream = builder.stream(blocks, Consumed.with(Serdes.ByteArray(), blockSummarySerde)) val statsByDay = blocksStream .map { k, v -> KeyValue(ByteUtil.byteArrayToLong(k), v) } .groupByKey(Serialized.with(Serdes.Long(), blockSummarySerde)) .reduce( { a, b -> if (a.totalDifficulty >= b.totalDifficulty) a else b }, Materialized.with(Serdes.Long(), blockSummarySerde) ).groupBy( { _, v -> KeyValue(timestampToDay(v.block.timestamp), v.statistics.setTotalDifficulty(v.block.cumulativeDifficulty)) }, Serialized.with(dateSerde, blockStatisticsSerde) ) // Blocks count per day // -------------------- val blockCountByDay = statsByDay.count() // Avg Total Difficulty // -------------------- statsByDay .aggregate( { BigInteger.ZERO }, { _, v, total -> total.add(v.totalDifficulty) }, { _, v, total -> total.subtract(v.totalDifficulty) }, Materialized.with(dateSerde, bigIntegerSerde) ).join( blockCountByDay, { total, count -> if (count == 0L) BigInteger.ZERO else total.divide(BigInteger.valueOf(count)) }, Materialized.with(dateSerde, bigIntegerSerde) ) .toStream() .mapValues { v -> Pair("avg_total_difficulty", v.toLong()) } .process({ get<StatisticMongoProcessor>() }, null) // Avg Gas Price // ------------- statsByDay .aggregate( { BigInteger.ZERO }, { _, v, total -> total.add(v.avgGasPrice) }, { _, v, total -> total.subtract(v.avgGasPrice) }, Materialized.with(dateSerde, bigIntegerSerde) ).join( blockCountByDay, { total, count -> if (count == 0L) BigInteger.ZERO else total.divide(BigInteger.valueOf(count)) }, Materialized.with(dateSerde, bigIntegerSerde) ) .toStream() .mapValues { v -> Pair("avg_gas_price", v.toLong()) } .process({ get<StatisticMongoProcessor>() }, null) // Avg Txs Fees // ------------ statsByDay .aggregate( { BigInteger.ZERO }, { _, v, total -> total.add(v.avgTxsFees) }, { _, v, total -> total.subtract(v.avgTxsFees) }, Materialized.with(dateSerde, bigIntegerSerde) ).join( blockCountByDay, { total, count -> if (count == 0L) BigInteger.ZERO else total.divide(BigInteger.valueOf(count)) }, Materialized.with(dateSerde, bigIntegerSerde) ) .toStream() .mapValues { v -> Pair("avg_txs_fees", v.toLong()) } .process({ get<StatisticMongoProcessor>() }, null) // Avg Failed Txs // ------------------ statsByDay .aggregate( { 0 }, { _, v, total -> total + v.numFailedTxs }, { _, v, total -> total - v.numFailedTxs }, Materialized.with(dateSerde, Serdes.Integer()) ).join( blockCountByDay, { total, count -> if (count == 0L) 0 else total / count }, Materialized.with(dateSerde, Serdes.Long()) ) .toStream() .mapValues { v -> Pair("avg_failed_txs", v.toLong()) } .process({ get<StatisticMongoProcessor>() }, null) // Avg Successful Txs // ------------------ statsByDay .aggregate( { 0 }, { _, v, total -> total + v.numSuccessfulTxs }, { _, v, total -> total - v.numSuccessfulTxs }, Materialized.with(dateSerde, Serdes.Integer()) ).join( blockCountByDay, { total, count -> if (count == 0L) 0 else total / count }, Materialized.with(dateSerde, Serdes.Long()) ) .toStream() .mapValues { v -> Pair("avg_successful_txs", v.toLong()) } .process({ get<StatisticMongoProcessor>() }, null) // Generate the topology val topology = builder.build() // Create streams streams = KafkaStreams(topology, kafkaProps) } private fun timestampToDay(timestampSeconds: Long): Date { val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")) with(cal) { timeInMillis = timestampSeconds * 1000 set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) } return cal.time } } class StatisticMongoProcessor : MongoProcessor<Date, Pair<String, Long>>() { private val statsCollection: MongoCollection<Document> by lazy { mongoDB.getCollection(config.mongo.statisticsCollection) } private var batch = mapOf<Pair<Date, String>, Long>() private var scheduledWrite: Cancellable? = null override fun init(context: ProcessorContext) { super.init(context) this.scheduledWrite = context.schedule(timeoutMs, PunctuationType.WALL_CLOCK_TIME) { _ -> tryToWrite() } } override fun process(key: Date, value: Pair<String, Long>) { batch += Pair(key, value.first) to value.second } private fun tryToWrite() { if (!running || batch.isEmpty()) { return } val startMs = System.currentTimeMillis() val updateOptions = UpdateOptions().upsert(true) val ops = batch.toList().map { kv -> val date = kv.first.first val name = kv.first.second val value = kv.second val filter = Document(mapOf("name" to name, "date" to date)) UpdateOneModel<Document>(filter, Document( mapOf("\$set" to Document( mapOf( "name" to name, "date" to date, "value" to value) ))), updateOptions) } try { statsCollection.bulkWrite(ops) context.commit() val elapsedMs = System.currentTimeMillis() - startMs logger.debug { "${batch.size} stats updated in $elapsedMs ms" } batch = emptyMap() } catch (e: Exception) { logger.error { "Failed to update stats. $e" } } } override fun close() { running = false scheduledWrite?.cancel() } }
79
JavaScript
0
0
78d0fb327cbb87c6035a89e3687f9c00aefa65be
7,906
ethvm
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/fsx/FileSystemAttributesDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.fsx import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.fsx.FileSystemAttributes @Generated public fun buildFileSystemAttributes(initializer: @AwsCdkDsl FileSystemAttributes.Builder.() -> Unit): FileSystemAttributes = FileSystemAttributes.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
414
aws-cdk-kt
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/fsx/FileSystemAttributesDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.fsx import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.fsx.FileSystemAttributes @Generated public fun buildFileSystemAttributes(initializer: @AwsCdkDsl FileSystemAttributes.Builder.() -> Unit): FileSystemAttributes = FileSystemAttributes.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
414
aws-cdk-kt
Apache License 2.0
sdk/sdk-metrics/src/commonMain/kotlin/io/opentelemetry/kotlin/sdk/metrics/SdkLongGaugeBuilder.kt
dcxp
450,518,130
false
{"Kotlin": 1483649}
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ package io.opentelemetry.kotlin.sdk.metrics import io.opentelemetry.kotlin.api.metrics.DoubleGaugeBuilder import io.opentelemetry.kotlin.api.metrics.LongGaugeBuilder import io.opentelemetry.kotlin.api.metrics.ObservableLongMeasurement import io.opentelemetry.kotlin.sdk.metrics.common.InstrumentType import io.opentelemetry.kotlin.sdk.metrics.internal.state.MeterProviderSharedState import io.opentelemetry.kotlin.sdk.metrics.internal.state.MeterSharedState internal class SdkLongGaugeBuilder( meterProviderSharedState: MeterProviderSharedState, sharedState: MeterSharedState, name: String, description: String, unit: String ) : AbstractInstrumentBuilder<SdkLongGaugeBuilder>( meterProviderSharedState, sharedState, name, description, unit ), LongGaugeBuilder { override val `this`: SdkLongGaugeBuilder protected get() = this override fun ofDoubles(): DoubleGaugeBuilder { return swapBuilder(::SdkDoubleGaugeBuilder) } override fun buildWithCallback(callback: (ObservableLongMeasurement) -> Unit) { registerLongAsynchronousInstrument(InstrumentType.OBSERVABLE_GAUGE, callback) } }
10
Kotlin
2
29
9c3186e26bd3ac78b650163be2c8f569096aaeec
1,286
opentelemetry-kotlin
Apache License 2.0
src/me/anno/graph/visual/vector/VectorTypes.kt
AntonioNoack
456,513,348
false
{"Kotlin": 10912545, "C": 236426, "Java": 6754, "Lua": 4496, "C++": 3070, "GLSL": 2698}
package me.anno.graph.visual.vector val vectorTypes = "Vector2f,Vector3f,Vector4f,Vector2d,Vector3d,Vector4d,Vector2i,Vector3i,Vector4i".split(',') fun getVectorTypeF(type: String): String { return when { type.endsWith('f') -> "Float" else -> "Double" } } fun getVectorType(type: String): String { return when { type.endsWith('f') -> "Float" type.endsWith('i') -> "Int" else -> "Double" } }
0
Kotlin
3
24
013af4d92e0f89a83958008fbe1d1fdd9a10e992
450
RemsEngine
Apache License 2.0
app/src/main/java/com/example/wanAndroid/widget/web/CoolIndicatorLayout.kt
SaltedFish-Extreme
458,692,555
false
{"Kotlin": 476520, "Java": 9830}
package com.base.wanandroid.widget import android.app.Activity import android.content.Context import android.util.AttributeSet import androidx.core.content.res.ResourcesCompat import com.base.wanandroid.R import com.coolindicator.sdk.CoolIndicator import com.just.agentweb.AgentWebUtils import com.just.agentweb.BaseIndicatorView /** * desc: 自定义彩色加载进度条 */ class CoolIndicatorLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = -1) : BaseIndicatorView(context, attrs, defStyleAttr) { private val mCoolIndicator by lazy { CoolIndicator.create(context as Activity) } init { mCoolIndicator.progressDrawable = ResourcesCompat.getDrawable(resources, R.drawable.default_drawable_indicator, context.theme) this.addView(mCoolIndicator, offerLayoutParams()) } override fun setProgress(newProgress: Int) {} override fun show() { this.visibility = VISIBLE mCoolIndicator.start() } override fun hide() { mCoolIndicator.complete() } override fun offerLayoutParams(): LayoutParams { return LayoutParams(-1, AgentWebUtils.dp2px(context, 3f)) } }
0
Kotlin
6
36
2ce81daeedee3f0df94dfc6b474f65356d6fd64a
1,179
WanAndroid
Apache License 2.0
core/core-ktx/src/androidTest/java/androidx/core/view/ViewGroupTest.kt
FYI-Google
258,765,297
false
null
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.core.view import android.support.test.InstrumentationRegistry import android.support.test.filters.SdkSuppress import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import androidx.testutils.assertThrows import androidx.testutils.fail import com.google.common.truth.Truth.assertThat import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test class ViewGroupTest { private val context = InstrumentationRegistry.getContext() private val viewGroup = LinearLayout(context) @Test fun get() { val view1 = View(context) viewGroup.addView(view1) val view2 = View(context) viewGroup.addView(view2) assertSame(view1, viewGroup[0]) assertSame(view2, viewGroup[1]) assertThrows<IndexOutOfBoundsException> { viewGroup[-1] }.hasMessageThat().isEqualTo("Index: -1, Size: 2") assertThrows<IndexOutOfBoundsException> { viewGroup[2] }.hasMessageThat().isEqualTo("Index: 2, Size: 2") } @Test fun contains() { val view1 = View(context) viewGroup.addView(view1) assertTrue(view1 in viewGroup) assertFalse(view1 !in viewGroup) val view2 = View(context) assertFalse(view2 in viewGroup) assertTrue(view2 !in viewGroup) } @Test fun plusAssign() { assertEquals(0, viewGroup.childCount) val view1 = View(context) viewGroup += view1 assertEquals(1, viewGroup.childCount) assertSame(view1, viewGroup.getChildAt(0)) val view2 = View(context) viewGroup += view2 assertEquals(2, viewGroup.childCount) assertSame(view2, viewGroup.getChildAt(1)) } @Test fun minusAssign() { val view1 = View(context) viewGroup.addView(view1) val view2 = View(context) viewGroup.addView(view2) assertEquals(2, viewGroup.childCount) viewGroup -= view2 assertEquals(1, viewGroup.childCount) assertSame(view1, viewGroup.getChildAt(0)) viewGroup -= view1 assertEquals(0, viewGroup.childCount) } @Test fun size() { assertEquals(0, viewGroup.size) viewGroup.addView(View(context)) assertEquals(1, viewGroup.size) viewGroup.addView(View(context)) assertEquals(2, viewGroup.size) viewGroup.removeViewAt(0) assertEquals(1, viewGroup.size) } @Test fun isEmpty() { assertTrue(viewGroup.isEmpty()) viewGroup.addView(View(context)) assertFalse(viewGroup.isEmpty()) } @Test fun isNotEmpty() { assertFalse(viewGroup.isNotEmpty()) viewGroup.addView(View(context)) assertTrue(viewGroup.isNotEmpty()) } @Test fun forEach() { viewGroup.forEach { fail("Empty view group should not invoke lambda") } val view1 = View(context) viewGroup.addView(view1) val view2 = View(context) viewGroup.addView(view2) val views = mutableListOf<View>() viewGroup.forEach { views += it } assertThat(views).containsExactly(view1, view2) } @Test fun forEachIndexed() { viewGroup.forEachIndexed { _, _ -> fail("Empty view group should not invoke lambda") } val view1 = View(context) viewGroup.addView(view1) val view2 = View(context) viewGroup.addView(view2) val views = mutableListOf<View>() viewGroup.forEachIndexed { index, view -> assertEquals(index, views.size) views += view } assertThat(views).containsExactly(view1, view2) } @Test fun iterator() { val view1 = View(context) viewGroup.addView(view1) val view2 = View(context) viewGroup.addView(view2) val iterator = viewGroup.iterator() assertTrue(iterator.hasNext()) assertSame(view1, iterator.next()) assertTrue(iterator.hasNext()) assertSame(view2, iterator.next()) assertFalse(iterator.hasNext()) assertThrows<IndexOutOfBoundsException> { iterator.next() } } @Test fun iteratorRemoving() { val view1 = View(context) viewGroup.addView(view1) val view2 = View(context) viewGroup.addView(view2) val iterator = viewGroup.iterator() assertSame(view1, iterator.next()) iterator.remove() assertFalse(view1 in viewGroup) assertEquals(1, viewGroup.childCount) assertSame(view2, iterator.next()) iterator.remove() assertFalse(view2 in viewGroup) assertEquals(0, viewGroup.childCount) } @Test fun iteratorForEach() { val views = listOf(View(context), View(context)) views.forEach(viewGroup::addView) var index = 0 for (view in viewGroup) { assertSame(views[index++], view) } } @Test fun children() { val views = listOf(View(context), View(context), View(context)) views.forEach { viewGroup.addView(it) } viewGroup.children.forEachIndexed { index, child -> assertSame(views[index], child) } } @Test fun setMargins() { val layoutParams = ViewGroup.MarginLayoutParams(100, 200) layoutParams.setMargins(42) assertEquals(42, layoutParams.leftMargin) assertEquals(42, layoutParams.topMargin) assertEquals(42, layoutParams.rightMargin) assertEquals(42, layoutParams.bottomMargin) } @Test fun updateMargins() { val layoutParams = ViewGroup.MarginLayoutParams(100, 200) layoutParams.updateMargins(top = 10, right = 20) assertEquals(0, layoutParams.leftMargin) assertEquals(10, layoutParams.topMargin) assertEquals(20, layoutParams.rightMargin) assertEquals(0, layoutParams.bottomMargin) } @Test fun updateMarginsNoOp() { val layoutParams = ViewGroup.MarginLayoutParams(100, 200) layoutParams.setMargins(10, 20, 30, 40) layoutParams.updateMargins() assertEquals(10, layoutParams.leftMargin) assertEquals(20, layoutParams.topMargin) assertEquals(30, layoutParams.rightMargin) assertEquals(40, layoutParams.bottomMargin) } @SdkSuppress(minSdkVersion = 17) @Test fun updateMarginsRelative() { val layoutParams = ViewGroup.MarginLayoutParams(100, 200) layoutParams.updateMarginsRelative(start = 10, end = 20) assertEquals(0, layoutParams.leftMargin) assertEquals(0, layoutParams.topMargin) assertEquals(0, layoutParams.rightMargin) assertEquals(0, layoutParams.bottomMargin) assertEquals(10, layoutParams.marginStart) assertEquals(20, layoutParams.marginEnd) assertTrue(layoutParams.isMarginRelative) } @SdkSuppress(minSdkVersion = 17) @Test fun updateMarginsRelativeNoOp() { val layoutParams = ViewGroup.MarginLayoutParams(100, 200) layoutParams.setMargins(10, 20, 30, 40) layoutParams.updateMarginsRelative() assertEquals(10, layoutParams.leftMargin) assertEquals(20, layoutParams.topMargin) assertEquals(30, layoutParams.rightMargin) assertEquals(40, layoutParams.bottomMargin) assertEquals(10, layoutParams.marginStart) assertEquals(30, layoutParams.marginEnd) } }
8
null
657
6
b9cd83371e928380610719dfbf97c87c58e80916
8,232
platform_frameworks_support
Apache License 2.0
kotlin-mui/src/main/generated/mui/material/Collapse.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/material/Collapse") @file:JsNonModule @file:Suppress( "VIRTUAL_MEMBER_HIDDEN", ) package mui.material import kotlinext.js.ReadonlyArray external interface CollapseProps : mui.system.StandardProps, mui.material.transitions.TransitionProps, react.PropsWithChildren { /** * The content node to be collapsed. */ override var children: ReadonlyArray<react.ReactNode>? var className: String? /** * Override or extend the styles applied to the component. */ var classes: CollapseClasses? /** * The width (horizontal) or height (vertical) of the container when collapsed. * @default '0px' */ var collapsedSize: dynamic /** * The component used for the root node. * Either a string to use a HTML element or a component. */ var component: react.ElementType<mui.material.transitions.TransitionProps>? /** * The transition timing function. * You may specify a single easing or a object containing enter and exit values. */ var easing: dynamic /* TransitionProps['easing'] */ /** * If `true`, the component will transition in. */ var `in`: Boolean? /** * The transition orientation. * @default 'vertical' */ var orientation: mui.system.Union? /* 'horizontal' | 'vertical' */ /** * The duration for the transition, in milliseconds. * You may specify a single timeout for all transitions, or individually with an object. * * Set to 'auto' to automatically calculate transition time based on height. * @default duration.standard */ var timeout: dynamic /* TransitionProps['timeout'] | 'auto' */ /** * The system prop that allows defining system overrides as well as additional CSS styles. */ var sx: mui.system.SxProps<mui.system.Theme>? } /** * The Collapse transition is used by the * [Vertical Stepper](https://mui.com/components/steppers/#vertical-stepper) StepContent component. * It uses [react-transition-group](https://github.com/reactjs/react-transition-group) internally. * * Demos: * * - [Cards](https://mui.com/components/cards/) * - [Lists](https://mui.com/components/lists/) * - [Transitions](https://mui.com/components/transitions/) * * API: * * - [Collapse API](https://mui.com/api/collapse/) * - inherits [Transition API](https://reactcommunity.org/react-transition-group/transition#Transition-props) */ @JsName("default") external val Collapse: react.FC<CollapseProps>
9
null
145
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
2,589
kotlin-wrappers
Apache License 2.0
src/controller/java/src/matter/controller/WriteAttributesCallback.kt
nrfconnect
319,609,059
false
null
/* * Copyright (c) 2024 Project CHIP Authors * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package matter.controller import matter.controller.model.AttributePath import matter.controller.model.Status /** An interface for receiving write response. */ interface WriteAttributesCallback { /** * OnError will be called when an error occurs after failing to write * * @param attributePath The attribute path field * @param Exception The IllegalStateException which encapsulated the error message, the possible * chip error could be CHIP_ERROR_TIMEOUT: A response was not received within the expected * response timeout. - CHIP_ERROR_*TLV*: A malformed, non-compliant response was received from * the server. - CHIP_ERROR encapsulating the converted error from the StatusIB: If we got a * non-path-specific status response from the server. CHIP_ERROR*: All other cases. */ fun onError(attributePath: AttributePath?, ex: Exception) /** * OnResponse will be called when a write response has been received and processed for the given * path. * * @param attributePath The attribute path field in write response. * @param status The attribute status field in write response. */ fun onResponse(attributePath: AttributePath, status: Status) fun onDone() {} }
5
null
57
47
700233bea1168d8822c4c7d1553e09592f9c6c48
1,879
sdk-connectedhomeip
Apache License 2.0
finnhub-api/src/commonMain/kotlin/com/hibernix/finnhub/model/MutualFundSectorExposure.kt
hibernix
591,662,668
false
null
package com.hibernix.finnhub.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * @property symbol Mutual symbol. * @property sectorExposure Array of sector and exposure levels. */ @Serializable data class MutualFundSectorExposure( @SerialName("symbol") var symbol: String? = null, @SerialName("sectorExposure") var sectorExposure: List<MutualFundSectorExposureData>? = null, )
0
Kotlin
0
1
cb570830c8af1ee5fd80bd9604649606c692fe09
432
finnhub-api
Apache License 2.0
core/builtins/native/kotlin/CharSequence.kt
JakeWharton
99,388,807
false
null
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kotlin /** * Represents a readable sequence of [Char] values. */ public interface CharSequence { /** * Returns the length of this character sequence. */ public val length: Int /** * Returns the character at the specified [index] in this character sequence. */ public operator fun get(index: Int): Char /** * Returns a new character sequence that is a subsequence of this character sequence, * starting at the specified [startIndex] and ending right before the specified [endIndex]. * * @param startIndex the start index (inclusive). * @param endIndex the end index (exclusive). */ public fun subSequence(startIndex: Int, endIndex: Int): CharSequence }
184
null
5691
83
4383335168338df9bbbe2a63cb213a68d0858104
1,340
kotlin
Apache License 2.0
testing/architecture-testing/src/test/java/com/mctech/architecture_testing/ComponentStateFlowValidationKtTest.kt
MayconCardoso
539,349,342
false
null
package com.mctech.architecture_testing import com.mctech.architecture_testing.extensions.assertFlow import com.mctech.common_test.TestScenario.Companion.responseScenario import com.mctech.pokergrinder.architecture.ComponentState import kotlinx.coroutines.ExperimentalCoroutinesApi import org.junit.Test @ExperimentalCoroutinesApi class ComponentStateFlowValidationKtTest { private val expectedValue = "Hello world" private val expectedError = RuntimeException() @Test fun `should assert success flow`() = responseScenario<List<ComponentState<String>>> { val expectedSuccessFLow = listOf( ComponentState.Loading.FromEmpty, ComponentState.Success(expectedValue) ) whenAction { expectedSuccessFLow } thenAssert { stateFlow -> stateFlow.assertFlow( ComponentState.Loading.FromEmpty, ComponentState.Success(expectedValue) ) } } @Test fun `should assert error flow`() = responseScenario<List<ComponentState<String>>> { val expectedErrorFLow = listOf<ComponentState<String>>( ComponentState.Loading.FromEmpty, ComponentState.Error(expectedError) ) whenAction { expectedErrorFLow } thenAssert { stateFlow -> stateFlow.assertFlow( ComponentState.Loading.FromEmpty, ComponentState.Error<String>(expectedError) ) } } }
7
Kotlin
0
7
d4a6f48fa73c0259d87934873a8ccb63b53694f3
1,373
poker-grinder
Apache License 2.0
lib/src/main/kotlin/org/walletconnect/types/TypeMapConversion.kt
yaoyuhang
189,737,113
true
{"Kotlin": 32345}
package org.walletconnect.types import org.walletconnect.Session fun Session.PeerMeta.intoMap(params: MutableMap<String, Any?> = mutableMapOf()) = params.also { params["peerMeta"] = mutableMapOf<String, Any>( "description" to (description ?: ""), "url" to (url ?: ""), "name" to (name ?: "") ).apply { icons?.let { put("icons", it) } } } fun Session.PeerData.intoMap(params: MutableMap<String, Any?> = mutableMapOf()) = params.also { params["peerId"] = this.id this.meta?.intoMap(params) } fun Session.SessionParams.intoMap(params: MutableMap<String, Any?> = mutableMapOf()) = params.also { it["approved"] = approved it["chainId"] = chainId it["accounts"] = accounts this.peerData?.intoMap(params) } fun Session.Error.intoMap(params: MutableMap<String, Any?> = mutableMapOf()) = params.also { it["code"] = code it["message"] = message }
0
Kotlin
0
0
8c598cc76d6a3aae8ff6f3a030b8ec6410d5c489
1,046
kotlin-walletconnect-lib
MIT License
app/src/main/java/com/example/themeswitcher/viewmodel/ToolbarViewModel.kt
tcqq
159,900,332
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 20, "XML": 41, "Java": 3}
package com.example.themeswitcher.viewmodel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel /** * @author Perry Lance * @since 2018/08/19 Created */ class ToolbarViewModel : ViewModel() { val title: MutableLiveData<String> = MutableLiveData() val menuResId: MutableLiveData<Int> = MutableLiveData() }
0
Kotlin
1
2
6a8d8c59c0d8b7b027cdd5b14dd29c943ad5a500
343
ThemeSwitcher
Apache License 2.0
Core/src/com/rimmer/yttrium/Task.kt
johguse
72,538,063
true
{"Kotlin": 305120, "Haskell": 2670}
package com.rimmer.yttrium enum class TaskState {waiting, finished, error} inline fun <T> task(f: Task<T>.() -> Unit): Task<T> { val t = Task<T>() t.f() return t } fun <T> finished(v: T): Task<T> { val task = Task<T>() task.finish(v) return task } fun <T> failed(reason: Throwable): Task<T> { val task = Task<T>() task.fail(reason) return task } /** Represents a task that will be performed asynchronously and will either provide a result or fail. */ class Task<T> { /** * Indicates that the task should finish with the provided value. * @return This task. */ fun finish(v: T): Task<T> { if(state == TaskState.waiting) { state = TaskState.finished cachedResult = v handler?.invoke(v, null) } else { throw IllegalStateException("This task already has a result") } return this } /** * Indicates that the task should fail with the provided reason. * @return This task. */ fun fail(reason: Throwable): Task<T> { if(state == TaskState.waiting) { state = TaskState.error cachedError = reason handler?.invoke(null, reason) } else { throw IllegalStateException("This task already has a result") } return this } /** Call the provided handler when finished. */ inline fun onFinish(crossinline f: (T) -> Unit) { handler = {r, e -> try { r?.let(f) } catch(e: Throwable) { println("Error in task onFinish handler: $e") } } } /** Call the provided handler when failed. */ inline fun onFail(crossinline f: (Throwable) -> Unit) { handler = {r, e -> try { e?.let(f) } catch(e: Throwable) { println("Error in task onFail handler: $e") } } } /** Maps the task through the provided function, returning a new task. */ inline fun <U> map(crossinline f: (T) -> U) = mapMaybe {f(it!!)} /** Maps the task through the provided function, returning a new task. */ inline fun <U> mapMaybe(crossinline f: (T?) -> U): Task<U> { val task = Task<U>() handler = {r, e -> if(e == null) { try { task.finish(f(r)) } catch(e: Throwable) { task.fail(e) } } else { task.fail(e) } } return task } /** Maps the task through the provided functions, returning a new task. */ inline fun <U> map(crossinline succeed: (T) -> U, crossinline fail: (Throwable) -> U) = mapMaybe({succeed(it!!)}, fail) /** Maps the task through the provided functions, returning a new task. */ inline fun <U> mapMaybe(crossinline succeed: (T?) -> U, crossinline fail: (Throwable) -> U): Task<U> { val task = Task<U>() handler = {r, e -> if(e == null) { try { task.finish(succeed(r)) } catch(e: Throwable) { task.fail(e) } } else { try { task.finish(fail(e)) } catch(e: Throwable) { task.fail(e) } } } return task } /** Maps the task failure through the provided function, returning a new task. */ inline fun catch(crossinline f: (Throwable) -> T) = map({it}, {f(it)}) /** Runs the provided task generator on finish, returning the new task. */ inline fun <U> then(crossinline f: (T) -> Task<U>) = thenMaybe {f(it!!)} /** Runs the provided task generator on finish, returning the new task. */ inline fun <U> thenMaybe(crossinline f: (T?) -> Task<U>): Task<U> { val task = Task<U>() handler = {r, e -> if(e == null) { try { val next = f(r) next.handler = {r, e -> if(e == null) { task.finish(r!!) } else { task.fail(e) } } } catch(e: Throwable) { task.fail(e) } } else { task.fail(e) } } return task } /** Runs the provided task generator on finish or failure, returning the new task. */ inline fun <U> then(crossinline succeed: (T) -> Task<U>, crossinline fail: (Throwable) -> Task<U>) = thenMaybe({succeed(it!!)}, fail) /** Runs the provided task generator on finish or failure, returning the new task. */ inline fun <U> thenMaybe(crossinline succeed: (T?) -> Task<U>, crossinline fail: (Throwable) -> Task<U>): Task<U> { val task = Task<U>() handler = {r, e -> if(e == null) { try { val next = succeed(r) next.handler = {r, e -> if(e == null) { task.finish(r!!) } else { task.fail(e) } } } catch(e: Throwable) { task.fail(e) } } else { try { val next = fail(e) next.handler = { r, e -> if(e == null) { task.finish(r!!) } else { task.fail(e) } } } catch(e: Throwable) { task.fail(e) } } } return task } /** Runs the provided function whether the task succeeds or not. */ inline fun always(crossinline f: (T?, Throwable?) -> Unit): Task<T> { val task = Task<T>() handler = {r, e -> try { f(r, e) if(e === null) (task as Task<T?>).finish(r) else task.fail(e) } catch(e: Throwable) { task.fail(e) } } return task } /** The last result passed through the task, if any. */ val result: T? get() = cachedResult /** The last error passed through the task, if any. */ val error: Throwable? get() = cachedError /** The current task result handler. */ var handler: ((T?, Throwable?) -> Unit)? = null set(v) { field = v if(state != TaskState.waiting) { v?.invoke(result, error) } } private var cachedResult: T? = null private var cachedError: Throwable? = null private var state = TaskState.waiting }
0
Kotlin
1
2
30a2801540df7ceb11003251b4e936a60e0cfc20
6,956
Yttrium
MIT License
forge/src/main/kotlin/toshio/forge/RegisterImpl.kt
gtosh4
435,545,152
false
null
package toshio.forge import net.minecraft.resources.ResourceLocation import net.minecraft.tags.ItemTags import net.minecraft.tags.Tag import net.minecraft.world.item.Item class RegisterImpl { companion object { @JvmStatic fun itemTag(id: ResourceLocation): Tag.Named<Item> { return ItemTags.createOptional(id) } } }
0
Kotlin
0
0
92c052ac9b8a2f66c5312d2b649f1562785f31d3
361
Tosh-IO
MIT License
src/jvmMain/java/support/net/NetIOException.kt
TarCV
358,762,107
true
{"Kotlin": 998044, "Java": 322706, "HTML": 46587, "XSLT": 7418}
package support.net actual typealias NetIOException = java.io.IOException
0
Kotlin
0
0
c86103748bdf214adb8a027492d21765059d3629
75
selenide.kt-js
MIT License
sdui/src/commonMain/kotlin/dev/helw/playground/sdui/serializer/model/TextColorToken.kt
ahmedre
680,260,539
false
{"Kotlin": 114371, "Swift": 29613, "HTML": 237}
/** * Copyright (c) 2023 <NAME> and <NAME> * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package dev.helw.playground.sdui.serializer.model import androidx.compose.runtime.Composable import androidx.compose.runtime.ReadOnlyComposable import dev.helw.playground.sdui.design.core.TextColor import dev.helw.playground.sdui.design.core.color.LocalTextColors import dev.helw.playground.sdui.design.core.color.TextColors import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable enum class TextColorToken(private val textColor: TextColors.() -> TextColor) { @SerialName("primary") PRIMARY(TextColors::primary), @SerialName("secondary") SECONDARY(TextColors::secondary), @SerialName("tertiary") TERTIARY(TextColors::tertiary), @SerialName("primary_inverse") PRIMARY_INVERSE(TextColors::primaryInverse); @Composable @ReadOnlyComposable fun colorValue(): TextColor = LocalTextColors.current.textColor() }
0
Kotlin
0
3
d9e02bcf1251834fe34518f7109b21a5ae7960f5
1,052
sdui
MIT License
shared/src/commonMain/kotlin/presentation/screen/components/ErrorPage.kt
adelsaramii
727,620,001
false
{"Kotlin": 1014333, "Swift": 2299, "Shell": 228}
package com.attendace.leopard.presentation.screen.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import com.attendace.leopard.util.theme.* import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource @OptIn(ExperimentalResourceApi::class) @Composable fun ErrorPage(modifier: Modifier = Modifier, description: String, onRetryClick: () -> Unit) { Column( modifier = modifier.padding(horizontal = 16.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, ) { Image( painter = painterResource("ic_error_page.xml"), contentDescription = "opened box", ) Spacer(modifier = Modifier.height(4.dp)) Text( text = localization(error_message).value, color = gray, style = MaterialTheme.typography.subtitle2, textAlign = TextAlign.Center, maxLines = 2, overflow = TextOverflow.Ellipsis, ) Spacer(modifier = Modifier.height(8.dp)) Text( text = localization(pleaseTryAgainLater).value, color = gray, style = MaterialTheme.typography.caption, fontWeight = FontWeight.W400, textAlign = TextAlign.Center, ) Spacer(modifier = Modifier.height(16.dp)) TextButton(onClick = onRetryClick) { Text( text = localization(refresh).value, color = primary, style = MaterialTheme.typography.subtitle1, textAlign = TextAlign.Center, ) } } }
0
Kotlin
0
0
ed51d4c99caafefc5fc70cedbe0dd0fa62cce271
2,361
Leopard-Multiplatform
Apache License 2.0
app/src/main/java/com/projectdelta/zoro/di/RepositoryModule.kt
sarafanshul
437,651,086
false
{"Kotlin": 151913}
/* * Copyright (c) 2022. <NAME> */ package com.projectdelta.zoro.di import com.projectdelta.zoro.data.local.MessageDao import com.projectdelta.zoro.data.remote.MessageApi import com.projectdelta.zoro.data.remote.UserApi import com.projectdelta.zoro.data.repository.MessageRepository import com.projectdelta.zoro.data.repository.MessageRepositoryImpl import com.projectdelta.zoro.data.repository.UserRepository import com.projectdelta.zoro.data.repository.UserRepositoryImpl import com.projectdelta.zoro.di.qualifiers.IODispatcher import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import kotlinx.coroutines.CoroutineDispatcher import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object RepositoryModule { @Singleton @Provides fun provideMessageRepository( api: MessageApi, messageDao: MessageDao, @IODispatcher dispatcher : CoroutineDispatcher ): MessageRepository { return MessageRepositoryImpl(api, messageDao, dispatcher) } @Singleton @Provides fun provideUserRepository(api: UserApi): UserRepository { return UserRepositoryImpl(api) } }
0
Kotlin
0
4
e24e20997f4f550adb6d24e1f093631b35464c82
1,220
Zoro
MIT License
core/ui/src/market/java/ru/tech/imageresizershrinker/core/ui/utils/helper/DocumentScanner.kt
T8RIN
478,710,402
false
{"Kotlin": 6498864}
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (Malik Mukhametzyanov) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.core.ui.utils.helper import android.app.Activity import androidx.activity.ComponentActivity import androidx.activity.compose.ManagedActivityResultLauncher import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.ActivityResult import androidx.activity.result.IntentSenderRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.platform.LocalContext import com.google.mlkit.vision.documentscanner.GmsDocumentScannerOptions import com.google.mlkit.vision.documentscanner.GmsDocumentScanning import com.google.mlkit.vision.documentscanner.GmsDocumentScanningResult import kotlinx.coroutines.launch import ru.tech.imageresizershrinker.core.ui.widget.other.LocalToastHostState import ru.tech.imageresizershrinker.core.ui.widget.other.showError class DocumentScanner internal constructor( private val context: ComponentActivity, private val scannerLauncher: ManagedActivityResultLauncher<IntentSenderRequest, ActivityResult>, private val onFailure: (Throwable) -> Unit ) { fun scan() { val options = GmsDocumentScannerOptions.Builder() .setGalleryImportAllowed(true) .setResultFormats( GmsDocumentScannerOptions.RESULT_FORMAT_JPEG, GmsDocumentScannerOptions.RESULT_FORMAT_PDF ) .setScannerMode(GmsDocumentScannerOptions.SCANNER_MODE_FULL) .build() val scanner = GmsDocumentScanning.getClient(options) scanner.getStartScanIntent(context) .addOnSuccessListener { intentSender -> scannerLauncher.launch(IntentSenderRequest.Builder(intentSender).build()) } .addOnFailureListener(onFailure) } } @Composable fun rememberDocumentScanner( onSuccess: (ScanResult) -> Unit ): DocumentScanner { val scope = rememberCoroutineScope() val toastHostState = LocalToastHostState.current val context = LocalContext.current as ComponentActivity val scannerLauncher = rememberLauncherForActivityResult( ActivityResultContracts.StartIntentSenderForResult() ) { result -> if (result.resultCode == Activity.RESULT_OK) { GmsDocumentScanningResult.fromActivityResultIntent(result.data)?.apply { onSuccess( ScanResult( imageUris = pages?.let { pages -> pages.map { it.imageUri } } ?: emptyList(), pdfUri = pdf?.uri ) ) } } } return remember(context, scannerLauncher) { DocumentScanner( context = context, scannerLauncher = scannerLauncher, onFailure = { scope.launch { toastHostState.showError( context = context, error = it ) } } ) } }
10
Kotlin
176
3,817
486410d4a9ea3c832fc5aa63eb5bdc7b1fab871d
3,919
ImageToolbox
Apache License 2.0
wechat/src/main/java/app/allever/android/learning/project/compose/module/tianliao/module/voiceroom/VoiceRoom.kt
devallever
738,467,560
false
{"Kotlin": 148004}
package app.allever.android.learning.project.compose.module.tianliao.module.voiceroom class VoiceRoom { }
0
Kotlin
0
0
5b6e53df3e067a609458aa9aa441f201392ace49
106
ComposeProjects
Apache License 2.0
mui-kotlin/src/jsMain/kotlin/mui/material/Tabs.ext.kt
karakum-team
387,062,541
false
{"Kotlin": 3038356, "TypeScript": 2249, "HTML": 724, "CSS": 86}
// Automatically generated - do not modify! package mui.material @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) // language=JavaScript @JsName("""(/*union*/{standard: 'standard', scrollable: 'scrollable', fullWidth: 'fullWidth'}/*union*/)""") sealed external interface TabsVariant { companion object { val standard: TabsVariant val scrollable: TabsVariant val fullWidth: TabsVariant } } @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) // language=JavaScript @JsName("""(/*union*/{secondary: 'secondary', primary: 'primary'}/*union*/)""") sealed external interface TabsIndicatorColor { companion object { val secondary: TabsIndicatorColor val primary: TabsIndicatorColor } } @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) // language=JavaScript @JsName("""(/*union*/{secondary: 'secondary', primary: 'primary', inherit: 'inherit'}/*union*/)""") sealed external interface TabsTextColor { companion object { val secondary: TabsTextColor val primary: TabsTextColor val inherit: TabsTextColor } } @Suppress( "NAME_CONTAINS_ILLEGAL_CHARS", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", ) // language=JavaScript @JsName("""(/*union*/{auto: 'auto', true: true, false: false}/*union*/)""") sealed external interface TabsScrollButtons { companion object { val auto: TabsScrollButtons val `true`: TabsScrollButtons val `false`: TabsScrollButtons } }
0
Kotlin
5
34
a5270a395943b069d41891c29e904d4d2f776789
1,592
mui-kotlin
Apache License 2.0
app/src/main/java/com/turastory/falcon/util/Worker.kt
turastory
154,104,058
false
null
package com.turastory.falcon.util import java.util.concurrent.Executors /** * Created by tura on 2018-10-22. */ private val executor = Executors.newFixedThreadPool(3) fun runOnBackground(job: Runnable) { executor.execute(job) } fun stopAll() { executor.shutdownNow() }
0
Kotlin
0
0
ec2d5472d7d7a4172b056e938bc4a0e1a8e41471
283
falcon-android
Apache License 2.0
features/dd-sdk-android-trace/src/test/kotlin/com/datadog/android/utils/forge/Configurator.kt
DataDog
219,536,756
false
null
/* * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. * This product includes software developed at Datadog (https://www.datadoghq.com/). * Copyright 2016-Present Datadog, Inc. */ package com.datadog.android.utils.forge import com.datadog.android.tests.elmyr.useCoreFactories import com.datadog.tools.unit.forge.BaseConfigurator import fr.xgouchet.elmyr.Forge internal class Configurator : BaseConfigurator() { override fun configure(forge: Forge) { super.configure(forge) // Core forge.useCoreFactories() // APM forge.addFactory(SpanForgeryFactory()) forge.addFactory(SpanEventForgeryFactory()) forge.addFactory(TraceConfigurationForgeryFactory()) forge.addFactory(CoreDDSpanForgeryFactory()) forge.addFactory(AgentSpanLinkForgeryFactory()) // MISC forge.addFactory(BigIntegerFactory()) } }
54
null
60
151
d7e640cf6440ab150c2bbfbac261e09b27e258f4
965
dd-sdk-android
Apache License 2.0
src/main/java/frc/robot/subsystems/TanqDrive.kt
blair-robot-project
713,041,967
false
{"Kotlin": 19485}
package frc.robot.subsystems import com.revrobotics.CANSparkMax import com.revrobotics.CANSparkMaxLowLevel import com.revrobotics.SparkMaxPIDController import edu.wpi.first.math.controller.DifferentialDriveFeedforward import edu.wpi.first.math.controller.SimpleMotorFeedforward import edu.wpi.first.math.kinematics.ChassisSpeeds import edu.wpi.first.math.kinematics.DifferentialDriveKinematics import edu.wpi.first.wpilibj.AnalogGyro import edu.wpi.first.wpilibj2.command.SubsystemBase class TanqDrive( private val rightLeader: CANSparkMax, private val rightFollower: CANSparkMax, private val leftLeader: CANSparkMax, private val leftFollower: CANSparkMax ) : SubsystemBase() { //below should be the width of the robot's track width in inches //this is creating a differential drive kinematics object var kinematics = DifferentialDriveKinematics(1.0) val feedForward = DifferentialDriveFeedforward(1.0, 3.0, 4.0, 6.0) fun setSpeed(desiredSpeed : ChassisSpeeds, feedForward : DifferentialDriveFeedforward){ //Here we use the ChassisSpeeds object to val wheelSpeeds = kinematics.toWheelSpeeds(desiredSpeed) // Left velocity val leftVelocity = wheelSpeeds.leftMetersPerSecond // Right velocity val rightVelocity = wheelSpeeds.rightMetersPerSecond val ffVolts = feedForward.calculate(leftLeader.encoder.velocity, leftVelocity, rightLeader.encoder.velocity, rightVelocity, 0.02) leftLeader.pidController.setReference(leftVelocity, CANSparkMax.ControlType.kVelocity, 0, ffVolts.left, SparkMaxPIDController.ArbFFUnits.kVoltage) rightLeader.pidController.setReference(rightVelocity, CANSparkMax.ControlType.kVelocity, 0, ffVolts.right, SparkMaxPIDController.ArbFFUnits.kVoltage) } fun getPose(){ } fun resetPose(){ } fun getCurrentSpeeds(){ } companion object { fun createTanqDrive(arrId: IntArray): TanqDrive { val kTrackWidth = 0.381 * 2 // meters val kWheelRadius = 0.0508 // meters val kEncoderResolution = 4096 val leftLeader = CANSparkMax(arrId[0], CANSparkMaxLowLevel.MotorType.kBrushless) val rightLeader = CANSparkMax(arrId[1], CANSparkMaxLowLevel.MotorType.kBrushless) val leftFollower = CANSparkMax(arrId[2], CANSparkMaxLowLevel.MotorType.kBrushless) val rightFollower = CANSparkMax(arrId[3], CANSparkMaxLowLevel.MotorType.kBrushless) rightLeader.inverted = true leftFollower.follow(leftLeader) rightFollower.follow(rightFollower) val m_gyro = AnalogGyro(0) /* Bellow we are converting from motor rotations to meters per second so that we can feed these values into the PID. The gearing is a placeholder for the ratio between 1 full motor spin to 1 wheel spin. */ val gearing = 0.25 leftLeader.encoder.positionConversionFactor = 2 * Math.PI * kWheelRadius * gearing / 60 rightLeader.encoder.positionConversionFactor = 2 * Math.PI * kWheelRadius * gearing / 60 //create 2 PID controllers for left and right leader motors val leftPidController = leftLeader.pidController val rightPidController = rightLeader.pidController //these values are not set and need to be changed ******** val kP = 6e-5 val kI = 0.0 val kD = 0.0 val kIz = 0.0 val kFF = 0.0 val kMaxOutput = 1.0 val kMinOutput = -1.0 val maxRPM = 5700 //setting pid values for left and right PID Controllers leftPidController.setP(kP) leftPidController.setI(kI) leftPidController.setD(kD) leftPidController.setIZone(kIz) leftPidController.setFF(kFF) leftPidController.setOutputRange(kMinOutput, kMaxOutput) rightPidController.setP(kP) rightPidController.setI(kI) rightPidController.setD(kD) rightPidController.setIZone(kIz) rightPidController.setFF(kFF) rightPidController.setOutputRange(kMinOutput, kMaxOutput) return TanqDrive(rightLeader, rightFollower, leftLeader, leftFollower) } } }
0
Kotlin
0
2
e7564383a522efd835e4fc256bfcafdb1bd480fe
4,389
rookiebunnybot2023
MIT License
SeekArc_sample/src/com/triggertrap/sample/CustomActivity.kt
IgorGanapolsky
201,293,378
true
{"Kotlin": 31573}
/* * The MIT License (MIT) * * Copyright (c) 2013 Triggertrap Ltd * Author <NAME> * * 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.triggertrap.sample /** * CustomActivity.java * * @author <NAME> */ class CustomActivity : SimpleActivity() { override fun getLayoutFile(): Int { return R.layout.custom_sample } }
0
Kotlin
2
2
45eb3b9a8de59c8db6e235a52d5f85f5af2e8949
1,453
SeekArc
MIT License
src/main/kotlin/ru/azhd/petro/elastictest/service/IIndexService.kt
a-zhd
222,006,130
false
null
package ru.azhd.petro.elastictest.service import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service import ru.azhd.petro.elastictest.model.NewsItem import ru.azhd.petro.elastictest.repository.NewsIndexRepository interface IIndexService { fun createIndex(newsItem: NewsItem) } @Service class IndexService(@Autowired private val newsIndexRepository: NewsIndexRepository) : IIndexService { override fun createIndex(newsItem: NewsItem) { newsIndexRepository.save(newsItem) } }
0
Kotlin
0
0
ad170a0d8e8f44b333d19d52df65c01bd0ac8bf4
545
elastic-test
MIT License
app/src/main/java/com/example/app_calculo_gasto_combustvel/e_result.kt
pedrosalmeron
785,010,532
false
{"Kotlin": 8872}
package com.example.app_calculo_gasto_combustvel import android.annotation.SuppressLint import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class e_result : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_result) val resultado = intent.getFloatExtra("KR_Resultado",0f) val preço = intent.getFloatExtra("KR_Preço",0f) val consumo = intent.getFloatExtra("KR_Consumo",0f) val distância = intent.getFloatExtra("KR_Distância",0f) val resultadoFormatado = String.format("%.2f", resultado) val preçoFormatado = String.format("%.2f", preço) val consumoFormatado = String.format("%.2f", consumo) val distânciaFormatado = String.format("%.2f", distância) val tv_resultado = findViewById<TextView>(R.id.tv_resultado) val tv_preço2 = findViewById<TextView>(R.id.tv_preço2) val tv_consumo2 = findViewById<TextView>(R.id.tv_consumo2) val tv_distancia2 = findViewById<TextView>(R.id.tv_distancia2) val btn_Novo_Cálculo = findViewById<Button>(R.id.btn_Novo_Cálculo) tv_resultado.text = "R$ $resultadoFormatado" tv_preço2.text = "R$ $preçoFormatado" tv_consumo2.text = "$consumoFormatado Km/L" tv_distancia2.text = "$distânciaFormatado Km" btn_Novo_Cálculo.setOnClickListener { val intent = Intent(this, a_tela_Inicial::class.java) startActivity(intent) } } }
0
Kotlin
0
0
7c5dbd4275ba09da473086927d403bfdfcfb7b90
1,658
Calculadora_Gasto_Combustivel
The Unlicense
app/src/main/java/com/andrii_a/walleria/domain/models/topic/Topic.kt
andrew-andrushchenko
525,795,850
false
{"Kotlin": 656065}
package com.andrii_a.walleria.domain.models.topic import com.andrii_a.walleria.domain.TopicStatus import com.andrii_a.walleria.domain.models.photo.Photo import com.andrii_a.walleria.domain.models.user.User data class Topic( val id: String, val title: String, val description: String?, val featured: Boolean, val startsAt: String, val endsAt: String?, val updatedAt: String?, val totalPhotos: Long, val links: TopicLinks?, val status: TopicStatus, val owners: List<User>?, val coverPhoto: Photo?, val previewPhotos: List<Photo>? )
0
Kotlin
2
3
c25661c610d3197390ac86b7c63295a10095e622
583
Walleria
MIT License
app/src/main/java/com/example/movie/di/ViewModelModule.kt
eneskkoc
408,488,959
false
{"Kotlin": 14636}
package com.example.movie.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.movie.ui.main.MainViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class ViewModelModule { @Binds @PerApplication abstract fun bindViewModelFactory(factory:ViewModelFactory) :ViewModelProvider.Factory @Binds @IntoMap @ViewModelKey(MainViewModel::class) abstract fun bindMainViewModel(viewModel: MainViewModel) :ViewModel }
0
Kotlin
0
1
98989232c42843501a031fe6a765c699f458caf8
537
movie-app
MIT License
app/src/main/java/com/example/yanghuiwen/habittodoist/allItemData.kt
kikiouo201
319,902,491
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "Java": 2, "XML": 45, "Kotlin": 41}
package com.example.yanghuiwen.habittodoist import android.os.Build import android.util.Log import androidx.annotation.RequiresApi import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.* import com.google.firebase.database.ktx.database import com.google.firebase.database.ktx.getValue import com.google.firebase.ktx.Firebase import java.time.LocalDate import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.time.temporal.ChronoUnit import java.util.* import kotlin.collections.ArrayList object AllItemData { private const val TAG = "AllItemData" val database = Firebase.database private lateinit var allItemReference: DatabaseReference private lateinit var todayToDoItemReference: DatabaseReference private lateinit var diaryItemReference: DatabaseReference private lateinit var habitToDoItemReference: DatabaseReference private lateinit var projectItemReference: DatabaseReference lateinit var auth: FirebaseAuth var allToDoMap = sortedMapOf<Int, ItemDate?>() var allActivityMap = sortedMapOf<Int, ItemDate?>() var allHabitToDoMap = sortedMapOf<Int, HabitDate?>() var allProjectMap = sortedMapOf<Int, String>() var allDiaryMap = sortedMapOf<String, String>() // 今天事項 val todayToDoItem = mutableSetOf<String>() var lastallItemIndex ="" var lastallHabitIndex = "" var todayToDo = ArrayList<ItemDate>() // 單項 var endSingleItemMap = sortedMapOf<String, ArrayList<Int>>() var notEndSingleItemMap = sortedMapOf<String, ArrayList<Int>>() // 無 週 月 年 事項 val noDateToDoItem = mutableSetOf<String>() val weekToDoItem = mutableSetOf<String>() val monthToDoItem = mutableSetOf<String>() val yearToDoItem = mutableSetOf<String>() var currentDate ="2020-02-07" var currentWeekIndex = 1 @RequiresApi(Build.VERSION_CODES.O) fun getFirebaseDate(){ val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") // allItem 所有單項 allItemReference = database.getReference("user/allItem/") val allItemPostListener = object : ValueEventListener { @RequiresApi(Build.VERSION_CODES.O) override fun onDataChange(dataSnapshot: DataSnapshot) { for (ItemSnapshot in dataSnapshot.children) { var itemDate= ItemSnapshot.getValue<ItemDate>() val itemIndex = ItemSnapshot.key.toString() lastallItemIndex = itemIndex allToDoMap.put(lastallItemIndex.toInt(),itemDate) if (itemDate != null) { //檢查項目有沒有過期 if (!itemDate.endDate.equals("無")){ val itemStartDateFormatter = LocalDateTime.parse(itemDate.endDate+" 00:00:00",timeFormatter) val currentDateFormatter = LocalDateTime.now() val dateDifference = ChronoUnit.DAYS.between(itemStartDateFormatter, currentDateFormatter).toInt() if(dateDifference>0){ itemDate.IsProhibitItem = true allItemReference.child(itemIndex).setValue(itemDate) } } //單項項目沒有被禁止 if(!itemDate.IsProhibitItem){ if(itemDate.IsEndItem){ //單項項目完成 if(endSingleItemMap.get("all") != null){ val endSingleItem =endSingleItemMap.get("all") endSingleItem?.add(itemIndex.toInt()) }else{ val endSingleItem =ArrayList<Int>() endSingleItem?.add(itemIndex.toInt()) endSingleItemMap.put("all",endSingleItem) } }else{ //單項項目未完成 if(notEndSingleItemMap.get("all") != null){ val notEndSingleItem =notEndSingleItemMap.get("all") notEndSingleItem?.add(itemIndex.toInt()) // Log.i("AllItemData","notEndSingleItem${notEndSingleItem}") }else{ val notEndSingleItem =ArrayList<Int>() notEndSingleItem?.add(itemIndex.toInt()) notEndSingleItemMap.put("all",notEndSingleItem) } } } // Log.i("AllItemData","endSingleItemMap${endSingleItemMap}") // Log.i("AllItemData","notEndSingleItemMap.size${notEndSingleItemMap.size}") } } for ((key,itemIndexs)in notEndSingleItemMap){ notEndSingleItemMap[key] =deleteDuplicateArrayList(itemIndexs) } for ((key,itemIndexs)in endSingleItemMap){ endSingleItemMap[key] =deleteDuplicateArrayList(itemIndexs) } // Log.i("AllItemData","allToDoMap="+allToDoMap) } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message // Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // ... } } allItemReference.addValueEventListener(allItemPostListener) // todayToDoItem 所有單項 todayToDoItemReference = database.getReference("user/todayToDoItem/") val todayToDoItemPostListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (ItemSnapshot in dataSnapshot.children) { var itemDate= ItemSnapshot.getValue<String>() if (itemDate != null) { todayToDoItem.add(itemDate) } } // Log.i("AllItemData","allToDoMap="+allToDoMap) } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message // Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // ... } } todayToDoItemReference.addValueEventListener(todayToDoItemPostListener) // habitToDoItem 所有單項 habitToDoItemReference = database.getReference("user/allHabit/") val habitToDoItemPostListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (ItemSnapshot in dataSnapshot.children) { var habitDate= ItemSnapshot.getValue<HabitDate>() val itemIndex = ItemSnapshot.key.toString() lastallHabitIndex = itemIndex if (habitDate != null) { //檢查項目有沒有過期 if (!habitDate.endDate.equals("無")){ val itemStartDateFormatter = LocalDateTime.parse(habitDate.endDate+" 00:00:00",timeFormatter) val currentDateFormatter = LocalDateTime.now() val dateDifference = ChronoUnit.DAYS.between(itemStartDateFormatter, currentDateFormatter).toInt() if(dateDifference>0){ habitDate.IsProhibitItem = true habitToDoItemReference.child(itemIndex).setValue(habitDate) } } if (!habitDate.IsProhibitItem){ allHabitToDoMap.put(lastallHabitIndex.toInt(),habitDate) } } // Log.i(TAG," HabitToDoMap lastallItemIndex="+lastallHabitIndex.toInt()) } // Log.i(TAG," first allHabitToDoMap="+allHabitToDoMap) } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message // Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // ... } } habitToDoItemReference.addValueEventListener(habitToDoItemPostListener) // projectItem 所有專案 projectItemReference = database.getReference("user/allProject/") val projectItemPostListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (ItemSnapshot in dataSnapshot.children) { var itemDate= ItemSnapshot.getValue<String>() val itemIndex = ItemSnapshot.key?.toInt() if (itemDate != null) { allProjectMap.put(itemIndex,itemDate) } } // Log.i("AllItemData","allToDoMap="+allToDoMap) } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message // Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // ... } } projectItemReference.addValueEventListener(projectItemPostListener) // DiaryItem 所有專案 diaryItemReference = database.getReference("user/allDiary/") val diaryItemPostListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (ItemSnapshot in dataSnapshot.children) { var itemDate= ItemSnapshot.getValue<String>() val itemIndex = ItemSnapshot.key if (itemDate != null) { allDiaryMap.put(itemIndex,itemDate) } } // Log.i("AllItemData","allToDoMap="+allToDoMap) } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message // Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // ... } } diaryItemReference.addValueEventListener(diaryItemPostListener) } //刪除重複項目 fun deleteDuplicateArrayList(duplicateItems:ArrayList<Int>):ArrayList<Int>{ val toDoItemIndex = mutableSetOf<Int>() for (itemIndex in duplicateItems){ toDoItemIndex.add(itemIndex) } val f = ArrayList<Int>() for (itemIndex in toDoItemIndex){ f.add(itemIndex) } return f } // 上傳 AllItem 到firebase fun setAllItem(AddItem:ItemDate):Int{ val allItem = database.getReference("user/allItem/") if(!lastallItemIndex.equals("")){ lastallItemIndex = (lastallItemIndex.toInt()+1).toString() }else{ lastallItemIndex = "1" } //上傳firebase allItem.child(lastallItemIndex).setValue(AddItem) //存本地 allToDoMap.put(lastallItemIndex.toInt(),AddItem) return lastallItemIndex.toInt() } fun deleteAllItem(deleteIndex:Int){ val allItem = database.getReference("user/allItem/") //移除firebase上的項目 allItem.child(deleteIndex.toString()).removeValue() allToDoMap.remove(deleteIndex) } fun modifyAllItem(modifyIndex:Int,modifyItem:ItemDate){ val allItem = database.getReference("user/allItem/") //修改firebase上的項目 allItem.child(modifyIndex.toString()).setValue(modifyItem) //allToDoMap.remove(modifyIndex) } // 上傳 AllHabit 到firebase fun setAllHabit(AddHabit:HabitDate):Int{ val allHabit = database.getReference("user/allHabit/") if(!lastallHabitIndex.equals("")){ lastallHabitIndex = (lastallHabitIndex.toInt()+1).toString() }else{ lastallHabitIndex = "1" } //上傳firebase allHabit.child(lastallHabitIndex).setValue(AddHabit) //存本地 // allToDoMap.put(lastallHabitIndex.toInt(),AddHabit) return lastallHabitIndex.toInt() } fun modifyAllHabit(modifyIndex:Int,modifyItem:HabitDate){ val allItem = database.getReference("user/allHabit/") //修改firebase上的項目 allItem.child(modifyIndex.toString()).setValue(modifyItem) //allToDoMap.remove(modifyIndex) } fun deleteAllHabit(deleteIndex:Int){ val habitToDo = database.getReference("user/allHabit/") habitToDo.child(deleteIndex.toString()).removeValue() allHabitToDoMap.remove(deleteIndex) } // 上傳 AllHabit 到firebase private fun setAllProject(AddProject:String){ val allHabit = database.getReference("user/allProject/") //上傳firebase if(allProjectMap.size != 0){ allHabit.child((allProjectMap.size+1).toString()).setValue(AddProject) }else{ allHabit.child("1").setValue(AddProject) } //存本地 allProjectMap.put((allProjectMap.size+1),AddProject) } // 上傳 AllDiary 到firebase private fun setAllDiary(diaryDate :String,AddDiary:String){ val allHabit = database.getReference("user/allDiary/") //上傳firebase allHabit.child(diaryDate).setValue(AddDiary) //存本地 // allProjectMap.put((allProjectMap.size+1),AddDiary) } fun setDiary(diaryDate:String, AddDiary: String){ setAllDiary(diaryDate,AddDiary) } fun getDiary(diaryDate:String):String{ var diary = "" if(allDiaryMap[diaryDate] !=null){ diary = allDiaryMap[diaryDate].toString() } return diary } fun modifySingleItem(modifyIndex:Int, modifyItem:ItemDate){ // Log.i("AllItemData","modifySingleItem") modifyAllItem(modifyIndex,modifyItem) // val notTimeToDo = database.getReference("user/notTimeToDo/") // notTimeToDo.child(modifyIndex.toString()).setValue(modifyItem) } fun deleteSingleItem(deleteIndex:Int){ // val itemDate=allToDoMap[deleteIndex] // val projectName = itemDate?.project // val projectItems = notEndSingleItemMap.get(projectName) // if (projectItems != null) { // projectItems.remove(deleteIndex) // } // Log.i("AllItemData","deleteSingleItem") deleteAllItem(deleteIndex) } fun setSingleItem(AddItem:ItemDate) { // Log.i("AllItemData","setSingleItem=${todayToDoItem}") var addItemIndex= setAllItem(AddItem) } fun getProjectSingleItem():Map<String, ArrayList<ItemDate>> { var singleItemMap = sortedMapOf<String, ArrayList<ItemDate>>() for ((key,itemIndexs)in notEndSingleItemMap){ val itemDates = ArrayList<ItemDate>() for (itemIndex in itemIndexs) { var nowItemDate = allToDoMap.get(itemIndex.toInt()) if (nowItemDate != null) { if(singleItemMap.get(nowItemDate.project) != null){ val endSingleItem =singleItemMap.get(nowItemDate.project) endSingleItem?.add(nowItemDate) }else{ val endSingleItem =ArrayList<ItemDate>() endSingleItem?.add(nowItemDate) singleItemMap.put(nowItemDate.project,endSingleItem) } itemDates.add(nowItemDate) } } } //Log.i("AllItemData"," getSingleItem notEndSingleItemMap${notEndSingleItemMap}") return singleItemMap } fun getImportantSingleItem():Map<String, Map<String, ItemDate>> { var singleItemMap = sortedMapOf<String,Map<String, ItemDate>>() var endSingleItem = sortedMapOf<String, ItemDate>() for ((key,itemIndexs)in notEndSingleItemMap){ val itemDates = ArrayList<ItemDate>() for (itemIndex in itemIndexs) { var nowItemDate = allToDoMap.get(itemIndex.toInt()) if (nowItemDate != null && !nowItemDate.isHabit) { if(singleItemMap.get(nowItemDate.important.toString()) != null){ endSingleItem = singleItemMap.get(nowItemDate.important.toString()) as SortedMap<String, ItemDate> endSingleItem.put(itemIndex.toString(),nowItemDate) }else{ endSingleItem = sortedMapOf<String, ItemDate>() endSingleItem.put(itemIndex.toString(),nowItemDate) singleItemMap.put(nowItemDate.important.toString(),endSingleItem) } itemDates.add(nowItemDate) } } } //Log.i("AllItemData"," getSingleItem notEndSingleItemMap${notEndSingleItemMap}") return singleItemMap } fun getTimeSingleItem():Map<String, Map<String, ItemDate>> { var singleItemMap = sortedMapOf<String,Map<String, ItemDate>>() var endSingleItem = sortedMapOf<String, ItemDate>() for ((key,itemIndexs)in notEndSingleItemMap){ val itemDates = ArrayList<ItemDate>() for (itemIndex in itemIndexs) { var nowItemDate = allToDoMap.get(itemIndex.toInt()) if (nowItemDate != null && !nowItemDate.isHabit) { if(singleItemMap.get(nowItemDate.startDate) != null){ endSingleItem =singleItemMap.get(nowItemDate.startDate) as SortedMap<String, ItemDate> endSingleItem.put(itemIndex.toString(),nowItemDate) }else{ endSingleItem =sortedMapOf<String, ItemDate>() endSingleItem.put(itemIndex.toString(),nowItemDate) singleItemMap.put(nowItemDate.startDate,endSingleItem) } itemDates.add(nowItemDate) } } } return singleItemMap } // fun convertDate(d: String): String { // if (d.equals("無")){ // return "無" // }else{ // val array = d.split("-") // return array[0] + array[1] + array[2] // } // } fun getProjectHabitItem():Map<String, ArrayList<HabitDate>> { var habitToDoMap = sortedMapOf<String, ArrayList<HabitDate>>() // Log.i("AllItemData","allHabitToDoMap=${allHabitToDoMap}") for ((key,itemIndexs)in allHabitToDoMap){ val HabitDates = ArrayList<HabitDate>() var nowItemDate = itemIndexs if (nowItemDate != null) { if(habitToDoMap.get(nowItemDate.project) != null){ val endSingleItem =habitToDoMap.get(nowItemDate.project) endSingleItem?.add(nowItemDate) }else{ val endHabitItem =ArrayList<HabitDate>() endHabitItem?.add(nowItemDate) habitToDoMap.put(nowItemDate.project,endHabitItem) } HabitDates.add(nowItemDate) } } //Log.i("AllItemData"," getSingleItem notEndSingleItemMap${notEndSingleItemMap}") return habitToDoMap } fun modifyDateToDayToDo(modifyIndex:Int, modifyItem:ItemDate){ modifyAllItem(modifyIndex,modifyItem) // Log.i("AllItemData","modify todayToDoItem=${todayToDoItem}") } fun deleteDateToDayToDo(deleteIndex:Int){ deleteAllItem(deleteIndex) val todayToDo = database.getReference("user/todayToDoItem/") todayToDo.child(deleteIndex.toString()).removeValue() todayToDoItem.remove(deleteIndex.toString()) // Log.i("AllItemData","delete todayToDoItem=${todayToDoItem}") } fun getDateToDayToDo():Map<String, ItemDate>{ val todayToDo = sortedMapOf<String, ItemDate>() for (itemIndex in todayToDoItem){ var nowItemDate = allToDoMap.get(itemIndex.toInt()) // Log.i("AllItemData","nowItemDate="+nowItemDate) if(currentDate.equals(nowItemDate?.startDate)){ if (nowItemDate != null && !nowItemDate.isHabit) { todayToDo.put(itemIndex,nowItemDate) } } } return todayToDo } @RequiresApi(Build.VERSION_CODES.O) fun getIntervalDateToDo(dateCategory:String):Map<String, ItemDate>{ var intervalDateToDo = sortedMapOf<String, ItemDate>() // Log.i(TAG,"dateCategory${dateCategory}") when(dateCategory){ "年" ->{ for ((key,itemDate) in allToDoMap){ // Log.i("AllItemData","nowItemDate="+nowItemDate) if(itemDate?.timeType==4){ val mCurrentDate = LocalDate.parse(currentDate) val mNowItemDate = LocalDate.parse(itemDate?.startDate) if(mCurrentDate.year.equals(mNowItemDate.year)){ if (itemDate != null && !itemDate.isHabit) { intervalDateToDo.put(key.toString(),itemDate) } } } } } "月" ->{ for ((key,itemDate) in allToDoMap){ if(itemDate?.timeType==3){ val mCurrentDate = LocalDate.parse(currentDate) val mNowItemDate = LocalDate.parse(itemDate?.startDate) if(mCurrentDate.month.equals(mNowItemDate.month)){ if (itemDate != null && !itemDate.isHabit) { intervalDateToDo.put(key.toString(),itemDate) } } } } } "週" ->{ for ((key,itemDate) in allToDoMap){ if(itemDate?.timeType==2){ var mCurrentDate = LocalDate.parse(currentDate) val week = mCurrentDate.dayOfWeek.value mCurrentDate = mCurrentDate.minusDays((week-1).toLong()) val mNowItemDate = LocalDate.parse(itemDate?.startDate) if(mCurrentDate.equals(mNowItemDate)){ if (itemDate != null && !itemDate.isHabit) { intervalDateToDo.put(key.toString(),itemDate) } } } } } } return intervalDateToDo } fun getIntervalDateToDayToDo(intervalDates: ArrayList<String>):ArrayList<ItemDate>{ todayToDo = ArrayList<ItemDate>() for (itemIndex in todayToDoItem){ var nowItemDate = allToDoMap.get(itemIndex.toInt()) //Log.i(TAG,"nowItemDate="+nowItemDate) for (intervalDate in intervalDates) { if (intervalDate.equals(nowItemDate?.startDate)) { if (nowItemDate != null && !nowItemDate.isHabit) { todayToDo.add(nowItemDate) } } } } return todayToDo } fun setDateToDayToDo(AddItem:ItemDate):Int{ var addItemIndex= setAllItem(AddItem) todayToDoItem.add(addItemIndex.toString()) val todayToDo = database.getReference("user/todayToDoItem/") // if(!nowTodayToDoIndex.equals("")){ // val nextTodayToDoIndex = (nowTodayToDoIndex.toInt()+1).toString() //上傳firebase todayToDo.child(addItemIndex.toString()).setValue(addItemIndex.toString()) // } return addItemIndex } fun setIntervalDateToDayToDo(AddItem:ItemDate,dateCategory:String):Int{ // when(dateCategory){ // "年" ->{ // // } // "月" ->{ // // } // "週" ->{ // // } // } var addItemIndex= setAllItem(AddItem) todayToDoItem.add(addItemIndex.toString()) val todayToDo = database.getReference("user/todayToDoItem/") // if(!nowTodayToDoIndex.equals("")){ // val nextTodayToDoIndex = (nowTodayToDoIndex.toInt()+1).toString() //上傳firebase todayToDo.child(addItemIndex.toString()).setValue(addItemIndex.toString()) // } return addItemIndex } fun getAllHabitToDo(): Map<Int,HabitDate>{ var habitToDoMap = sortedMapOf<Int, HabitDate>() // Log.i("AllItemData","allHabitToDoMap=${allHabitToDoMap}") for ((key,itemIndexs)in allHabitToDoMap){ habitToDoMap.put(key,itemIndexs) } //Log.i("AllItemData"," getSingleItem notEndSingleItemMap${notEndSingleItemMap}") return habitToDoMap } fun getDateHabitToDo():Map<String, HabitDate>{ var habitToDo = sortedMapOf<String, HabitDate>() for ((key,itemIndexs)in allHabitToDoMap){ for (date in itemIndexs?.allDate!!){ if(currentDate.equals(date)){ habitToDo.put(key.toString(),itemIndexs) } } } return habitToDo } fun getIntervalDateHabitToDo(intervalDates: ArrayList<String>):ArrayList<HabitDate>{ var habitToDo = ArrayList<HabitDate>() for ((key,itemIndexs)in allHabitToDoMap){ for (date in itemIndexs?.allDate!!){ for (intervalDate in intervalDates) { if (intervalDate.equals(date)) { // Log.i("AllItemData","nowItemDate="+nowItemDate) habitToDo.add(itemIndexs) } } } } return habitToDo } @RequiresApi(Build.VERSION_CODES.O) fun setDateHabitToDo(AddHabit:HabitDate){ //拆成一個個 item //更新addItemIndex when(AddHabit.timeType){ "日" -> { val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val mStart = LocalDateTime.parse(AddHabit.startDate+" 00:00:00",timeFormatter) val mEnd = LocalDateTime.parse(AddHabit.endDate+" 00:00:00",timeFormatter) val difference = ChronoUnit.DAYS.between(mStart, mEnd).toInt() val repeatNum = AddHabit.repeatCycle[0].toInt() for (i in 0..difference step repeatNum){ AddHabit.allDate.add( mStart.plusDays(i.toLong()).format(dateFormatter)) AddHabit.notEndItemList.add(mStart.plusDays(i.toLong()).format(dateFormatter)) } } "週" -> { val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val mStart = LocalDateTime.parse(AddHabit.startDate+" 00:00:00",timeFormatter) val mEnd = LocalDateTime.parse(AddHabit.endDate+" 00:00:00",timeFormatter) val difference = ChronoUnit.DAYS.between(mStart, mEnd).toInt() for (i in 0..difference){ for (j in 0..AddHabit.repeatCycle.size-1){ val mDate = mStart.plusDays(i.toLong()) if(mDate.dayOfWeek.value == AddHabit.repeatCycle[j].toInt()){ AddHabit.allDate.add( mStart.plusDays(i.toLong()).format(dateFormatter)) AddHabit.notEndItemList.add(mStart.plusDays(i.toLong()).format(dateFormatter)) } } } } "月" -> { val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val mStart = LocalDateTime.parse(AddHabit.startDate+" 00:00:00",timeFormatter) val mEnd = LocalDateTime.parse(AddHabit.endDate+" 00:00:00",timeFormatter) val difference = ChronoUnit.DAYS.between(mStart, mEnd).toInt() for (i in 0..difference){ for (j in 0..AddHabit.repeatCycle.size-1){ val mDate = mStart.plusDays(i.toLong()) if(mDate.dayOfMonth == AddHabit.repeatCycle[j].toInt()){ AddHabit.allDate.add( mStart.plusDays(i.toLong()).format(dateFormatter)) AddHabit.notEndItemList.add(mStart.plusDays(i.toLong()).format(dateFormatter)) } } } } "年" -> { val dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val mStart = LocalDateTime.parse(AddHabit.startDate+" 00:00:00",timeFormatter) val mEnd = LocalDateTime.parse(AddHabit.endDate+" 00:00:00",timeFormatter) val difference = ChronoUnit.DAYS.between(mStart, mEnd).toInt() for (i in 0..difference){ for (j in 0..AddHabit.repeatCycle.size-1){ val mDate = mStart.plusDays(i.toLong()) var chooseTime ="" if(mDate.monthValue<10){ chooseTime +="0${mDate.monthValue}" }else{ chooseTime +="${mDate.monthValue}" } if (mDate.dayOfMonth<10){ chooseTime +="-0${mDate.dayOfMonth}" }else{ chooseTime +="-${mDate.dayOfMonth}" } if(chooseTime == AddHabit.repeatCycle[j]){ AddHabit.allDate.add( mStart.plusDays(i.toLong()).format(dateFormatter)) AddHabit.notEndItemList.add(mStart.plusDays(i.toLong()).format(dateFormatter)) } } } } } //上傳到 firebase var addHabitIndex= setAllHabit(AddHabit) // habitToDoItem.add(addHabitIndex.toString()) // val habitToDo = database.getReference("user/habitToDoItem/") // //上傳firebase // habitToDo.child(addHabitIndex.toString()).setValue(addHabitIndex.toString()) } fun checkDateHabitToDo(modifyIndex:Int, modifyItem:HabitDate){ modifyAllHabit(modifyIndex,modifyItem) } @RequiresApi(Build.VERSION_CODES.O) fun modifyDateHabitToDo(modifyIndex:Int, modifyItem:HabitDate){ setDateHabitToDo(modifyItem) deleteAllHabit(modifyIndex) //modifyAllHabit(modifyIndex,modifyItem) //把過去紀錄以外的紀錄刪除 val currentDate = LocalDateTime.now() val timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss") val nowDate = LocalDateTime.parse(currentDate.format(timeFormatter),timeFormatter) val startDate = LocalDateTime.parse(modifyItem.startDate+" 00:00:00",timeFormatter) val endDate = LocalDateTime.parse(modifyItem.endDate+" 00:00:00",timeFormatter) val nowToEndDateDifference = ChronoUnit.DAYS.between(nowDate, endDate).toInt() // Log.i("AllItemData","nowToEndDateDifference=${nowToEndDateDifference}") // if(nowToEndDateDifference>0){ // //項目中有未來 可動 // //刪掉未來的 // for (notEndItemDate in modifyItem.notEndItemList){ // val notEndItem = allToDoMap[notEndItemDate.toInt()] // val notEndStartDate = LocalDateTime.parse(notEndItem?.startDate+" 00:00:00",timeFormatter) // val nowToNotEndDateDifference = ChronoUnit.DAYS.between(nowDate, notEndStartDate).toInt() // if(nowToNotEndDateDifference>0){ // //未來的項目 // modifyItem.notEndItemList.remove(notEndItemDate) // } // } // //重新建未來的 // addSingleItemOfHabit() // // } //modifyAllItem(modifyIndex,modifyItem) // Log.i("AllItemData","modify todayToDoItem=${todayToDoItem}") } fun deleteDateHabitToDo(deleteIndex:Int){ deleteAllHabit(deleteIndex) } fun addSingleItemOfHabit(){ } fun getHabitToDoList():ArrayList<HabitDate>{ val habitToDoList = ArrayList<HabitDate>() for (itemIndex in allHabitToDoMap){ itemIndex.value?.let { habitToDoList.add(it) } // Log.i("AllItemData","nowItemDate="+nowItemDate) } return habitToDoList } fun getDateActivity():Map<String, ItemDate>{ var activity = sortedMapOf<String, ItemDate>() for ((key,nowItemDate)in allActivityMap){ if(currentDate.equals(nowItemDate?.startDate)){ // Log.i("AllItemData","nowItemDate="+nowItemDate?.startDate) if (nowItemDate != null ){ activity.put(key.toString(),nowItemDate) } } } return activity } fun getIntervalDateActivity(intervalDates: ArrayList<String>):ArrayList<ItemDate>{ var activity = ArrayList<ItemDate>() for ((key,nowItemDate)in allActivityMap){ for (intervalDate in intervalDates){ if(intervalDate.equals(nowItemDate?.startDate)){ // Log.i("AllItemData","nowItemDate="+nowItemDate?.startDate) if (nowItemDate != null ){ activity.add(nowItemDate) } } } } return activity } fun setActivity(eventID:Long,startDate:String,endDate:String,startTime:String,endTime:String,title:String){ val addItem =ItemDate() addItem.name = title addItem.startDate = startDate addItem.endDate = endDate addItem.startTime = startTime addItem.endTime = endTime addItem.isActivity = true allActivityMap.put(eventID.toInt(),addItem) } //專案 fun getProjectHabitDate(projectName:String):Map<String,HabitDate>{ val allProjectHabitDate = sortedMapOf<String,HabitDate>() for ((key,item)in allHabitToDoMap){ if (item != null) { if(item.project.equals(projectName)){ allProjectHabitDate.put(key.toString(),item) } } } return allProjectHabitDate } fun getProjectItemDate(projectName : String):Map<String,ItemDate>{ val allProjectItemDate = sortedMapOf<String,ItemDate>() for ((key,item)in allToDoMap){ if (item != null) { if(item.project.equals(projectName)){ allProjectItemDate.put(key.toString(),item) } } } return allProjectItemDate } fun getProjectName():ArrayList<String>{ var allProject = ArrayList<String>() for ((key,item)in allProjectMap){ allProject.add(item) } return allProject } fun setProject(AddProject:String){ setAllProject(AddProject) } fun dateFormatter(year:Int,monthOfYear:Int,dayOfMonth:Int):String{ var chooseTime ="" chooseTime ="${year}" if(monthOfYear+1<10){ chooseTime +="-0${monthOfYear+1}" }else{ chooseTime +="-${monthOfYear+1}" } if (dayOfMonth<10){ chooseTime +="-0${dayOfMonth}" }else{ chooseTime +="-${dayOfMonth}" } return chooseTime } }
0
Kotlin
0
0
5a58e75503064b0f1f2619ef04b21fec0f9308b9
36,288
habitToDoList
Apache License 2.0
src/main/kotlin/nl/jackploeg/aoc/_2022/calendar/day04/Day04.kt
jackploeg
736,755,380
false
{"Kotlin": 318734}
package nl.jackploeg.aoc._2022.calendar.day04 import javax.inject.Inject import nl.jackploeg.aoc.generators.InputGenerator.InputGeneratorFactory import nl.jackploeg.aoc.utilities.readStringFile class Day04 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { // get number of containments fun partOne(fileName: String): Int { val assignmentPairs: List<Pair<IntRange, IntRange>> = readStringFile(fileName) .map { toRangePair(it) } return assignmentPairs.count { rangesContained(it) } } // get number of overlaps fun partTwo(fileName: String): Int { val assignmentPairs: List<Pair<IntRange, IntRange>> = readStringFile(fileName) .map { toRangePair(it) } return assignmentPairs.count { rangesOverlap(it) } } fun toRangePair(input: String): Pair<IntRange, IntRange> { val ranges = input.split(",") val (start1, end1) = ranges[0].split("-") val range1 = start1.toInt().rangeTo(end1.toInt()) val (start2, end2) = ranges[1].split("-") val range2 = start2.toInt().rangeTo(end2.toInt()) return Pair(range1, range2) } fun rangesContained(ranges: Pair<IntRange, IntRange>): Boolean { return (ranges.first.contains(ranges.second.first) && ranges.first.contains(ranges.second.last)) || (ranges.second.contains(ranges.first.first) && ranges.second.contains(ranges.first.last)) } fun rangesOverlap(ranges: Pair<IntRange, IntRange>): Boolean { return ranges.first.contains(ranges.second.first) || ranges.first.contains(ranges.second.last) || ranges.second.contains(ranges.first.first) || ranges.second.contains(ranges.first.last) }}
0
Kotlin
0
0
f2b873b6cf24bf95a4ba3d0e4f6e007b96423b76
1,782
advent-of-code
MIT License
komapper-core/src/main/kotlin/org/komapper/core/dsl/query/Query.kt
komapper
349,909,214
false
null
package org.komapper.core.dsl.query import kotlinx.coroutines.flow.Flow import org.komapper.core.ThreadSafe import org.komapper.core.dsl.expression.SortExpression import org.komapper.core.dsl.expression.SubqueryExpression import org.komapper.core.dsl.options.SelectOptions import org.komapper.core.dsl.visitor.QueryVisitor @ThreadSafe interface Query<out T> { fun <VISIT_RESULT> accept(visitor: QueryVisitor<VISIT_RESULT>): VISIT_RESULT } interface ListQuery<out T> : Query<List<T>> { fun <R> collect(collect: suspend (Flow<T>) -> R): Query<R> } interface Subquery<T> : ListQuery<T>, SubqueryExpression<T> { infix fun except(other: SubqueryExpression<T>): SetOperationQuery<T> infix fun intersect(other: SubqueryExpression<T>): SetOperationQuery<T> infix fun union(other: SubqueryExpression<T>): SetOperationQuery<T> infix fun unionAll(other: SubqueryExpression<T>): SetOperationQuery<T> } interface SetOperationQuery<T> : Subquery<T> { fun orderBy(vararg aliases: CharSequence): SetOperationQuery<T> fun orderBy(vararg expressions: SortExpression): SetOperationQuery<T> fun options(configure: (SelectOptions) -> SelectOptions): SetOperationQuery<T> }
6
Kotlin
0
16
7092a2bd24b609a1816bf05c89730259ff45178d
1,193
komapper
Apache License 2.0
idea/tests/testData/intentions/convertCollectionConstructorToFunction/replaceHashMapCall.kt
JetBrains
278,369,660
false
null
// WITH_RUNTIME import java.util.HashMap fun foo() { var list: HashMap<Int, Int> = <caret>HashMap() }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
106
intellij-kotlin
Apache License 2.0
app/src/main/java/org/tty/dailyset/model/entity/DailyCell.kt
h1542462994
346,364,988
false
null
package org.tty.dailyset.model.entity import androidx.room.Entity import androidx.room.PrimaryKey import androidx.room.TypeConverters import org.tty.dailyset.common.datetime.epochLocalDateTime import org.tty.dailyset.model.converter.StringLocalDateTimeConverter import org.tty.dailyset.model.converter.StringLocalTimeConverter import java.time.LocalDateTime import java.time.LocalTime @Entity(tableName = "daily_cell") @TypeConverters(StringLocalTimeConverter::class, StringLocalDateTimeConverter::class) data class DailyCell( @PrimaryKey var uid: String, /** * the reference dailyRowUid */ var dailyRowUid: String, /** * the index of the total. */ var currentIndex: Int, /** * time duration .start */ var start: LocalTime, /** * time duration .end */ var end: LocalTime, /** * a.m. = 0; p.m. = 1; evening = 2 */ var normalType: Int, /** * the index of the current group */ var serialIndex: Int, var updateAt: LocalDateTime ): Comparable<DailyCell> { companion object { const val default = "#default" fun default(): List<DailyCell> { return listOf( DailyCell( uid = "${default}-0", currentIndex = 0, start = LocalTime.parse("08:00:00"), end = LocalTime.parse("08:45:00"), normalType = 0, serialIndex = 0, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-1", currentIndex = 1, start = LocalTime.parse("08:55:00"), end = LocalTime.parse("09:40:00"), normalType = 0, serialIndex = 1, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-2", currentIndex = 2, start = LocalTime.parse("09:55:00"), end = LocalTime.parse("10:40:00"), normalType = 0, serialIndex = 2, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-3", currentIndex = 3, start = LocalTime.parse("10:50:00"), end = LocalTime.parse("11:35:00"), normalType = 0, serialIndex = 3, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-4", currentIndex = 4, start = LocalTime.parse("11:45:00"), end = LocalTime.parse("12:30:00"), normalType = 0, serialIndex = 4, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-5", currentIndex = 5, start = LocalTime.parse("13:30:00"), end = LocalTime.parse("14:15:00"), normalType = 1, serialIndex = 0, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-6", currentIndex = 7, start = LocalTime.parse("14:25:00"), end = LocalTime.parse("15:10:00"), normalType = 1, serialIndex = 1, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-7", currentIndex = 8, start = LocalTime.parse("15:25:00"), end = LocalTime.parse("16:10:00"), normalType = 1, serialIndex = 2, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-8", currentIndex = 9, start = LocalTime.parse("16:20:00"), end = LocalTime.parse("17:05:00"), normalType = 1, serialIndex = 3, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-9", currentIndex = 10, start = LocalTime.parse("18:30:00"), end = LocalTime.parse("19:15:00"), normalType = 2, serialIndex = 0, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-10", currentIndex = 11, start = LocalTime.parse("19:25:00"), end = LocalTime.parse("20:10:00"), normalType = 2, serialIndex = 1, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), DailyCell( uid = "${default}-11", currentIndex = 12, start = LocalTime.parse("20:20:00"), end = LocalTime.parse("21:05:00"), normalType = 2, serialIndex = 2, dailyRowUid = DailyRow.default, updateAt = epochLocalDateTime() ), ) } } override fun compareTo(other: DailyCell): Int { return this.currentIndex.compareTo(other.currentIndex) } }
1
Kotlin
0
0
57b384fd50ab7892c46be70a16f81f396e65d6ee
6,343
DailySet
MIT License