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
bbfgradle/tmp/results/BACKUP_JVM/FRONTEND_jbxcnht_PROJECT.kt
DaniilStepanov
346,008,310
false
{"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1}
// Bug happens on JVM -Xuse-ir // WITH_RUNTIME // WITH_COROUTINES // FILE: tmp0.kt import helpers.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* fun builder(c: suspend () -> Unit) { c.startCoroutine(EmptyContinuation) } @Suppress(listOf(1uL, 3uL, 5uL, 7uL), ulongList) inline class IC(val s: Long) class Test1() { suspend fun <T> foo(value: T): T { return suspendCoroutineUninterceptedOrReturn { try { it.resume(value) } catch (e: AssertionError) { "OK" } finally{} COROUTINE_SUSPENDED } } suspend fun qux(ss: IC): IC = IC(ss.s) suspend fun <T> quz(t: T): T = t suspend fun bar(): IC { return foo(qux(quz(IC(42L)))) } suspend fun test() = bar().s } class Test2 { suspend fun foo(value: IC): IC { return suspendCoroutineUninterceptedOrReturn { it.resume(value) COROUTINE_SUSPENDED } } suspend fun qux(s: Long): IC = IC(s) suspend fun quz() = 42L suspend fun bar(): IC { return foo(qux(42)) } suspend fun test() = bar().s } class Test3 { suspend fun <T> foo(value: T): T { return suspendCoroutineUninterceptedOrReturn { it.resume(value) COROUTINE_SUSPENDED } } suspend fun bar(): IC { return foo(IC(42L)) } suspend fun test() = bar().s } fun Long.toBoxResult() = if (try { this } catch(e: Exception){} == 42L) "OK" else String() fun box(): String { var result: CharSequence = "FAIL" builder { result = Test1().test().toBoxResult() } if (result != "OK") return "FAIL 1 $result" try { result = "FAIL2" } catch(e: Exception){} builder { result = Test2().test().toBoxResult() } if (result != "1OK") return "FAIL 2 $result" try { result = "fail 2" } catch(e: Exception){} finally{} builder { result = Test3().test().toBoxResult() } return result as String }
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
2,020
kotlinWithFuzzer
Apache License 2.0
app/src/main/java/com/example/bogungym/adapter/ChoosingAdapter.kt
momabogun
693,280,109
false
{"Kotlin": 95124}
package com.example.bogungym.adapter import android.annotation.SuppressLint import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.net.toUri import androidx.navigation.findNavController import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.bogungym.ExercisesViewModel import com.example.bogungym.R import com.example.bogungym.data.model.Exercises import com.example.bogungym.data.model.UserWorkout import com.example.bogungym.databinding.ListItemCustomBinding import com.example.bogungym.ui.ChoosingFragment import com.example.bogungym.ui.ChoosingFragmentDirections import com.google.firebase.firestore.ktx.toObjects import java.util.Locale class ChoosingAdapter( private var dataset: List<Exercises>, private val context: ChoosingFragment, val viewModel: ExercisesViewModel ) : RecyclerView.Adapter<ChoosingAdapter.ItemViewHolder>() { inner class ItemViewHolder(val binding: ListItemCustomBinding) : RecyclerView.ViewHolder(binding.root) @SuppressLint("NotifyDataSetChanged") fun newData(newList: List<Exercises>) { dataset = newList notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder { val binding = ListItemCustomBinding .inflate(LayoutInflater.from(parent.context), parent, false) return ItemViewHolder(binding) } override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { val item = dataset[position] holder.binding.exerTV.text = item.name.replaceFirstChar { if (it.isLowerCase()) it.titlecase( Locale.ROOT ) else it.toString() } holder.binding.equipTV.text = item.equipment.replaceFirstChar { if (it.isLowerCase()) it.titlecase( Locale.ROOT ) else it.toString() } val imgUri = item.gifUrl.toUri().buildUpon().scheme("https").build() Glide .with(context) .asBitmap() .load(imgUri) .into(holder.binding.exerIV) holder.binding.chooseBTN.setImageResource(R.drawable.baseline_circle_24) if (item.userPick) { holder.binding.imageView3.visibility = View.VISIBLE } else { holder.binding.imageView3.visibility = View.GONE } holder.itemView.setOnClickListener { val navController = holder.itemView.findNavController() navController.navigate(ChoosingFragmentDirections.actionChoosingFragmentToDetailFragment(item.id)) } holder.binding.chooseBTN.setOnClickListener { if (!item.userPick){ viewModel.addPickedExercise(item.id) } else{ viewModel.removePickedExercise(item.id) } viewModel.updatePick(!item.userPick,item.id) } } override fun getItemCount(): Int { return dataset.size } }
0
Kotlin
0
0
cf7a68ae6285311d14a808aeb8886c6489fe5bdb
3,101
BogunGym
MIT License
app/src/main/java/com/vanzoconsulting/tictactoe/ui/BoardActivity.kt
2021-DEV-005
361,874,547
false
null
package com.vanzoconsulting.tictactoe.ui import android.os.Bundle import android.view.View import android.view.View.GONE import android.view.View.VISIBLE import android.widget.TextView import androidx.annotation.StringRes import androidx.core.content.ContextCompat.getColor import androidx.core.text.HtmlCompat.FROM_HTML_MODE_COMPACT import androidx.core.text.HtmlCompat.fromHtml import androidx.core.view.children import com.vanzoconsulting.domain.Board import com.vanzoconsulting.domain.Player import com.vanzoconsulting.domain.Player.O import com.vanzoconsulting.domain.Player.X import com.vanzoconsulting.domain.label import com.vanzoconsulting.tictactoe.R import dagger.android.support.DaggerAppCompatActivity import kotlinx.android.synthetic.main.activity_board.* import javax.inject.Inject class BoardActivity: DaggerAppCompatActivity(), BoardContract.View { @Inject lateinit var presenter: BoardContract.Presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_board) fab_restart.hide() presenter.view = this presenter.loadBoard() } override fun renderBoard(board: Board) { board_grid.children.filterIsInstance(TextView::class.java).forEachIndexed { index, view -> view.text = board[index]?.label() view.setTextColor(getColor(this, if (board[index] == O) R.color.colorPlayer2 else R.color.colorPlayer )) if (view.text.isEmpty()) { view.isClickable = true view.setOnClickListener { presenter.makeMove(board, index) } } else { view.isClickable = false view.setOnClickListener(null) } } } override fun showWinner(player: Player) = showMessage( if (player == X) R.string.board_message_winner_x else R.string.board_message_winner_o ) override fun showDraw() = showMessage(R.string.board_message_draw) private fun showMessage(@StringRes stringRes: Int) { tv_message.visibility = VISIBLE tv_message.text = fromHtml(getString(stringRes), FROM_HTML_MODE_COMPACT) fab_restart.show() } @Suppress("UNUSED_PARAMETER") fun onRestartClick(v: View) { presenter.loadBoard() } override fun reset() { fab_restart.hide() tv_message.visibility = GONE renderBoard(Board()) } override fun onDestroy() { super.onDestroy() presenter.view = null } }
0
Kotlin
0
0
7d4f7dbe8c8589cb6feb37a091086047044f5fd1
2,705
TicTacToe
Apache License 2.0
Test/Transaction/NonsegwitUTxO.kt
rushmi0
656,012,539
false
null
package LaeliaX.Transaction import LaeliaX.util.Bech32 import LaeliaX.util.ShiftTo.decodeBase58 import LaeliaX.util.Hashing.doubleSHA256 import LaeliaX.util.ShiftTo.DeciToHex import LaeliaX.util.ShiftTo.ByteToHex import LaeliaX.util.ShiftTo.ByteArrayToHex import LaeliaX.util.ShiftTo.HexToByteArray import LaeliaX.util.ShiftTo.DeciToHexByte import LaeliaX.util.ShiftTo.FlipByteOrder import LaeliaX.MiniScript.OP_ import LaeliaX.MiniScript.Validator.getLockTime import LaeliaX.MiniScript.Validator.viewScript import LaeliaX.MiniScript.Validator.generateTransactionID import LaeliaX.SecureKey.ECDSA.SignSignatures import LaeliaX.SecureKey.ECDSA.toDERFormat import LaeliaX.SecureKey.WIF.extractWIF import LaeliaX.util.Address.verify.isP2PKH import LaeliaX.util.Address.verify.isP2WPKH import java.math.BigInteger import java.nio.ByteBuffer import java.nio.ByteOrder class NonsegwitUTxO(private val version: Int, private val privateKey: String) { private val inputs: MutableList<UTxOInput> = mutableListOf() private val outputs: MutableList<UTxOOutput> = mutableListOf() private var scriptCode: String? = null private var lockTime: Int? = null // * UTxO ขาเข้า fun addInput(transactionID: String, outputIndex: Int, scriptCode: String) { val input = UTxOInput(transactionID, outputIndex, scriptCode) this.inputs.add(input) this.scriptCode = scriptCode setLockTime(scriptCode) } // * UTxO ขาออก fun addOutput(amounts: Long, address: String) { val output = UTxOOutput(amounts, address) this.outputs.add(output) } private fun setLockTime(scriptCode: String) { this.lockTime = viewScript(scriptCode).getLockTime() } // * ประกอบ "ธุรกรรมดิบ" ขึ้นมา fun generateUnsignedTransaction(): String { val version = NETWORKS.VERSION[this.version].toString() val inputCount = inputs.size.DeciToHex().toInt().DeciToHexByte() val inputComponents = inputs.joinToString("") { it.generateInputComponents() } val outputCount = outputs.size.DeciToHex().toInt().DeciToHexByte() val outputComponents = outputs.joinToString("") { it.generateOutputComponents() } val lockTime = this.lockTime!!.let { ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(it).array().ByteArrayToHex() } return version + inputCount + inputComponents + outputCount + outputComponents + lockTime } private fun ScriptSigComponents(SignaturePoint: Pair<BigInteger, BigInteger>): String { val Signature = toDERFormat(SignaturePoint) + "01" val SignatureLength: String = Signature.HexToByteArray().size.DeciToHex() val RedeemLength: String = this.scriptCode.toString().HexToByteArray().size.DeciToHex() val RedeemScriptCode: String = this.scriptCode.toString() val scriptSigLength: String = ( SignatureLength + Signature + RedeemLength + RedeemScriptCode ).HexToByteArray().size.DeciToHex() val result = scriptSigLength + SignatureLength + Signature + RedeemLength + RedeemScriptCode return result } private fun Pair<BigInteger, BigInteger>.getScriptSig(): String { return ScriptSigComponents(this) } fun signTransaction(): String { val unsignedTransaction = generateUnsignedTransaction() val message = BigInteger(unsignedTransaction.HexToByteArray().doubleSHA256().ByteArrayToHex(), 16) val signatures = SignSignatures(BigInteger(privateKey, 16), message) return mergeSignature(unsignedTransaction, signatures.getScriptSig()) } private fun mergeSignature(UTxO: String, ScriptSig: String): String { val pattern = "00000000(.*?)f(.?)ffffff" val regex = Regex(pattern) val match = regex.find(UTxO) if (match != null) { val originalData = match.groupValues[1] val modifiedData = ScriptSig val result = UTxO.replaceFirst(originalData, modifiedData) return result } return UTxO } // * สร้างองค์ประกอบ UTxO ขาเข้า private data class UTxOInput(val txID: String, val vout: Int, val scriptCode: String) { // * https://en.bitcoin.it/wiki/Dump_format#CTxIn fun generateInputComponents(): String { val txIDFlip = txID.FlipByteOrder() val voutHex = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(vout).array().ByteArrayToHex() val scriptSize = scriptCode.HexToByteArray().size.DeciToHex() val time = viewScript(scriptCode).getLockTime() // * คุณสมบัติเฉพาะ val sequence: List<String> = listOf( "ffffffff", // อนุญาตปิดลง block ได้ทันที "fdffffff", // ไม่อนุญาตปิดลง block ได้ทันทีจนกว่าจะถึงเวลาที่กำหนด //"feffffff" // ยกเลิกการใช้คุณสมบัติ "replace-by-fee" (RBF) ) return if (time > 0) { txIDFlip + voutHex + scriptSize + scriptCode + sequence[1] } else { txIDFlip + voutHex + scriptSize + scriptCode + sequence[0] } } } // * สร้างองค์ประกอบ UTxO ขาออก private data class UTxOOutput(val amounts: Long, val address: String) { // * https://en.bitcoin.it/wiki/Dump_format#CTxOut fun generateOutputComponents(): String { // * โอนไปที่ P2WPKH if (address.isP2WPKH()) { val amounts = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(amounts).array().ByteArrayToHex() val data = Bech32.bech32ToSegwit(address)[2] as ByteArray val size = data.size.DeciToHex() val scriptCode = ( OP_.FALSE.ByteToHex() + size + data.ByteArrayToHex() ) val scriptSize = scriptCode.HexToByteArray().size.DeciToHex() return amounts + scriptSize + scriptCode } // * โอนไปที่ P2PKH if (address.isP2PKH()) { val amounts = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(amounts).array().ByteArrayToHex() val data = address.decodeBase58().HexToByteArray() val keyHash = data.copyOfRange(1, 21) val keyHashSize = keyHash.size.DeciToHex() // * https://en.bitcoin.it/wiki/Dump_format#CScript val scriptCode = ( OP_.DUP.ByteToHex() + OP_.HASH160.ByteToHex() + keyHashSize + keyHash.ByteArrayToHex() + OP_.EQUALVERIFY.ByteToHex() + OP_.CHECKSIG.ByteToHex() ) val scriptSize = scriptCode.HexToByteArray().size.DeciToHex() return amounts + scriptSize + scriptCode } throw IllegalArgumentException("Invalid 'address'") } } } fun main() { /** * L1c3ZfZu5e8TiQKS9FJ9ioh4GXEjxjob5ZSgqYRCHwrGNNEnyrBk * 02aa36a1958e2fc5e5de75d05bcf6f3ccc0799be4905f4e418505dc6ab4422a8db * */ val wif = "L1c3ZfZu5e8TiQKS9FJ9ioh4GXEjxjob5ZSgqYRCHwrGNNEnyrBk" val privateKey = wif.extractWIF() val tx = NonsegwitUTxO(2, privateKey) // * UTxO : ขาเข้า tx.addInput( "de496c29138457073c86de1f6818c8caccb6be3cdfce57254cba5f66f8046bda", 0, "03b43b25b1752102aa36a1958e2fc5e5de75d05bcf6f3ccc0799be4905f4e418505dc6ab4422a8dbac" ) // * UTxO : ขาออก tx.addOutput( 5_800, "tb1q7uqrl2tjxj43zunc5aka3fuv2ssn990qhltahj" ) val unsignedTransaction = tx.generateUnsignedTransaction() val txUID = unsignedTransaction.generateTransactionID() println("Transaction ID: $txUID") println("Unsigned Transaction:\n$unsignedTransaction \n") val signedTransaction = tx.signTransaction() val txSID = signedTransaction.generateTransactionID() println("\nTransaction ID: $txSID") println("Signed Transaction: \n$signedTransaction") } // ! Road to Bitcoin developer
1
null
0
1
3830aaeb06e75140ab0e3242400f59a5b0fba445
8,266
LaeliaX
MIT License
litho-it/src/test/com/facebook/litho/TreeDiffingTest.kt
facebook
80,179,724
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho import android.R import android.graphics.Color import android.graphics.Rect import android.graphics.drawable.Drawable import androidx.collection.SparseArrayCompat import com.facebook.litho.MountSpecLithoRenderUnit.UpdateState import com.facebook.litho.config.ComponentsConfiguration import com.facebook.litho.drawable.ComparableColorDrawable import com.facebook.litho.testing.LegacyLithoViewRule import com.facebook.litho.testing.TestComponent import com.facebook.litho.testing.TestDrawableComponent import com.facebook.litho.testing.TestSizeDependentComponent import com.facebook.litho.testing.Whitebox import com.facebook.litho.testing.exactly import com.facebook.litho.testing.inlinelayoutspec.InlineLayoutSpec import com.facebook.litho.testing.testrunner.LithoTestRunner import com.facebook.litho.widget.Text import com.facebook.rendercore.MountItem import com.facebook.rendercore.RenderTreeNode import com.facebook.yoga.YogaAlign import com.facebook.yoga.YogaEdge import java.lang.Exception import org.assertj.core.api.Assertions.assertThat import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.mock import org.mockito.kotlin.whenever import org.robolectric.annotation.LooperMode @RunWith(LithoTestRunner::class) @LooperMode(LooperMode.Mode.LEGACY) class TreeDiffingTest { @JvmField @Rule val legacyLithoViewRule = LegacyLithoViewRule( ComponentsConfiguration.defaultInstance.copy(shouldAddHostViewForRootComponent = true)) @Before @Throws(Exception::class) fun setup() { RedDrawable = ComparableColorDrawable.create(Color.RED) BlackDrawable = ComparableColorDrawable.create(Color.BLACK) TransparentDrawable = ComparableColorDrawable.create(Color.TRANSPARENT) } @Test fun testLayoutStateDiffing() { val component: Component = object : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .build() } } val layoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component, exactly(350), exactly(200), null) // Check diff tree is not null and consistent. val node = layoutState.diffTree assertThat(node).isNotNull assertThat(4).isEqualTo(countNodes(requireNotNull(node))) } @Test fun testCachedMeasureFunction() { val c = legacyLithoViewRule.context val component0: Component = Text.create(c).text("hello-world").build() legacyLithoViewRule.attachToWindow().setRoot(component0).layout().measure() val diffNode = legacyLithoViewRule.committedLayoutState?.diffTree val component1: Component = Text.create(c).text("hello-world").build() legacyLithoViewRule.setRoot(component1).layout().measure() val result = legacyLithoViewRule.currentRootNode assertThat(result?.width).isEqualTo(diffNode?.lastMeasuredWidth) assertThat(result?.height).isEqualTo(diffNode?.lastMeasuredHeight) } @Test fun tesLastConstraints() { val c = legacyLithoViewRule.context val component0: Component = Text.create(c).text("hello-world").build() legacyLithoViewRule.attachToWindow().setRoot(component0).layout().measure() val diffNode = legacyLithoViewRule.committedLayoutState?.diffTree val component1: Component = Text.create(c).text("hello-world").build() legacyLithoViewRule.setRoot(component1).layout().measure() val result = legacyLithoViewRule.currentRootNode assertThat(diffNode?.lastWidthSpec).isEqualTo(result?.widthSpec) assertThat(diffNode?.lastHeightSpec).isEqualTo(result?.heightSpec) } @Test fun testCachedMeasures() { val c = legacyLithoViewRule.context val component0: Component = Column.create(c) .child(Text.create(c).text("hello-world").build()) .child(Text.create(c).text("hello-world").build()) .build() legacyLithoViewRule.attachToWindow().setRoot(component0).layout().measure() val component1: Component = Column.create(c) .child(Text.create(c).text("hello-world").build()) .child(Text.create(c).text("hello-world").build()) .build() legacyLithoViewRule.setRoot(component1).layout().measure() val result = legacyLithoViewRule.currentRootNode assertThat(result?.getChildAt(0)?.cachedMeasuresValid).isTrue assertThat(result?.getChildAt(1)?.cachedMeasuresValid).isTrue } @Test fun testPartiallyCachedMeasures() { val c = legacyLithoViewRule.context val component0: Component = Column.create(c) .child(Text.create(c).text("hello-world-1").build()) .child(Text.create(c).text("hello-world-2").build()) .build() legacyLithoViewRule.attachToWindow().setRoot(component0).layout().measure() val component1: Component = Column.create(c) .child(Text.create(c).text("hello-world-1").build()) .child(Text.create(c).text("hello-world-3").build()) .build() legacyLithoViewRule.setRoot(component1).layout().measure() val result = legacyLithoViewRule.currentRootNode assertThat(result?.getChildAt(0)?.cachedMeasuresValid).isTrue assertThat(result?.getChildAt(1)?.cachedMeasuresValid).isFalse } @Test fun testLayoutOutputReuse() { // Needed because of (legacy) usage two different InlineLayoutSpec that the test wants to treat // as the same component type. val COMPONENT_IDENTITY = 12345 val component1: Component = object : InlineLayoutSpec(COMPONENT_IDENTITY) { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .build() } } val component2: Component = object : InlineLayoutSpec(COMPONENT_IDENTITY) { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .build() } } val prevLayoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component1, exactly(350), exactly(200), null) val layoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component2, exactly(350), exactly(200), prevLayoutState) assertThat(layoutState.getMountableOutputCount()) .isEqualTo(prevLayoutState.getMountableOutputCount()) var i = 0 val count = prevLayoutState.getMountableOutputCount() while (i < count) { assertThat(layoutState.getMountableOutputAt(i).renderUnit.id) .isEqualTo(prevLayoutState.getMountableOutputAt(i).renderUnit.id) i++ } } @Test fun testLayoutOutputPartialReuse() { // Needed because of (legacy) usage two different InlineLayoutSpec that the test wants to treat // as the same component type. val COMPONENT_IDENTITY = 12345 val component1: Component = object : InlineLayoutSpec(COMPONENT_IDENTITY) { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .build() } } val component2: Component = object : InlineLayoutSpec(COMPONENT_IDENTITY) { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .child(TestDrawableComponent.create(c)) .build() } } val prevLayoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component1, exactly(350), exactly(200), null) val layoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component2, exactly(350), exactly(200), prevLayoutState) Assert.assertNotEquals( prevLayoutState.getMountableOutputCount().toLong(), layoutState.getMountableOutputCount().toLong()) var i = 0 val count = prevLayoutState.getMountableOutputCount() while (i < count) { assertThat(layoutState.getMountableOutputAt(i).renderUnit.id) .describedAs("Output $i") .isEqualTo(prevLayoutState.getMountableOutputAt(i).renderUnit.id) i++ } } private fun assertCachedMeasurementsNotDefined(node: LithoLayoutResult) { assertThat(node.cachedMeasuresValid).isFalse } private fun checkAllComponentsHaveMeasureCache(node: LithoLayoutResult) { if (node.node.tailComponent != null && node.node.tailComponent.canMeasure()) { assertCachedMeasurementsDefined(node) } val numChildren = node.childCount for (i in 0 until numChildren) { checkAllComponentsHaveMeasureCache(node.getChildAt(i)) } } @Test fun testComponentHostMoveItem() { val c = legacyLithoViewRule.componentTree.context val hostHolder = ComponentHost(c) val mountItem: MountItem = mock() whenever(mountItem.renderTreeNode).thenReturn(createNode(Column.create(c).build())) val mountItem1: MountItem = mock() whenever(mountItem1.renderTreeNode).thenReturn(createNode(Column.create(c).build())) val mountItem2: MountItem = mock() whenever(mountItem2.renderTreeNode).thenReturn(createNode(Column.create(c).build())) hostHolder.mount(0, mountItem, Rect()) hostHolder.mount(1, mountItem1, Rect()) hostHolder.mount(2, mountItem2, Rect()) assertThat(mountItem).isEqualTo(hostHolder.getMountItemAt(0)) assertThat(mountItem1).isEqualTo(hostHolder.getMountItemAt(1)) assertThat(mountItem2).isEqualTo(hostHolder.getMountItemAt(2)) hostHolder.moveItem(mountItem, 0, 2) hostHolder.moveItem(mountItem2, 2, 0) assertThat(mountItem2).isEqualTo(hostHolder.getMountItemAt(0)) assertThat(mountItem1).isEqualTo(hostHolder.getMountItemAt(1)) assertThat(mountItem).isEqualTo(hostHolder.getMountItemAt(2)) } @Test fun testComponentHostMoveItemPartial() { val c = legacyLithoViewRule.componentTree.context val hostHolder = ComponentHost(c) val mountItem: MountItem = mock() whenever(mountItem.renderTreeNode).thenReturn(createNode(Column.create(c).build())) val mountItem1: MountItem = mock() whenever(mountItem1.renderTreeNode).thenReturn(createNode(Column.create(c).build())) val mountItem2: MountItem = mock() whenever(mountItem2.renderTreeNode).thenReturn(createNode(Column.create(c).build())) hostHolder.mount(0, mountItem, Rect()) hostHolder.mount(1, mountItem1, Rect()) hostHolder.mount(2, mountItem2, Rect()) assertThat(mountItem).isEqualTo(hostHolder.getMountItemAt(0)) assertThat(mountItem1).isEqualTo(hostHolder.getMountItemAt(1)) assertThat(mountItem2).isEqualTo(hostHolder.getMountItemAt(2)) hostHolder.moveItem(mountItem2, 2, 0) assertThat(mountItem2).isEqualTo(hostHolder.getMountItemAt(0)) assertThat(mountItem1).isEqualTo(hostHolder.getMountItemAt(1)) assertThat(1) .isEqualTo( (Whitebox.getInternalState<Any>(hostHolder, "mScrapMountItemsArray") as? SparseArrayCompat<MountItem?>) ?.size()) hostHolder.unmount(0, mountItem) assertThat(2) .isEqualTo( (Whitebox.getInternalState<Any>(hostHolder, "mMountItems") as? SparseArrayCompat<MountItem?>) ?.size()) assertThat(Whitebox.getInternalState<Any?>(hostHolder, "mScrapMountItemsArray")).isNull() } @Test fun testLayoutOutputUpdateState() { val c = legacyLithoViewRule.context val firstComponent: Component = TestDrawableComponent.create(c).color(Color.BLACK).build() val secondComponent: Component = TestDrawableComponent.create(c).color(Color.BLACK).build() val thirdComponent: Component = TestDrawableComponent.create(c).color(Color.WHITE).build() legacyLithoViewRule.setRoot(firstComponent).attachToWindow() legacyLithoViewRule.setRootAndSizeSpecSync(firstComponent, exactly(10), exactly(10)) val state = legacyLithoViewRule.componentTree.mainThreadLayoutState assertOutputsState(state, MountSpecLithoRenderUnit.STATE_UNKNOWN) legacyLithoViewRule.setRoot(secondComponent) val secondState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertOutputsState(secondState, MountSpecLithoRenderUnit.STATE_UPDATED) legacyLithoViewRule.setRoot(thirdComponent) val thirdState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertOutputsState(thirdState, MountSpecLithoRenderUnit.STATE_DIRTY) } @Test fun testLayoutOutputUpdateStateWithBackground() { val component1: Component = TestLayoutSpecBgState(false) val component2: Component = TestLayoutSpecBgState(false) val component3: Component = TestLayoutSpecBgState(true) legacyLithoViewRule.setRoot(component1).attachToWindow() legacyLithoViewRule.setRootAndSizeSpecSync(component1, exactly(10), exactly(10)) val state = legacyLithoViewRule.componentTree.mainThreadLayoutState assertOutputsState(state, MountSpecLithoRenderUnit.STATE_UNKNOWN) legacyLithoViewRule.setRoot(component2) val secondState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertThat(secondState?.getMountableOutputCount()).isEqualTo(4) legacyLithoViewRule.setRoot(component3) val thirdState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertThat(thirdState?.getMountableOutputCount()).isEqualTo(4) assertThat( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(thirdState?.getMountableOutputAt(2)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UPDATED) assertThat( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(thirdState?.getMountableOutputAt(3)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UPDATED) } // This test covers the same case with the foreground since the code path is the same! @Test fun testLayoutOutputUpdateStateWithBackgroundInWithLayout() { val component1: Component = TestLayoutSpecInnerState(false) val component2: Component = TestLayoutSpecInnerState(false) val component3: Component = TestLayoutSpecInnerState(true) legacyLithoViewRule.setRoot(component1).attachToWindow() legacyLithoViewRule.setRootAndSizeSpecSync(component1, exactly(10), exactly(10)) val state = legacyLithoViewRule.componentTree.mainThreadLayoutState assertThat( MountSpecLithoRenderUnit.getUpdateState(requireNotNull(state?.getMountableOutputAt(2)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UNKNOWN) legacyLithoViewRule.setRoot(component2) val secondState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertThat( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(2)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UNKNOWN) assertThat( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(3)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UPDATED) legacyLithoViewRule.setRoot(component3) val thirdState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertThat( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(thirdState?.getMountableOutputAt(2)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UNKNOWN) assertThat( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(thirdState?.getMountableOutputAt(3)))) .isEqualTo(MountSpecLithoRenderUnit.STATE_UPDATED) } @Test fun testLayoutOutputUpdateStateIdClash() { val component1: Component = TestLayoutWithStateIdClash(false) val component2: Component = TestLayoutWithStateIdClash(true) legacyLithoViewRule.setRoot(component1).attachToWindow() legacyLithoViewRule.setRootAndSizeSpecSync(component1, exactly(10), exactly(10)) val state = legacyLithoViewRule.componentTree.mainThreadLayoutState assertOutputsState(state, MountSpecLithoRenderUnit.STATE_UNKNOWN) legacyLithoViewRule.setRoot(component2) val secondState = legacyLithoViewRule.componentTree.mainThreadLayoutState assertThat(6).isEqualTo(secondState?.getMountableOutputCount()) assertThat(MountSpecLithoRenderUnit.STATE_DIRTY) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(0)))) assertThat(MountSpecLithoRenderUnit.STATE_UNKNOWN) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(1)))) assertThat(MountSpecLithoRenderUnit.STATE_UPDATED) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(2)))) assertThat(MountSpecLithoRenderUnit.STATE_UNKNOWN) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(3)))) assertThat(MountSpecLithoRenderUnit.STATE_UNKNOWN) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(4)))) assertThat(MountSpecLithoRenderUnit.STATE_UPDATED) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(secondState?.getMountableOutputAt(5)))) } @Test fun testDiffTreeUsedIfRootMeasureSpecsAreDifferentButChildHasSame() { val c = legacyLithoViewRule.componentTree.context val component: TestComponent = TestDrawableComponent.create(c).color(Color.BLACK).build() val layoutComponent: Component = TestSimpleContainerLayout2(component) val firstLayoutState = calculateLayoutStateWithDiffing(c, layoutComponent, exactly(100), exactly(100), null) assertThat(component.wasMeasureCalled()).isTrue val secondComponent: TestComponent = TestDrawableComponent.create(c).color(Color.BLACK).build() val secondLayoutComponent: Component = TestSimpleContainerLayout2(secondComponent) calculateLayoutStateWithDiffing( c, secondLayoutComponent, exactly(100), exactly(90), firstLayoutState) assertThat(secondComponent.wasMeasureCalled()).isFalse } @Test fun testDiffTreeUsedIfMeasureSpecsAreSame() { val c = legacyLithoViewRule.componentTree.context val component: TestComponent = TestDrawableComponent.create(c).color(Color.BLACK).build() val layoutComponent: Component = TestSimpleContainerLayout(component, 0) val firstLayoutState = calculateLayoutStateWithDiffing(c, layoutComponent, exactly(100), exactly(100), null) assertThat(component.wasMeasureCalled()).isTrue val secondComponent: TestComponent = TestDrawableComponent.create(c).color(Color.BLACK).build() val secondLayoutComponent: Component = TestSimpleContainerLayout(secondComponent, 0) calculateLayoutStateWithDiffing( c, secondLayoutComponent, exactly(100), exactly(100), firstLayoutState) assertThat(secondComponent.wasMeasureCalled()).isFalse } @Test fun testCachedMeasuresForNestedTreeComponentDelegateWithUndefinedSize() { val component1: Component = TestNestedTreeDelegateWithUndefinedSizeLayout() val component2: Component = TestNestedTreeDelegateWithUndefinedSizeLayout() val prevLayoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component1, exactly(350), exactly(200), null) val layoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component2, exactly(350), exactly(200), prevLayoutState) // The nested root measure() was called in the first layout calculation. val prevNestedRoot = LithoRenderUnit.getRenderUnit(prevLayoutState.getMountableOutputAt(2)).component as TestComponent assertThat(prevNestedRoot.wasMeasureCalled()).isTrue val nestedRoot = LithoRenderUnit.getRenderUnit(layoutState.getMountableOutputAt(2)).component as TestComponent assertThat(nestedRoot.wasMeasureCalled()).isFalse } @Test fun testCachedMeasuresForNestedTreeComponentWithUndefinedSize() { val component1: Component = TestUndefinedSizeLayout() val component2: Component = TestUndefinedSizeLayout() val prevLayoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component1, exactly(350), exactly(200), null) val layoutState = calculateLayoutStateWithDiffing( legacyLithoViewRule.componentTree.context, component2, exactly(350), exactly(200), prevLayoutState) // The nested root measure() was called in the first layout calculation. val prevMainTreeLeaf = LithoRenderUnit.getRenderUnit(prevLayoutState.getMountableOutputAt(1)).component as TestComponent assertThat(prevMainTreeLeaf.wasMeasureCalled()).isTrue val prevNestedLeaf1 = LithoRenderUnit.getRenderUnit(prevLayoutState.getMountableOutputAt(3)).component as TestComponent assertThat(prevNestedLeaf1.wasMeasureCalled()).isTrue val prevNestedLeaf2 = LithoRenderUnit.getRenderUnit(prevLayoutState.getMountableOutputAt(4)).component as TestComponent assertThat(prevNestedLeaf2.wasMeasureCalled()).isTrue val mainTreeLeaf = LithoRenderUnit.getRenderUnit(layoutState.getMountableOutputAt(1)).component as TestComponent assertThat(mainTreeLeaf.wasMeasureCalled()).isFalse val nestedLeaf1 = LithoRenderUnit.getRenderUnit(layoutState.getMountableOutputAt(3)).component as TestComponent assertThat(nestedLeaf1.wasMeasureCalled()).isFalse val nestedLeaf2 = LithoRenderUnit.getRenderUnit(layoutState.getMountableOutputAt(4)).component as TestComponent assertThat(nestedLeaf2.wasMeasureCalled()).isFalse } private class TestLayoutSpec internal constructor(private val addThirdChild: Boolean) : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .child(if (addThirdChild) TestDrawableComponent.create(c) else null) .build() } } private class TestSimpleContainerLayout internal constructor(private val component: Component, private val horizontalPadding: Int) : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .paddingPx(YogaEdge.HORIZONTAL, horizontalPadding) .child(component) .build() } } private class TestSimpleContainerLayout2 internal constructor(private val component: Component) : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .alignItems(YogaAlign.FLEX_START) .child(Wrapper.create(c).delegate(component).heightPx(50)) .build() } } private class TestLayoutSpecInnerState internal constructor(private val changeChildDrawable: Boolean) : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .background(RedDrawable) .foregroundRes(R.drawable.btn_default) .child( TestDrawableComponent.create(c) .background(if (changeChildDrawable) RedDrawable else BlackDrawable)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .build() } } private class TestLayoutSpecBgState internal constructor(private val changeBg: Boolean) : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .background(if (changeBg) BlackDrawable else RedDrawable) .foreground(TransparentDrawable) .child(TestDrawableComponent.create(c)) .child(Column.create(c).child(TestDrawableComponent.create(c))) .build() } } private class TestUndefinedSizeLayout : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .paddingPx(YogaEdge.ALL, 2) .child(TestDrawableComponent.create(c, true, true, false)) .child( TestSizeDependentComponent.create(c) .setDelegate(false) .flexShrink(0f) .marginPx(YogaEdge.ALL, 11)) .build() } } private class TestNestedTreeDelegateWithUndefinedSizeLayout : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .paddingPx(YogaEdge.ALL, 2) .child(TestSizeDependentComponent.create(c).setDelegate(true).marginPx(YogaEdge.ALL, 11)) .build() } } private class TestLayoutWithStateIdClash internal constructor(private val addChild: Boolean) : InlineLayoutSpec() { override fun onCreateLayout(c: ComponentContext): Component { return Column.create(c) .child( Column.create(c) .wrapInView() .child(TestDrawableComponent.create(c)) .child(if (addChild) TestDrawableComponent.create(c) else null)) .child(Column.create(c).wrapInView().child(TestDrawableComponent.create(c))) .build() } } companion object { private lateinit var RedDrawable: Drawable private lateinit var BlackDrawable: Drawable private lateinit var TransparentDrawable: Drawable private fun countNodes(node: DiffNode): Int { var sum = 1 for (i in 0 until node.childCount) { val child = node.getChildAt(i) if (child != null) { sum += countNodes(child) } } return sum } private fun calculateLayoutState( context: ComponentContext, component: Component, widthSpec: Int, heightSpec: Int ): LayoutState { val result = ResolveTreeFuture.resolve(context, component, TreeState(), -1, -1, null, null, null, null) return LayoutTreeFuture.layout(result, widthSpec, heightSpec, -1, -1, null, null, null, null) } private fun calculateLayoutStateWithDiffing( context: ComponentContext, component: Component, widthSpec: Int, heightSpec: Int, previousLayoutState: LayoutState? ): LayoutState { val result = ResolveTreeFuture.resolve( context, component, TreeState(), -1, -1, previousLayoutState?.mRoot, null, null, null) return LayoutTreeFuture.layout( result, widthSpec, heightSpec, -1, -1, previousLayoutState, previousLayoutState?.diffTree, null, null) } private fun assertOutputsState(layoutState: LayoutState?, @UpdateState state: Int) { assertThat(MountSpecLithoRenderUnit.STATE_DIRTY) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(layoutState?.getMountableOutputAt(0)))) for (i in 1 until (layoutState?.getMountableOutputCount() ?: 0)) { assertThat(state) .isEqualTo( MountSpecLithoRenderUnit.getUpdateState( requireNotNull(layoutState?.getMountableOutputAt(i)))) } } private fun assertCachedMeasurementsDefined(node: LithoLayoutResult) { val diffHeight: Int = node.diffNode?.lastMeasuredHeight ?: -1 val diffWidth: Int = node.diffNode?.lastMeasuredWidth ?: -1 assertThat(diffHeight != -1).isTrue assertThat(diffWidth != -1).isTrue assertThat(node.cachedMeasuresValid).isTrue } private fun createNode(component: Component): RenderTreeNode { val unit: LithoRenderUnit = MountSpecLithoRenderUnit.create( 0, component, null, null, null, 0, 0, MountSpecLithoRenderUnit.STATE_UNKNOWN, null) return create( unit, Rect(), LithoLayoutData( 0, 0, 0, 0, null, null, if (component is SpecGeneratedComponent) { component.isMountSizeDependent } else { false }, null), null) } } }
90
null
769
7,703
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
30,215
litho
Apache License 2.0
src/test/kotlin/de/codecentric/totiblogpost/IdGenerator.kt
codecentric
471,350,927
false
null
package de.codecentric.totiblogpost import org.springframework.util.SocketUtils import java.util.* class IdGenerator { companion object { @Synchronized // TODO migrate to TestSocketUtils once its released. See: https://github.com/spring-projects/spring-framework/issues/28052 fun nextPort(): Int = SocketUtils.findAvailableTcpPort(10001) fun nextAsString(): String = UUID.randomUUID().toString() fun nextAsLong(): Long = Random().nextLong() } }
0
Kotlin
0
0
943168175dc08396484893f25a57c2296bfefc0a
498
toti-example-service
MIT License
extension/src/test/java/org/nvest/extension/NumberKtTest.kt
nvest-solutions
331,924,233
false
null
package org.nvest.extension import org.assertj.core.api.Assertions.assertThat import org.junit.Test class NumberKtTest { @Test fun `Number is rounded properly`() { val input = 123.456 val result = input.round(2) assertThat(result).isEqualTo(123.46) } @Test fun `Double in String is a number`() { val input = "123.456" val result = input.isNumber() assertThat(result).isTrue } @Test fun `Integer in String is a number`() { val input = "123" val result = input.isNumber() assertThat(result).isTrue } @Test fun `Text in String is not a number`() { val input = "123Abc" val result = input.isNumber() assertThat(result).isFalse } @Test fun `null is not a number`() { val input = null val result = input.isNumber() assertThat(result).isFalse } @Test fun `some string is not a number`() { val input = "a" val result = input.isNotNumber() assertThat(result).isTrue } }
0
Kotlin
0
1
d3569b9b90db750cba206a6a9e76f65f70fa6b51
1,095
android-extensions
Apache License 2.0
butterfly-compose/src/main/kotlin/io/getstream/butterfly/compose/internal/Extensions.kt
GetStream
451,401,439
false
{"Kotlin": 71414}
/* * Copyright 2022 Stream.IO, Inc. 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 io.getstream.butterfly.compose.internal import android.content.res.Resources import android.util.DisplayMetrics /** Returns dp size from a pixel size. */ @PublishedApi internal val Int.px2dp: Int @JvmSynthetic inline get() = this / (Resources.getSystem().displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)
3
Kotlin
10
213
620cbbf99480bef97fb887311e8f1d3bf6eaf4cd
954
butterfly
Apache License 2.0
app/src/main/java/jp/mihailskuzmins/sugoinihongoapp/persistence/models/Word.kt
MihailsKuzmins
240,947,625
false
null
package jp.mihailskuzmins.sugoinihongoapp.persistence.models import jp.mihailskuzmins.sugoinihongoapp.extensions.runIf interface Word { val original: String val translation: String val transcription: String } fun Word.createJapaneseTextWithNewLine(isTranscriptionShown: Boolean) = StringBuilder(translation) .runIf(isTranscriptionShown && transcription.isNotBlank()) { appendln().append(transcription) }.toString() fun Word.createJapaneseTextWithBrackets() = StringBuilder(translation) .runIf(transcription.isNotBlank()) { append(" [${transcription}]") } .toString()
1
null
1
1
57e19b90b4291dc887a92f6d57f9be349373a444
587
sugoi-nihongo-android
Apache License 2.0
libraries/tools/new-project-wizard/src/org/jetbrains/kotlin/tools/projectWizard/moduleConfigurators/JsModuleConfigurator.kt
Sathawale27
247,057,405
true
{"Kotlin": 45118239, "Java": 7616593, "JavaScript": 197377, "HTML": 77202, "Lex": 23783, "TypeScript": 21238, "Groovy": 11196, "CSS": 9144, "Shell": 7220, "Batchfile": 5360, "Swift": 2272, "Ruby": 1300, "Objective-C": 404, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.tools.projectWizard.moduleConfigurators import org.jetbrains.kotlin.tools.projectWizard.core.context.ReadingContext import org.jetbrains.kotlin.tools.projectWizard.core.buildList import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.KotlinBuildSystemPluginIR import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.gradle.RawGradleIR import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleConfigurationData import org.jetbrains.kotlin.tools.projectWizard.plugins.kotlin.ModuleType import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.Module import org.jetbrains.kotlin.tools.projectWizard.settings.buildsystem.ModuleKind interface JSConfigurator : ModuleConfiguratorWithModuleType { override val moduleType: ModuleType get() = ModuleType.js } object JsSingleplatformModuleConfigurator : JSConfigurator, ModuleConfiguratorWithTests { override val moduleKind = ModuleKind.singleplatformJs override val suggestedModuleName = "js" override val id = "jsSinglepaltform" override val text = "JS for Browser" override fun defaultTestFramework(): KotlinTestFramework = KotlinTestFramework.JS override val canContainSubModules = false override fun createKotlinPluginIR(configurationData: ModuleConfigurationData, module: Module): KotlinBuildSystemPluginIR? = KotlinBuildSystemPluginIR( KotlinBuildSystemPluginIR.Type.js, version = configurationData.kotlinVersion ) override fun createBuildFileIRs( readingContext: ReadingContext, configurationData: ModuleConfigurationData, module: Module ): List<BuildSystemIR> = buildList { +RawGradleIR { +"kotlin.target.browser { }" } } }
0
Kotlin
0
1
9dd201aaf243cf9198cf129b22d3aa38fcff182c
2,070
kotlin
Apache License 2.0
src/test/enhetstester/kotlin/no/nav/familie/ks/sak/integrasjon/familieintegrasjon/IntegrasjonClientTest.kt
navikt
533,308,075
false
{"Kotlin": 3728348, "Gherkin": 186833, "Shell": 1839, "Dockerfile": 467}
package no.nav.familie.ks.sak.integrasjon.familieintegrasjon import com.github.tomakehurst.wiremock.WireMockServer import com.github.tomakehurst.wiremock.client.WireMock import com.github.tomakehurst.wiremock.core.WireMockConfiguration import io.mockk.every import io.mockk.mockkObject import no.nav.familie.kontrakter.felles.Tema import no.nav.familie.kontrakter.felles.dokarkiv.LogiskVedleggRequest import no.nav.familie.kontrakter.felles.dokarkiv.v2.ArkiverDokumentRequest import no.nav.familie.kontrakter.felles.dokdist.Distribusjonstype import no.nav.familie.kontrakter.felles.oppgave.FinnOppgaveRequest import no.nav.familie.ks.sak.api.dto.JournalpostBrukerDto import no.nav.familie.ks.sak.api.dto.OppdaterJournalpostRequestDto import no.nav.familie.ks.sak.data.randomFnr import no.nav.familie.ks.sak.sikkerhet.SikkerhetContext import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.containsInAnyOrder import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.springframework.boot.web.client.RestTemplateBuilder import org.springframework.web.client.RestOperations import java.net.URI import org.hamcrest.CoreMatchers.`is` as Is internal class IntegrasjonClientTest { private val restOperations: RestOperations = RestTemplateBuilder().build() private lateinit var integrasjonClient: IntegrasjonClient private lateinit var wiremockServerItem: WireMockServer @BeforeEach fun initClass() { wiremockServerItem = WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort()) wiremockServerItem.start() integrasjonClient = IntegrasjonClient(URI.create(wiremockServerItem.baseUrl()), restOperations) } @Test fun `hentOppgaver skal returnere en liste av oppgaver basert på request og tema`() { wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/oppgave/v4")) .willReturn(WireMock.okJson(readFile("hentOppgaverEnkelKONResponse.json"))), ) val oppgaver = integrasjonClient.hentOppgaver(FinnOppgaveRequest(Tema.KON)) assertThat(oppgaver.antallTreffTotalt, Is(1)) assertThat(oppgaver.oppgaver.size, Is(1)) assertThat(oppgaver.oppgaver.single().tema, Is(Tema.KON)) } @Test fun `hentBehandlendeEnhet skal hente enhet fra familie-integrasjon`() { wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/arbeidsfordeling/enhet/KON")) .willReturn(WireMock.okJson(readFile("hentBehandlendeEnhetEnkelResponse.json"))), ) val behandlendeEnheter = integrasjonClient.hentBehandlendeEnheter("testident") assertThat(behandlendeEnheter.size, Is(2)) assertThat(behandlendeEnheter.map { it.enhetId }, containsInAnyOrder("enhetId1", "enhetId2")) assertThat(behandlendeEnheter.map { it.enhetNavn }, containsInAnyOrder("enhetNavn1", "enhetNavn2")) } @Test fun `hentNavKontorEnhet skal hente enhet fra familie-integrasjon`() { wiremockServerItem.stubFor( WireMock.get(WireMock.urlEqualTo("/arbeidsfordeling/nav-kontor/200")) .willReturn(WireMock.okJson(readFile("hentEnhetEnkelResponse.json"))), ) val navKontorEnhet = integrasjonClient.hentNavKontorEnhet("200") assertThat(navKontorEnhet.enhetId, Is(200)) assertThat(navKontorEnhet.enhetNr, Is("200")) assertThat(navKontorEnhet.navn, Is("Riktig navn")) assertThat(navKontorEnhet.status, Is("Riktig status")) } @Test fun `finnOppgaveMedId skal hente oppgave med spesifikt id fra familie-integrasjon`() { wiremockServerItem.stubFor( WireMock.get(WireMock.urlEqualTo("/oppgave/200")) .willReturn(WireMock.okJson(readFile("finnOppgaveMedIdEnkelResponse.json"))), ) val oppgave = integrasjonClient.finnOppgaveMedId(200) assertThat(oppgave.id, Is(200)) assertThat(oppgave.tildeltEnhetsnr, Is("4812")) assertThat(oppgave.endretAvEnhetsnr, Is("4812")) assertThat(oppgave.journalpostId, Is("123456789")) assertThat(oppgave.tema, Is(Tema.KON)) } @Test fun `sjekkTilgangTilPersoner skal returnere Tilgang med true hvis SB har tilgang til alle personidenter`() { wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/tilgang/v2/personer")) .willReturn(WireMock.okJson(readFile("sjekkTilgangTilPersonerResponseMedTilgangTilAlle.json"))), ) mockkObject(SikkerhetContext) every { SikkerhetContext.erSystemKontekst() } returns false val tilgangTilPersonIdent = integrasjonClient.sjekkTilgangTilPersoner(listOf("ident1", "ident2", "ident3")) assertThat(tilgangTilPersonIdent.all { it.harTilgang }, Is(true)) assertThat(tilgangTilPersonIdent.all { it.begrunnelse == "Har tilgang" }, Is(true)) } @Test fun `sjekkTilgangTilPersoner skal returnere Tilgang med false hvis SB ikke har tilgang til alle personidenter`() { wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/tilgang/v2/personer")) .willReturn(WireMock.okJson(readFile("sjekkTilgangTilPersonerResponseMedIkkeTilgangTilAlle.json"))), ) mockkObject(SikkerhetContext) every { SikkerhetContext.erSystemKontekst() } returns false val tilgangTilPersonIdent = integrasjonClient.sjekkTilgangTilPersoner(listOf("ident1", "ident2", "ident3")) assertThat(tilgangTilPersonIdent.all { it.harTilgang }, Is(false)) assertThat(tilgangTilPersonIdent.any { it.begrunnelse == "Har ikke tilgang" }, Is(true)) assertThat(tilgangTilPersonIdent.any { it.begrunnelse == "Har tilgang" }, Is(true)) } @Test fun `fordelOppgave skal returnere fordelt oppgave ved OK fordelelse av oppgave`() { val saksbehandler = "testSB" wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/oppgave/200/fordel?saksbehandler=$saksbehandler")) .willReturn(WireMock.okJson(readFile("fordelOppgaveEnkelResponse.json"))), ) val fordeltOppgave = integrasjonClient.fordelOppgave(200, saksbehandler) assertThat(fordeltOppgave.oppgaveId, Is(200)) } @Test fun `tilordneEnhetForOppgave skal returnere tildelt oppgave ved OK fordelelse av enhet`() { val nyEnhet = "testenhet" wiremockServerItem.stubFor( WireMock.patch(WireMock.urlEqualTo("/oppgave/200/enhet/testenhet?fjernMappeFraOppgave=true")) .willReturn(WireMock.okJson(readFile("fordelOppgaveEnkelResponse.json"))), ) val fordeltOppgave = integrasjonClient.tilordneEnhetForOppgave(200, nyEnhet) assertThat(fordeltOppgave.oppgaveId, Is(200)) } @Test fun `leggTilLogiskVedlegg skal returnere id på vedlegg som ble lagt til`() { val request = LogiskVedleggRequest("testtittel") wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/arkiv/dokument/testid/logiskVedlegg")) .willReturn(WireMock.okJson(readFile("logiskVedleggEnkelResponse.json"))), ) val fordeltOppgave = integrasjonClient.leggTilLogiskVedlegg(request, "testid") assertThat(fordeltOppgave.logiskVedleggId, Is(200)) } @Test fun `slettLogiskVedlegg skal returnere id på vedlegg som ble slettet til`() { wiremockServerItem.stubFor( WireMock.delete(WireMock.urlEqualTo("/arkiv/dokument/testDokumentId/logiskVedlegg/testId")) .willReturn(WireMock.okJson(readFile("logiskVedleggEnkelResponse.json"))), ) val fordeltOppgave = integrasjonClient.slettLogiskVedlegg("testId", "testDokumentId") assertThat(fordeltOppgave.logiskVedleggId, Is(200)) } @Test fun `oppdaterJournalpost skal returnere id på journalpost som ble oppdatert`() { val request = OppdaterJournalpostRequestDto(bruker = JournalpostBrukerDto(id = "testId", navn = "testNavn")) wiremockServerItem.stubFor( WireMock.put(WireMock.urlEqualTo("/arkiv/v2/testJournalpostId")) .willReturn(WireMock.okJson(readFile("oppdaterJournalpostEnkelResponse.json"))), ) val fordeltOppgave = integrasjonClient.oppdaterJournalpost(request, "testJournalpostId") assertThat(fordeltOppgave.journalpostId, Is("oppdatertJournalpostId")) } @Test fun `ferdigstillJournalpost skal sette journalpost til ferdigstilt`() { wiremockServerItem.stubFor( WireMock.put(WireMock.urlEqualTo("/arkiv/v2/testJournalPost/ferdigstill?journalfoerendeEnhet=testEnhet")) .willReturn(WireMock.okJson(readFile("logiskVedleggEnkelResponse.json"))), ) integrasjonClient.ferdigstillJournalpost("testJournalPost", "testEnhet") } @Test fun `journalførDokument skal returnere detaljer om dokument som ble journalført`() { val request = ArkiverDokumentRequest(randomFnr(), true, emptyList(), emptyList()) wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/arkiv/v4")) .willReturn(WireMock.okJson(readFile("journalførDokumentEnkelResponse.json"))), ) val arkiverDokumentResponse = integrasjonClient.journalførDokument(request) assertThat(arkiverDokumentResponse.ferdigstilt, Is(true)) assertThat(arkiverDokumentResponse.journalpostId, Is("12345678")) } @Test fun `hentLand skal returnere landNavn gitt landKode`() { val landKode = "NOR" wiremockServerItem.stubFor( WireMock.get(WireMock.urlEqualTo("/kodeverk/landkoder/$landKode")) .willReturn(WireMock.okJson(readFile("hentLandEnkelResponse.json"))), ) val hentLandKodeRespons = integrasjonClient.hentLand(landKode) assertThat(hentLandKodeRespons, Is("Norge")) } @Test fun `distribuerBrev skal en bestillingsid på at brevet at distribuert`() { wiremockServerItem.stubFor( WireMock.post(WireMock.urlEqualTo("/dist/v1")) .willReturn(WireMock.okJson(readFile("distribuerBrevEnkelResponse.json"))), ) val bestillingId = integrasjonClient.distribuerBrev("testId", Distribusjonstype.VEDTAK) assertThat(bestillingId, Is("testBestillingId")) } private fun readFile(filnavn: String): String { return this::class.java.getResource("/familieintegrasjon/json/$filnavn").readText() } }
3
Kotlin
1
2
c39fb12189c468a433ca2920b1aa0f5509b23d54
10,578
familie-ks-sak
MIT License
mapview-desktop/src/desktopMain/kotlin/example/map/SearchOrCrop.kt
ShreyashKore
672,328,509
false
null
package template.map import kotlin.math.max fun Map<Tile, TileImage>.searchOrCrop(tile: Tile): TileImage? { val img1 = get(tile) if (img1 != null) { return img1 } var zoom = tile.zoom var x = tile.x var y = tile.y while (zoom > 0) { zoom-- x /= 2 y /= 2 val tile2 = Tile(zoom, x, y) val img2 = get(tile2) if (img2 != null) { val deltaZoom = tile.zoom - tile2.zoom val i = tile.x - (x shl deltaZoom) val j = tile.y - (y shl deltaZoom) val size = max(TILE_SIZE ushr deltaZoom, 1) return img2.cropAndRestoreSize(i * size, j * size, size) } } return null }
4
null
1
94
a0d32d8abc3e6b0470f38e74d1e632e1ab3f0999
715
wonderous_compose
MIT License
src/main/kotlin/com/github/mrbean355/admiralbulldog/persistence/migration/From0To1Migration.kt
danieldonaldson
318,585,457
true
{"Kotlin": 200715}
package com.github.mrbean355.admiralbulldog.persistence.migration import com.google.gson.JsonArray import com.google.gson.JsonObject import com.google.gson.JsonParser.parseString class From0To1Migration : Migration(from = 0, to = 1) { override fun migrate(config: JsonObject) { doLegacyMigration(config) // Volume changed from double to int. config.getAsJsonPrimitive("volume").let { config["volume"] = it.asDouble.toInt() } // New property: updates. config["updates"] = parseString("{ \"appUpdateCheck\": 0, \"appUpdateFrequency\": \"WEEKLY\", \"soundsUpdateFrequency\": \"DAILY\", \"modUpdateCheck\": 0, \"modUpdateFrequency\": \"ALWAYS\" }") // New "sounds" object properties: chance, minRate, maxRate. config.getAsJsonObject("sounds").entrySet().forEach { (_, el) -> el.asJsonObject.apply { this["chance"] = 100.0 this["minRate"] = 100.0 this["maxRate"] = 100.0 } } // New property: special. config["special"] = parseString("{ \"useHealSmartChance\": true, \"minPeriod\": 5, \"maxPeriod\": 15 }") // System tray was added back; notify when minimised. config["trayNotified"] = false } /** Make sure there are no null properties. */ private fun doLegacyMigration(config: JsonObject) { if (config.get("id") == null) { config["id"] = "" } if (config.get("dotaPath") == null) { config["dotaPath"] = "" } if (config.get("discordToken") == null) { config["discordToken"] = "" } if (config.get("soundBoard") == null) { config["soundBoard"] = JsonArray() } if (config.get("modVersion") == null) { config["modVersion"] = "" } if (config.getAsJsonObject("sounds").get("OnRespawn") == null) { config.getAsJsonObject("sounds")["OnRespawn"] = parseString("{ \"enabled\": \"false\", \"playThroughDiscord\": false, \"sounds\": [] }") } } }
0
null
0
0
6495a9b2d9b7fc9ba5652d3e5a58389abe828f1b
2,112
admiralbulldog-sounds
Apache License 2.0
HttpServer/src/main/java/top/fksoft/server/http/server/serverIO/responseData/impl/raw/FileResponseData.kt
ExplodingDragon
216,512,177
false
null
package top.fksoft.server.http.server.serverIO.responseData.impl.raw import top.fksoft.server.http.config.HttpConstant import top.fksoft.server.http.config.ResponseCode import top.fksoft.server.http.config.ResponseCode.Companion.HTTP_NOT_MODIFIED import top.fksoft.server.http.config.ResponseCode.Companion.HTTP_OK import top.fksoft.server.http.config.ResponseCode.Companion.HTTP_PARTIAL import top.fksoft.server.http.server.serverIO.HttpHeaderInfo import top.fksoft.server.http.server.serverIO.responseData.BaseResponseData import top.fksoft.server.http.utils.CalculateUtils import top.fksoft.server.http.utils.ContentTypeUtils import java.io.* /** * @author ExplodingDragon * @version 1.0 */ /** * 文件断点续传 * * @property file File 解析的文件 * @property breakpoint 开启断点续传(实际情况受内部解析而定) * @property length Long Content-Length 长度 * @property responseCode ResponseCode 请求ID * @property contentType String 文件类型 * @constructor */ class FileResponseData(private val httpHeaderInfo: HttpHeaderInfo, private val file: File, private val breakpoint: Boolean = false) : BaseResponseData() { override var length: Long = 0 override var responseCode: ResponseCode = ResponseCode.HTTP_OK override var contentType: String = ContentTypeUtils.file2Application(file) data class Range(val start: Long, val end: Long) { val size = end - start + 1 } private val rangeFormatList = ArrayList<Range>() private val eTag by lazy { "\"${getFileETag(file)}\"" } private val lastModified by lazy { webDateFormat.format(file.lastModified()) } init { if (file.isFile.not()) { throw FileNotFoundException("${file.absolutePath} exists."); } val clientModified = httpHeaderInfo.getHeader("If-Modified-Since") //客户端下文件记录的修改时间 val clientETag = httpHeaderInfo.getHeader("If-None-Match", HttpConstant.UNKNOWN_VALUE) val fileLength = file.length() if (clientETag == eTag && clientModified != "") { if (lastModified.trim().toLowerCase() == clientModified.trim().toLowerCase()) { // 确定本地文件与网络文件为同一个, 发送 304 ,同时不发送 body responseCode = HTTP_NOT_MODIFIED length = 0 addHeader("Last-Modified", lastModified) addHeader("ETag", eTag) } else { // 表示本地文件与服务器文件并不相同 responseCode = HTTP_OK length = fileLength addHeader("Last-Modified", lastModified) addHeader("ETag", eTag) } }else{ responseCode = HTTP_OK length = fileLength addHeader("Last-Modified", lastModified) addHeader("ETag", eTag) } val clientRange = httpHeaderInfo.getHeader("Range", "") if (breakpoint && responseCode == HTTP_NOT_MODIFIED && clientRange != "") { val rangeData = clientRange.split("=")[1] val rangeArray = rangeData.split(",") rangeArray.forEach { val trim = it.trim() val i = trim.indexOf("-") val split = trim.split('-') length += when (i) { 0 -> { val l = split[0].toLong() val element = Range(fileLength - l, fileLength - 1) rangeFormatList.add(element) element.size } trim.length - 1 -> { val l = split[0].toLong() val element = Range(l, fileLength - 1) rangeFormatList.add(element) element.size } else -> { val element = Range(split[0].toLong(), split[1].toLong()) rangeFormatList.add(element) element.size } } } addHeader("Content-Range", "bytes $rangeData/$fileLength") responseCode = HTTP_PARTIAL } } override fun writeBody(output: OutputStream): Boolean { val b = ByteArray(4096) if (responseCode == HTTP_OK) { val inputStream = file.inputStream() while (true) { val i = inputStream.read(b) if (i == -1) { break } output.write(b, 0, i) output.flush() } inputStream.close() } else if (responseCode == HTTP_PARTIAL) { val accessFile = RandomAccessFile(file, "r") rangeFormatList.forEach { accessFile.seek(it.start) var size = it.size while (true) { if (size >= b.size){ output.write(b,0,accessFile.read(b)) size-=b.size }else{ output.write(b,0,accessFile.read(b,0,size.toInt())) output.flush() break } } } } return true } override fun close() { } /** * # 尝试计算文件ETag * * * * @param file File * @return String */ private fun getFileETag(file: File): String { val absolutePath = file.absolutePath if (!absolutePath.endsWith(".md5") && !absolutePath.endsWith(".sha1")) { val md5File = File("$absolutePath.md5") val sha1File = File("$absolutePath.sha1") if (md5File.isFile) { return getFileETag(md5File) } if (sha1File.isFile) { return getFileETag(sha1File) } } if (file.length() > 8192) { var b = ByteArray(8192) val inputStream = file.inputStream() inputStream.read(b) inputStream.close() val byteArrayOutputStream = ByteArrayOutputStream() byteArrayOutputStream.write(b) byteArrayOutputStream.write(file.lastModified().toString(16).toByteArray()) val crC32 = CalculateUtils.getCRC32(byteArrayOutputStream.toByteArray().inputStream()) byteArrayOutputStream.close() return "$crC32-c" } else { val crC32 = CalculateUtils.getCRC32(file.inputStream()) return "$crC32-c" } } }
1
null
1
2
da67552f6427e31575fed00e7adc8dfeb2f852e0
6,517
JNetServer
MIT License
app/src/main/java/com/mindorks/framework/mvp/ui/main/view/MainActivity.kt
janishar
115,260,052
false
null
package com.mindorks.framework.mvp.ui.main.view import android.content.Intent import android.os.Bundle import android.os.Handler import android.support.design.widget.NavigationView import android.support.v4.app.Fragment import android.support.v4.content.ContextCompat import android.support.v4.view.GravityCompat import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.view.MenuItem import com.mindorks.framework.mvp.R import com.mindorks.framework.mvp.ui.about.view.AboutFragment import com.mindorks.framework.mvp.ui.base.view.BaseActivity import com.mindorks.framework.mvp.ui.feed.view.FeedActivity import com.mindorks.framework.mvp.ui.login.view.LoginActivity import com.mindorks.framework.mvp.ui.main.interactor.MainMVPInteractor import com.mindorks.framework.mvp.ui.main.interactor.QuestionCardData import com.mindorks.framework.mvp.ui.main.presenter.MainMVPPresenter import com.mindorks.framework.mvp.ui.rate.view.RateUsDialog import com.mindorks.framework.mvp.ui.tasks.view.OpenJobsFragment import com.mindorks.framework.mvp.util.ScreenUtils import com.mindorks.framework.mvp.util.extension.addFragment import com.mindorks.framework.mvp.util.extension.removeFragment import com.mindorks.placeholderview.SwipeDecor import dagger.android.DispatchingAndroidInjector import dagger.android.support.HasSupportFragmentInjector import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.nav_header_navigation.view.* import javax.inject.Inject class MainActivity : BaseActivity(), MainMVPView, NavigationView.OnNavigationItemSelectedListener, HasSupportFragmentInjector { @Inject internal lateinit var presenter: MainMVPPresenter<MainMVPView, MainMVPInteractor> @Inject internal lateinit var fragmentDispatchingAndroidInjector: DispatchingAndroidInjector<Fragment> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setUpDrawerMenu() //setupCardContainerView() presenter.onAttach(this) toolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.blue)) supportFragmentManager.addFragment(R.id.container, OpenJobsFragment.newInstance(), OpenJobsFragment.TAG) } override fun onBackPressed() { if (drawerLayout.isDrawerOpen(GravityCompat.START)) { drawerLayout.closeDrawer(GravityCompat.START) } val fragment = supportFragmentManager.findFragmentByTag(AboutFragment.TAG) fragment?.let { onFragmentDetached(AboutFragment.TAG) } ?: super.onBackPressed() } override fun onDestroy() { presenter.onDetach() super.onDestroy() } override fun onFragmentDetached(tag: String) { supportFragmentManager?.removeFragment(tag = tag) unlockDrawer() } override fun onFragmentAttached() { } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.navItemAbout -> { presenter.onDrawerOptionAboutClick() } R.id.navItemRateUs -> { presenter.onDrawerOptionRateUsClick() } R.id.navItemFeed -> { presenter.onDrawerOptionFeedClick() } R.id.navItemLogout -> { presenter.onDrawerOptionLogoutClick() } } drawerLayout.closeDrawer(GravityCompat.START) return true } override fun lockDrawer() = drawerLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED) override fun unlockDrawer() = drawerLayout?.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) override fun displayQuestionCard(questionCards: List<QuestionCardData>) { for (questionCard in questionCards) { //questionHolder.addView(QuestionCard(questionCard)) } } override fun inflateUserDetails(userDetails: Pair<String?, String?>) { } override fun openLoginActivity() { val intent = Intent(this, LoginActivity::class.java) startActivity(intent) finish() } override fun openAboutFragment() { lockDrawer() supportFragmentManager.addFragment(R.id.cl_root_view, AboutFragment.newInstance(), AboutFragment.TAG) } override fun openFeedActivity() { val intent = Intent(this, FeedActivity::class.java) startActivity(intent) } override fun openRateUsDialog() = RateUsDialog.newInstance().let { it?.show(supportFragmentManager) } override fun supportFragmentInjector() = fragmentDispatchingAndroidInjector private fun setUpDrawerMenu() { setSupportActionBar(toolbar) val toggle = ActionBarDrawerToggle( this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) drawerLayout.addDrawerListener(toggle) toggle.syncState() navigation_view.setNavigationItemSelectedListener(this) } // private fun setupCardContainerView() { // val screenWidth = ScreenUtils.getScreenWidth(this) // val screenHeight = ScreenUtils.getScreenHeight(this) // questionHolder.builder // .setDisplayViewCount(3) // .setHeightSwipeDistFactor(10f) // .setWidthSwipeDistFactor(5f) // .setSwipeDecor(SwipeDecor() // .setViewWidth((0.90 * screenWidth).toInt()) // .setViewHeight((0.75 * screenHeight).toInt()) // .setPaddingTop(20) // .setSwipeRotationAngle(10) // .setRelativeScale(0.01f)) // questionHolder.addItemRemoveListener { count -> // if (count == 0) { // Handler(mainLooper).postDelayed({ presenter.refreshQuestionCards() }, 800) // } // } // } }
17
null
199
702
5ac97334d417aff636dd587c82ad97c661c38666
5,993
android-kotlin-mvp-architecture
Apache License 2.0
java/kotlin-extractor/src/main/kotlin/utils/versions/v_1_9_0-Beta/LinesOfCodeLighterAST.kt
github
143,040,428
false
null
package com.github.codeql import com.github.codeql.utils.versions.* import com.intellij.lang.LighterASTNode import com.intellij.util.diff.FlyweightCapableTreeStructure import org.jetbrains.kotlin.KtSourceElement import org.jetbrains.kotlin.fir.backend.FirMetadataSource import org.jetbrains.kotlin.ir.IrElement import org.jetbrains.kotlin.ir.declarations.* import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.util.getChildren class LinesOfCodeLighterAST(val logger: FileLogger, val tw: FileTrapWriter, val file: IrFile) { val fileEntry = file.fileEntry fun linesOfCodeInFile(id: Label<DbFile>): Boolean { val sourceElement = (file.metadata as? FirMetadataSource.File)?.firFile?.source if (sourceElement == null) { return false } linesOfCodeInLighterAST(id, file, sourceElement) // Even if linesOfCodeInLighterAST didn't manage to extract any // information, if we got as far as calling it then we have // LighterAST info for the file return true } fun linesOfCodeInDeclaration(d: IrDeclaration, id: Label<out DbSourceline>): Boolean { val metadata = (d as? IrMetadataSourceOwner)?.metadata val sourceElement = (metadata as? FirMetadataSource)?.fir?.source if (sourceElement == null) { return false } linesOfCodeInLighterAST(id, d, sourceElement) // Even if linesOfCodeInLighterAST didn't manage to extract any // information, if we got as far as calling it then we have // LighterAST info for the declaration return true } private fun linesOfCodeInLighterAST( id: Label<out DbSourceline>, e: IrElement, s: KtSourceElement ) { val rootStartOffset = s.startOffset val rootEndOffset = s.endOffset if (rootStartOffset < 0 || rootEndOffset < 0) { // This is synthetic, or has an invalid location tw.writeNumlines(id, 0, 0, 0) return } val rootFirstLine = fileEntry.getLineNumber(rootStartOffset) val rootLastLine = fileEntry.getLineNumber(rootEndOffset) if (rootLastLine < rootFirstLine) { logger.errorElement("Source element ends before it starts", e) tw.writeNumlines(id, 0, 0, 0) return } val numLines = 1 + rootLastLine - rootFirstLine val lineContents = Array(numLines) { LineContent() } val treeStructure = s.treeStructure processSubtree( e, treeStructure, rootFirstLine, rootLastLine, lineContents, s.lighterASTNode ) val code = lineContents.count { it.containsCode } val comment = lineContents.count { it.containsComment } tw.writeNumlines(id, numLines, code, comment) } private fun processSubtree( e: IrElement, treeStructure: FlyweightCapableTreeStructure<LighterASTNode>, rootFirstLine: Int, rootLastLine: Int, lineContents: Array<LineContent>, node: LighterASTNode ) { if (KtTokens.WHITESPACES.contains(node.tokenType)) { return } val isComment = KtTokens.COMMENTS.contains(node.tokenType) val children = node.getChildren(treeStructure) // Leaf nodes are assumed to be tokens, and // therefore we count any lines that they are on. // For comments, we actually need to look at the // outermost node, as the leaves of KDocs don't // necessarily cover all lines. if (isComment || children.isEmpty()) { val startOffset = node.getStartOffset() val endOffset = node.getEndOffset() if (startOffset < 0 || endOffset < 0) { logger.errorElement("LighterAST node has negative offset", e) return } if (startOffset > endOffset) { logger.errorElement("LighterAST node has negative size", e) return } // This may not be possible with LighterAST, but: // We might get e.g. an import list for a file // with no imports, which claims to have start // and end offsets of 0. Anything of 0 width // we therefore just skip. if (startOffset == endOffset) { return } val firstLine = fileEntry.getLineNumber(startOffset) val lastLine = fileEntry.getLineNumber(endOffset) if (firstLine < rootFirstLine) { logger.errorElement("LighterAST element starts before root", e) return } else if (lastLine > rootLastLine) { logger.errorElement("LighterAST element ends after root", e) return } for (line in firstLine..lastLine) { val lineContent = lineContents[line - rootFirstLine] if (isComment) { lineContent.containsComment = true } else { lineContent.containsCode = true } } } else { for (child in children) { processSubtree(e, treeStructure, rootFirstLine, rootLastLine, lineContents, child) } } } private class LineContent { var containsComment = false var containsCode = false } }
1,149
null
1553
7,510
5108799224a667d9acb2a1a28ff45e680e76e13c
5,512
codeql
MIT License
app/src/main/java/in/dimigo/dimigoin/data/usecase/fcm/FcmUseCaseImpl.kt
dimigo-din
276,088,881
false
{"Kotlin": 156078, "Ruby": 939}
package `in`.dimigo.dimigoin.data.usecase.fcm import `in`.dimigo.dimigoin.data.model.FcmTokenUploadRequestModel import `in`.dimigo.dimigoin.data.service.DimigoinService import `in`.dimigo.dimigoin.data.util.Result import `in`.dimigo.dimigoin.data.util.safeApiCall import retrofit2.await class FcmUseCaseImpl(private val service: DimigoinService) : FcmUseCase { override suspend fun uploadFcmToken(token: String): Result<Unit> { return safeApiCall { service.uploadFcmToken(FcmTokenUploadRequestModel(token)).await() } } override suspend fun deleteFcmToken(token: String): Result<Unit> { return safeApiCall { service.deleteFcmToken(FcmTokenUploadRequestModel(token)).await() } } }
10
Kotlin
1
21
b89dbdb7f5a540d59a0b70bc91fb29eb7d6a9846
754
dimigoin-android
Apache License 2.0
Driver Mobile App/app/src/main/java/in/techware/lataxidriverapp/model/BasicBean.kt
BlondelSeumo
272,554,453
false
{"TSQL": 61756373, "PHP": 2277395, "Java": 2067539, "JavaScript": 103903, "Kotlin": 40327, "CSS": 25122, "HTML": 6107, "Hack": 3473}
package `in`.techware.lataxidriverapp.model /** * Created by <NAME> on 03 December, 2016. * Package in.techware.lataxidriver.model * Project LaTaxi */ open class BasicBean : BaseBean() { /* private ArrayList<CountryBean> countries; private ArrayList<StateBean> states; private ArrayList<DistrictBean> cities; private ArrayList<CourtBean> courts;*/ var requestID: String= "" var tripID: String= "" var tripStatus: Int = 0 var otpCode: String= "" var phone: String= "" var countryID: Int = 0 var stateID: Int = 0 var districtID: Int = 0 var isDriverOnline: Boolean = false var isPhoneAvailable: Boolean = false /* public ArrayList<CourtBean> getCourts() { return courts; } public void setCourts(List<CourtBean> courts) { this.courts = courts; } public ArrayList<CountryBean> getCountries() { return countries; } public void setCountries(List<CountryBean> countries) { this.countries = countries; } public ArrayList<StateBean> getStates() { return states; } public void setStates(List<StateBean> states) { this.states = states; } public ArrayList<DistrictBean> getDistricts() { return cities; } public void setDistricts(List<DistrictBean> cities) { this.cities = cities; }*/ }
0
TSQL
4
1
ba28a9ba6129a502a3f5081d9a999d4b2c2da165
1,380
On-Demand-Taxi-Booking-Application
MIT License
library/kmp-tor-common/src/commonMain/kotlin/io/matthewnelson/kmp/tor/common/address/PortProxy.kt
05nelsonm
456,238,754
false
{"Kotlin": 1053325}
/* * Copyright (c) 2022 <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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ package io.matthewnelson.kmp.tor.common.address import io.matthewnelson.component.parcelize.Parcelize import io.matthewnelson.kmp.tor.common.annotation.ExperimentalTorApi import io.matthewnelson.kmp.tor.common.annotation.SealedValueClass import kotlin.jvm.JvmInline import kotlin.jvm.JvmStatic /** * Holder for a valid proxy port between 1024 and 65535 * * @see [RealPortProxy] * @throws [IllegalArgumentException] if port is not valid * */ @SealedValueClass @OptIn(ExperimentalTorApi::class) sealed interface PortProxy: Port { companion object { const val MIN = 1024 const val MAX = Port.MAX @JvmStatic @Throws(IllegalArgumentException::class) operator fun invoke(port: Int): PortProxy { return RealPortProxy(port) } @JvmStatic fun fromIntOrNull(port: Int?): PortProxy? { return try { RealPortProxy(port ?: return null) } catch (_: IllegalArgumentException) { null } } } } @JvmInline @Parcelize private value class RealPortProxy(override val value: Int): PortProxy { init { require(value in PortProxy.MIN..PortProxy.MAX) { "Invalid port range. Must be between ${PortProxy.MIN} and ${PortProxy.MAX}" } } override fun toString(): String = "PortProxy(value=$value)" }
25
Kotlin
5
33
7888dc90b99b04f8d28f8abe7ccfb7402e2bd1bc
1,979
kmp-tor
Apache License 2.0
rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/actions/internal/DumpUnityExplorerAction.kt
JetBrains
42,181,594
false
null
package com.jetbrains.rider.plugins.unity.actions.internal import com.intellij.ide.util.treeView.AbstractTreeNode import com.intellij.openapi.actionSystem.AnActionEvent import com.jetbrains.rd.platform.internal.DumpAction import com.jetbrains.rider.plugins.unity.explorer.UnityExplorer import java.io.OutputStreamWriter class DumpUnityExplorerAction : DumpAction("Dump Unity Explorer") { override fun actionPerformed(e: AnActionEvent) { val project = e.project ?: return val host = UnityExplorer.getInstance(project) val root = host.model.root dump(project) { writer -> dumpReq(root, 0, writer) } } private fun dumpReq(node: AbstractTreeNode<*>, indent: Int, writer: OutputStreamWriter) { for (m in node.children) { writer.append(" ".repeat(indent)) writer.append(m.name) writer.append(" ") writer.appendLine(m.value.toString()) if (m.children.any()) { if (m is AbstractTreeNode<*>) dumpReq(m,indent + 1, writer) else { writer.appendLine(" unexpected node: $m") } } } } }
284
null
141
1,212
0c8dd88b62259ac3ba4c8c703bd998bf0c67d8cc
1,235
resharper-unity
Apache License 2.0
postannouncement/src/main/java/org/mhacks/app/postannouncement/ui/PostAnnouncementDialogFragment.kt
mhacks
22,456,318
false
null
package org.mhacks.app.postannouncement.ui import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Toast import androidx.lifecycle.Observer import org.mhacks.app.core.ktx.showSnackBar import org.mhacks.app.core.widget.BaseDialogFragment import org.mhacks.app.postannouncement.PostAnnouncementViewModel import org.mhacks.app.postannouncement.R import org.mhacks.app.postannouncement.data.model.PostAnnouncement import org.mhacks.app.postannouncement.databinding.FragmentPostAnnouncementBinding import org.mhacks.app.postannouncement.inject import javax.inject.Inject /** * Fragment used to create and post a new announcement. */ class PostAnnouncementDialogFragment : BaseDialogFragment() { private lateinit var binding: FragmentPostAnnouncementBinding private var isTitleValid = false private var isCategoryValid = false private var isBodyValid = false override var rootView: View? = null @Inject lateinit var postAnnouncementViewModel: PostAnnouncementViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { inject() binding = FragmentPostAnnouncementBinding.inflate( inflater, container, false).apply { dialog?.setTitle(context?.getString(R.string.post_announcement)) val countries = arrayOf( "Food", "Emergency", "Event", "Logistics", "Sponsored") activity?.let { val adapter = ArrayAdapter(it, android.R.layout.simple_dropdown_item_1line, countries) fragmentCreateAnnouncementCategoryEditText.setAdapter(adapter) } fragmentCreateAnnouncementCategoryEditText.keyListener = null fragmentCreateAnnouncementCategoryEditText.setOnFocusChangeListener { _, _ -> showDropDown() } fragmentCreateAnnouncementCategoryEditText.setOnClickListener { showDropDown() } fragmentCreateAnnouncementTitleEditText.addTextChangedListener( object : TextWatcher { override fun afterTextChanged(p0: Editable?) { isTitleValid = !p0.toString().isEmpty() validate() } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) fragmentCreateAnnouncementBodyEditText.addTextChangedListener( object : TextWatcher { override fun afterTextChanged(p0: Editable?) { isBodyValid = p0.toString().isNotEmpty() validate() } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) fragmentCreateAnnouncementCategoryEditText.setOnItemClickListener { _, _, _, _ -> isCategoryValid = true validate() } subscribeUi(postAnnouncementViewModel) fragmentCreateAnnouncementPostButton.setOnClickListener { postAnnouncementViewModel.postAnnouncement( PostAnnouncement( fragmentCreateAnnouncementTitleEditText.text.toString().trim(), fragmentCreateAnnouncementBodyEditText.text .toString().trim(), fragmentCreateAnnouncementCategoryEditText.text .toString().toLowerCase().trim(), true, isSent = true, push = true ) ) } rootView = root } return super.onCreateView(inflater, container, savedInstanceState) } private fun subscribeUi(postAnnouncementViewModel: PostAnnouncementViewModel) { postAnnouncementViewModel.createAnnouncement.observe(this, Observer { Toast.makeText( context, R.string.post_announcement_success, Toast.LENGTH_LONG) .show() dismiss() }) postAnnouncementViewModel.text.observe(this, Observer { binding.root.showSnackBar(it) }) } private fun validate() { binding.fragmentCreateAnnouncementPostButton.isEnabled = isTitleValid and isCategoryValid and isBodyValid } private fun showDropDown() { binding.fragmentCreateAnnouncementCategoryEditText.showDropDown() } }
1
null
12
21
12309b463e51acc3f41c463df647f410e16a6261
5,228
mhacks-android
MIT License
onebusaway-sdk-java-core/src/main/kotlin/org/onebusaway/services/async/CurrentTimeServiceAsync.kt
OneBusAway
864,202,238
false
{"Kotlin": 1800021, "Java": 32530, "Shell": 3662, "Dockerfile": 399}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package org.onebusaway.services.async import java.util.concurrent.CompletableFuture import org.onebusaway.core.RequestOptions import org.onebusaway.models.CurrentTimeRetrieveParams import org.onebusaway.models.CurrentTimeRetrieveResponse interface CurrentTimeServiceAsync { /** current-time */ @JvmOverloads fun retrieve( params: CurrentTimeRetrieveParams, requestOptions: RequestOptions = RequestOptions.none() ): CompletableFuture<CurrentTimeRetrieveResponse> }
0
Kotlin
0
1
53b9dc885b925f3dc94410ade095e2cf5e733fe7
646
java-sdk
Apache License 2.0
src/main/kotlin/mathlingua/frontend/chalktalk/phase2/ast/group/clause/existsUnique/ExistsUniqueSection.kt
DominicKramer
203,428,613
false
null
/* * Copyright 2020 The MathLingua Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mathlingua.frontend.chalktalk.phase2.ast.group.clause.exists import mathlingua.frontend.chalktalk.phase1.ast.Phase1Node import mathlingua.frontend.chalktalk.phase2.CodeWriter import mathlingua.frontend.chalktalk.phase2.ast.DEFAULT_EXISTS_SECTION import mathlingua.frontend.chalktalk.phase2.ast.clause.Target import mathlingua.frontend.chalktalk.phase2.ast.common.Phase2Node import mathlingua.frontend.chalktalk.phase2.ast.section.appendTargetArgs import mathlingua.frontend.chalktalk.phase2.ast.track import mathlingua.frontend.chalktalk.phase2.ast.validateTargetSection import mathlingua.frontend.support.MutableLocationTracker import mathlingua.frontend.support.ParseError internal data class ExistsSection(val identifiers: List<Target>) : Phase2Node { override fun forEach(fn: (node: Phase2Node) -> Unit) = identifiers.forEach(fn) override fun toCode(isArg: Boolean, indent: Int, writer: CodeWriter): CodeWriter { writer.writeIndent(isArg, indent) writer.writeHeader("exists") appendTargetArgs(writer, identifiers, indent + 2) return writer } override fun transform(chalkTransformer: (node: Phase2Node) -> Phase2Node) = chalkTransformer( ExistsSection( identifiers = identifiers.map { it.transform(chalkTransformer) as Target })) } internal fun validateExistsSection( node: Phase1Node, errors: MutableList<ParseError>, tracker: MutableLocationTracker ) = track(node, tracker) { validateTargetSection( node.resolve(), errors, "exists", DEFAULT_EXISTS_SECTION, tracker, ::ExistsSection) }
4
Kotlin
0
67
c264bc61ac7d9e520018f2652b110c4829876c82
2,227
mathlingua
Apache License 2.0
android/src/main/kotlin/net/niuxiaoer/flutter_gromore/manager/FlutterGromoreRewardCache.kt
50431040
496,944,700
false
null
package net.niuxiaoer.flutter_gromore.manager import com.bytedance.sdk.openadsdk.TTRewardVideoAd class FlutterGromoreRewardCache { companion object { /// 缓存插屏广告 private var cacheAd: MutableMap<Int, TTRewardVideoAd> = mutableMapOf() /// 添加缓存插屏广告 fun addCacheAd(id: Int, ad: TTRewardVideoAd) { cacheAd[id] = ad } /// 获取缓存插屏广告 fun getCacheAd(id: Int): TTRewardVideoAd? { return cacheAd[id] } /// 移除缓存插屏广告 fun removeCacheAd(id: Int) { cacheAd.remove(id) } } }
1
Kotlin
2
6
e2cd2bf1acf8c901758791184ae8a759ad5570ab
592
flutter_gromore
MIT License
tools/plugins/virtual-node/src/main/kotlin/net/corda/cli/plugins/vnode/commands/PlatformMigration.kt
corda
346,070,752
false
null
package net.corda.cli.plugins.vnode.commands import liquibase.Contexts import liquibase.Liquibase import liquibase.database.Database import liquibase.database.DatabaseFactory import liquibase.database.jvm.JdbcConnection import liquibase.resource.ClassLoaderResourceAccessor import net.corda.cli.plugins.vnode.withPluginClassLoader import picocli.CommandLine import java.io.File import java.io.FileWriter import java.sql.Connection import java.sql.DriverManager @CommandLine.Command( name = "platform-migration", description = ["Generates SQL commands to perform database schema migration of virtual nodes from one version of " + "Corda Platform Liquibase files to the next."] ) class PlatformMigration(private val config: PlatformMigrationConfig = PlatformMigrationConfig()) : Runnable { @CommandLine.Option( names = ["--jdbc-url"], description = ["JDBC Url of virtual node database/schema. Read access is required for Liquibase tracking tables " + "to determine what the current version of platform schemas each virtual node is currently at."] ) var jdbcUrl: String? = null @CommandLine.Option( names = ["-u", "--user"], description = ["Database username"] ) var user: String? = null @CommandLine.Option( names = ["-p", "--password"], description = ["Database password. Defaults to no password."] ) var password: String = "" @CommandLine.Option( names = ["-o", "--output-filename"], description = ["SQL output file. Default is '$SQL_FILENAME'"] ) var outputFilename: String = SQL_FILENAME @CommandLine.Option( names = ["-i", "--input-filename"], description = ["File containing list of Virtual Node Short Holding Ids to migrate. File should contain one short" + "holding Id per line and nothing else. Default is '$HOLDING_ID_FILENAME'"] ) var holdingIdFilename: String = HOLDING_ID_FILENAME companion object { private const val HOLDING_ID_FILENAME = "./holdingIds" private const val SQL_FILENAME = "./vnodes.sql" } /** * Lazy because we don't want the list generated until run() is called, to ensure all the parameters are set */ private val holdingIdsToMigrate: List<String> by lazy { mutableListOf<String>().apply { // Regex checks holdingId matches expected format and is one per line val regex = Regex("^[a-f0-9]{12}\$") config.lineReader(holdingIdFilename) { if (regex.matches(it)) { add(it) } else if (it.isNotEmpty()) { // allow and ignore empty lines throw IllegalArgumentException("Found invalid holding Id: $it") } } } } private data class LiquibaseFileAndSchema(val filename: String, val schemaPrefix: String) data class PlatformMigrationConfig( val writerFactory: (String) -> FileWriter = { file -> FileWriter(File(file)) }, val lineReader: (String, (String) -> Unit) -> Unit = { filename, block -> File(filename).forEachLine { block(it) } }, val liquibaseFactory: (String, Database) -> Liquibase = { file: String, database: Database -> Liquibase(file, ClassLoaderResourceAccessor(), database) }, val jdbcConnectionFactory: (String?, String?, String?) -> Connection = { jdbcUrl, user, password -> DriverManager.getConnection(jdbcUrl, user, password) }, val jdbcDatabaseFactory: (Connection) -> Database = { connection -> DatabaseFactory.getInstance().findCorrectDatabaseImplementation(JdbcConnection(connection)) } ) override fun run() { config.writerFactory(outputFilename).use { fileWriter -> listOf( LiquibaseFileAndSchema("net/corda/db/schema/vnode-crypto/db.changelog-master.xml", "vnode_crypto_"), LiquibaseFileAndSchema("net/corda/db/schema/vnode-uniqueness/db.changelog-master.xml", "vnode_uniq_"), LiquibaseFileAndSchema("net/corda/db/schema/vnode-vault/db.changelog-master.xml", "vnode_vault_") ).forEach { fileAndSchema -> holdingIdsToMigrate.forEach { holdingId -> generateSql(fileWriter, holdingId, fileAndSchema) } } } } private fun generateSql(fileWriter: FileWriter, holdingId: String, fileAndSchema: LiquibaseFileAndSchema) { withPluginClassLoader { val connection = config.jdbcConnectionFactory(jdbcUrl, user, password) val database = config.jdbcDatabaseFactory(connection).apply { val schemaName = fileAndSchema.schemaPrefix + holdingId defaultSchemaName = schemaName // our tables liquibaseSchemaName = schemaName // liquibase tracking tables } connection.use { config.liquibaseFactory(fileAndSchema.filename, database).update(Contexts(), fileWriter) } } } }
32
null
25
58
15a1ccc52cfc6b2edd6a306760f693f59e7aca20
5,136
corda-runtime-os
Apache License 2.0
app/src/main/java/com/ignitetech/compose/data/chat/ChatWithSender.kt
gnumilanix
602,430,902
false
null
package com.ignitetech.compose.data.chat import androidx.room.Embedded import androidx.room.Relation import com.ignitetech.compose.data.user.User data class ChatWithSender( @Embedded val chat: Chat, @Relation( parentColumn = Chat.FIELD_USER_ID, entityColumn = User.FIELD_ID ) val sender: User )
3
Kotlin
1
0
7a7fc31e7013e91ae78947af6bca1d97fb1140ed
334
explore-compose
Apache License 2.0
src/main/kotlin/com/team4099/robot2023/subsystems/vision/VisionIO.kt
team4099
560,942,123
false
null
package com.team4099.robot2023.subsystems.vision import org.littletonrobotics.junction.LogTable import org.littletonrobotics.junction.inputs.LoggableInputs interface VisionIO { class VisionInputs : LoggableInputs { override fun fromLog(table: LogTable?) { TODO("Not yet implemented") } override fun toLog(table: LogTable?) { TODO("Not yet implemented") } } fun updateInputs(inputs: VisionInputs) {} }
4
Kotlin
2
7
382bd764bd3c50ad60eb615757072daaa52ab704
439
ChargedUp-2023
MIT License
mvicore-demo/mvicore-demo-app/src/main/java/com/badoo/mvicoredemo/ui/main/viewmodel/ViewModel.kt
emreakcan
287,947,555
true
{"Gradle": 15, "Java Properties": 2, "Shell": 3, "Text": 1, "Ignore List": 13, "Batchfile": 1, "YAML": 2, "Markdown": 31, "Kotlin": 130, "XML": 31, "Proguard": 6, "Java": 5}
package com.badoo.mvicoredemo.ui.main.viewmodel data class ViewModel( val buttonColors: List<Int>, val counter: Int, val imageUrl: String?, val imageIsLoading: Boolean )
0
Kotlin
0
2
b381a0c3684afca743a39808fbc8a2e37a722375
187
MVICore
Apache License 2.0
src/main/kotlin/dev/paulshields/aoc/Day1.kt
Pkshields
433,609,825
false
{"Kotlin": 133840}
/** * Day 1: Sonar Sweep */ package dev.paulshields.aoc import dev.paulshields.aoc.common.readFileAsStringList fun main() { println(" ** Day 1: Sonar Sweep ** \n") val depths = readFileAsStringList("/Day1Depths.txt").mapNotNull { it.toIntOrNull() } val numDepthIncreases = countNumberOfDepthIncreases(depths) println("There are $numDepthIncreases depth measurements that are larger than the previous measurement.") val slidingWindowNumDepthIncreases = countNumberOfDepthIncreasesUsingSlidingWindow(depths) println("Using a 3-measurement sliding window, there are $slidingWindowNumDepthIncreases depths that are larger than the previous.") } fun countNumberOfDepthIncreases(depths: List<Int>) = depths.zipWithNext().count { it.second > it.first } fun countNumberOfDepthIncreasesUsingSlidingWindow(depths: List<Int>) = depths.windowed(3) .map { it.sum() } .zipWithNext() .count { it.second > it.first }
0
Kotlin
0
0
e3533f62e164ad72ec18248487fe9e44ab3cbfc2
967
AdventOfCode2021
MIT License
src/main/kotlin/com/turbomates/kotlin/lsports/sdk/listener/message/EventsMessage.kt
turbomates
447,160,415
false
{"Kotlin": 79957}
package com.turbomates.kotlin.lsports.sdk.listener.message import com.turbomates.kotlin.lsports.sdk.model.Event interface EventsMessage : Message { val body: Body interface Body { val events: List<Event> } }
1
Kotlin
0
2
f49520e8922912d8e0e336b58e1af9da6194ac73
231
lsports-sdk-kotlin
MIT License
src/main/kotlin/org/exampleapps/greatbig/domain/inout/Comment.kt
evangryska94
113,926,900
false
{"YAML": 14, "JSON with Comments": 3, "Batchfile": 1, "JSON": 190, "JavaScript": 13, "Shell": 1, "Maven POM": 1, "Procfile": 1, "Text": 2, "Ignore List": 2, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 18, "INI": 2, "Java": 160, "XML": 24, "HTML": 189, "Scala": 24, "robots.txt": 1, "SCSS": 107, "CSS": 14, "SVG": 69, "Java Properties": 7, "Dockerfile": 1, "Kotlin": 39, "Pug": 3, "CoffeeScript": 1}
package org.exampleapps.greatbig.domain.inout import com.fasterxml.jackson.annotation.JsonRootName import org.exampleapps.greatbig.domain.Author import java.time.OffsetDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter @JsonRootName("comment") data class Comment(val createdAt: String, val updatedAt: String, val body: String, val author: Profile, val id: Long) { companion object { fun dateFormat(date: OffsetDateTime): String { return date.toZonedDateTime().withZoneSameInstant(ZoneId.of("Z")).format(DateTimeFormatter.ISO_ZONED_DATE_TIME) } fun fromModel(model: org.exampleapps.greatbig.domain.Comment, currentAuthor: Author): Comment { return Comment( id = model.id, body = model.body, createdAt = dateFormat(model.createdAt), updatedAt = dateFormat(model.updatedAt), author = Profile.fromAuthor(model.author, currentAuthor) ) } } }
1
null
1
1
5436f905da7e1b0fa5756288beaabf931855e7d4
1,116
great-big-example-application
MIT License
app/src/main/java/org/yameida/worktool/activity/AccessibilityGuideActivity.kt
gallonyin
473,181,796
false
null
package com.functorz.worktool.activity import android.content.Intent import android.os.Bundle import android.provider.Settings import android.view.View import android.view.animation.AlphaAnimation import android.view.animation.Animation import androidx.appcompat.app.AppCompatActivity import com.blankj.utilcode.util.LogUtils import com.blankj.utilcode.util.SPUtils import kotlinx.android.synthetic.main.activity_accessibility_guide.* import com.functorz.worktool.R import com.functorz.worktool.utils.PermissionHelper /** * Created by gallon on 2019/7/20. * 提示开启无障碍服务权限 */ class AccessibilityGuideActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_accessibility_guide) window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION tv_float_allow.setOnClickListener { try { if (!PermissionHelper.isAccessibilitySettingOn()) { val intent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) startActivity(intent) } } catch (t: Throwable) {} } tv_float_reject.setOnClickListener { finish() } cb_guide_not.isChecked = SPUtils.getInstance().getBoolean("not_show_accessibility_guide", false) cb_guide_not.setOnCheckedChangeListener { buttonView, isChecked -> SPUtils.getInstance().put("not_show_accessibility_guide", isChecked) } val alphaAnimation = AlphaAnimation(0.2F, 1F).apply { duration = 800 repeatCount = Animation.INFINITE repeatMode = Animation.REVERSE } iv_over_finger.startAnimation(alphaAnimation) } override fun onResume() { super.onResume() val accessibilitySettingOn = PermissionHelper.isAccessibilitySettingOn() LogUtils.d("PermissionHelper.isAccessibilitySettingOn: $accessibilitySettingOn") if (accessibilitySettingOn) { finish() } } }
1
Kotlin
118
643
12eda85c122129cef74cd53d2ce5ca8f95af4422
2,368
worktool
Apache License 2.0
android/src/main/kotlin/com/ekodemy/eko_payu/PaymentData.kt
ShubhamJuIT
340,315,766
false
null
package com.ekodemy.eko_payu class PaymentData { var merchantName: String = "Eko"; var merchantKey: String? = null var merchantID: String? = null var isProduction: Boolean? = false var amount: String? = null; var txnId: String? = null; var userCredential: String? = null; var phoneNumber: String? = null; var productName: String? = null; var firstName: String? = null; var emailId: String? = null; var sUrl: String = "https://payuresponse.firebaseapp.com/success"; var fUrl: String = "https://payuresponse.firebaseapp.com/failure"; var udf1: String = ""; var udf2: String = ""; var udf3: String = ""; var udf4: String = ""; var udf5: String = ""; var udf6: String = ""; var udf7: String = ""; var udf8: String = ""; var udf9: String = ""; var udf10: String = ""; var hash: String? = null; var paymentSdkHash: String? = null; var vasSdkHash: String? = null; }
0
Kotlin
0
0
193bc75222a19faac8209cfff017b66fe4dde00b
965
eko_payu
MIT License
test/i_introduction/_7_Data_Classes/_07_Data_Classes.kt
grmaciel
44,112,142
true
{"XML": 13, "Ignore List": 1, "Text": 1, "Markdown": 1, "Kotlin": 109, "Java": 10}
package i_introduction._7_Data_Classes import kotlin.test.* import org.junit.Test as test import org.junit.Assert public class _07_Data_Classes { @test fun testDelight() { Assert.assertTrue(task7()) } }
1
Kotlin
1
1
bdfb637b99cb4787f05b05f6db604364b1cb3c0f
221
workshop-jb
MIT License
app/src/main/java/ru/maxim/unsplash/ui/login/LoginFragment.kt
maximborodkin
406,747,572
false
{"Kotlin": 242939}
package ru.maxim.unsplash.ui.login import android.app.Activity import android.os.Bundle import android.view.View import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import by.kirich1409.viewbindingdelegate.viewBinding import kotlinx.coroutines.flow.collect import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationResponse import org.koin.androidx.viewmodel.ext.android.viewModel import ru.maxim.unsplash.R import ru.maxim.unsplash.databinding.FragmentLoginBinding import ru.maxim.unsplash.ui.login.LoginViewModel.LoginState.* class LoginFragment : Fragment(R.layout.fragment_login) { private val binding: FragmentLoginBinding by viewBinding(FragmentLoginBinding::bind) private val model: LoginViewModel by viewModel() private val authActivityResult = registerForActivityResult(StartActivityForResult()) { result -> val resultData = result.data if (result.resultCode == Activity.RESULT_OK && resultData != null) { val tokenRequest = AuthorizationResponse.fromIntent(resultData)?.createTokenExchangeRequest() if (tokenRequest == null) { AuthorizationException.fromIntent(resultData)?.let { model::onAuthFailed } } else { model.onTokenRequestReceived(tokenRequest) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) with(binding) { lifecycleOwner = viewLifecycleOwner loginBtn.setOnClickListener { model.startLoginPage() } message = getString(R.string.login_page_start_message) // Initial message } viewLifecycleOwner.lifecycleScope.launchWhenStarted { model.loginState.collect { state -> when(state) { is Empty -> { model.startLoginPage() } is Error -> { binding.message = state.message } is Process -> { authActivityResult.launch(state.loginIntent) } is Success -> { findNavController().navigate(LoginFragmentDirections.actionLoginToMain()) } } } } } override fun onDestroyView() { super.onDestroyView() authActivityResult.unregister() } }
0
Kotlin
0
2
06a7d3fb24badae12d42d1a6c45666434ec34d73
2,539
kts-android-unsplash
MIT License
Seção 13 - Orientação a Objetos/Construtor.kt
nunes1909
347,762,017
false
null
package Classes // O construtor natural da classe Pessoa4 é "(var nome: String, var anoNascimento: Int)" class Pessoa4(var nome: String) { // declarando a variavel dentro da classe para possibilitar o uso na função "saudacao()" // ela espera um retorno, basta colocar nulo que quando a pessoa nao possuir "ano", o sistema imprime "nulo" var ano: Int? = null // definindo o construtor secundário // o construtor secundário sempre exige que o construtor primario seja chamado constructor(nome: String, ano: Int) : this(nome) { /* Apenas criando a variavel "ano" ainda não possibilita o uso dela * Deve-se informar ao Kotlin que a variavel "ano nula" recebe a variavel "ano do construtor" * Isso se faz através do "this" */ // this ano se refere a variável nula // = ano é a variável do construtor this.ano = ano } // não é possível chamar a variavel ano, somente se declarar ela dentro da Classe fun saudacao() { if (ano == null){ println("Olá, meu nome é $nome") }else { println("Olá, meu nome é $nome, e nasci em $ano") } } } fun main() { val p2: Pessoa4 = Pessoa4("João") val p1: Pessoa4 = Pessoa4("Gabriel", 1997) p1.saudacao() p2.saudacao() }
0
Kotlin
0
1
9fcbf199ddf400be030d71b83ba3fc7f41427d3a
1,320
Kotlin
MIT License
bugsnag-android-core/src/main/java/com/bugsnag/android/LastRunInfoStore.kt
bugsnag
2,406,783
false
null
package com.bugsnag.android import com.bugsnag.android.internal.ImmutableConfig import java.io.File import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.withLock private const val KEY_VALUE_DELIMITER = "=" private const val KEY_CONSECUTIVE_LAUNCH_CRASHES = "consecutiveLaunchCrashes" private const val KEY_CRASHED = "crashed" private const val KEY_CRASHED_DURING_LAUNCH = "crashedDuringLaunch" /** * Persists/loads [LastRunInfo] on disk, which allows Bugsnag to determine * whether the previous application launch crashed or not. This class is thread-safe. */ internal class LastRunInfoStore(config: ImmutableConfig) { val file: File = File(config.persistenceDirectory, "last-run-info") private val logger: Logger = config.logger private val lock = ReentrantReadWriteLock() fun persist(lastRunInfo: LastRunInfo) { lock.writeLock().withLock { try { persistImpl(lastRunInfo) } catch (exc: Throwable) { logger.w("Unexpectedly failed to persist LastRunInfo.", exc) } } } private fun persistImpl(lastRunInfo: LastRunInfo) { val text = KeyValueWriter().apply { add(KEY_CONSECUTIVE_LAUNCH_CRASHES, lastRunInfo.consecutiveLaunchCrashes) add(KEY_CRASHED, lastRunInfo.crashed) add(KEY_CRASHED_DURING_LAUNCH, lastRunInfo.crashedDuringLaunch) }.toString() file.writeText(text) logger.d("Persisted: $text") } fun load(): LastRunInfo? { return lock.readLock().withLock { try { loadImpl() } catch (exc: Throwable) { logger.w("Unexpectedly failed to load LastRunInfo.", exc) null } } } private fun loadImpl(): LastRunInfo? { if (!file.exists()) { return null } val lines = file.readText().split("\n").filter { it.isNotBlank() } if (lines.size != 3) { logger.w("Unexpected number of lines when loading LastRunInfo. Skipping load. $lines") return null } return try { val consecutiveLaunchCrashes = lines[0].asIntValue(KEY_CONSECUTIVE_LAUNCH_CRASHES) val crashed = lines[1].asBooleanValue(KEY_CRASHED) val crashedDuringLaunch = lines[2].asBooleanValue(KEY_CRASHED_DURING_LAUNCH) val runInfo = LastRunInfo(consecutiveLaunchCrashes, crashed, crashedDuringLaunch) logger.d("Loaded: $runInfo") runInfo } catch (exc: NumberFormatException) { // unlikely case where information was serialized incorrectly logger.w("Failed to read consecutiveLaunchCrashes from saved lastRunInfo", exc) null } } private fun String.asIntValue(key: String) = substringAfter("$key$KEY_VALUE_DELIMITER").toInt() private fun String.asBooleanValue(key: String) = substringAfter("$key$KEY_VALUE_DELIMITER").toBoolean() } private class KeyValueWriter { private val sb = StringBuilder() fun add(key: String, value: Any) { sb.appendln("$key$KEY_VALUE_DELIMITER$value") } override fun toString() = sb.toString() }
22
null
205
1,188
8074d55eae773563fc97e91161b56089bf329107
3,261
bugsnag-android
MIT License
src/main/kotlin/no/nav/k9brukerdialogapi/ytelse/pleiepengerlivetssluttfase/PleiepengerLivetsSluttfaseApi.kt
navikt
460,765,798
false
{"Kotlin": 833953, "Dockerfile": 103}
package no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase import io.ktor.http.HttpStatusCode import io.ktor.server.application.call import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.Route import io.ktor.server.routing.post import io.ktor.server.routing.route import no.nav.helse.dusseldorf.ktor.auth.IdTokenProvider import no.nav.k9brukerdialogapi.INNSENDING_URL import no.nav.k9brukerdialogapi.PLEIEPENGER_LIVETS_SLUTTFASE_URL import no.nav.k9brukerdialogapi.general.formaterStatuslogging import no.nav.k9brukerdialogapi.general.getCallId import no.nav.k9brukerdialogapi.innsending.InnsendingCache import no.nav.k9brukerdialogapi.innsending.InnsendingService import no.nav.k9brukerdialogapi.kafka.getMetadata import no.nav.k9brukerdialogapi.ytelse.pleiepengerlivetssluttfase.domene.PilsSøknad import no.nav.k9brukerdialogapi.ytelse.registrerMottattSøknad import no.nav.k9brukerdialogapi.ytelse.ytelseFraHeader import org.slf4j.Logger import org.slf4j.LoggerFactory fun Route.pleiepengerLivetsSluttfaseApi( innsendingService: InnsendingService, innsendingCache: InnsendingCache, idTokenProvider: IdTokenProvider, ){ val logger: Logger = LoggerFactory.getLogger("ytelse.pleiepengerlivetssluttfase.pleiepengerLivetsSluttfaseApi.kt") route(PLEIEPENGER_LIVETS_SLUTTFASE_URL){ post(INNSENDING_URL){ val pilsSøknad = call.receive<PilsSøknad>() val idToken = idTokenProvider.getIdToken(call) val cacheKey = "${idToken.getNorskIdentifikasjonsnummer()}_${pilsSøknad.ytelse()}" val ytelse = call.ytelseFraHeader() logger.info(formaterStatuslogging(pilsSøknad.ytelse(), pilsSøknad.søknadId, "mottatt.")) innsendingCache.put(cacheKey) innsendingService.registrer(pilsSøknad, call.getCallId(), idToken, call.getMetadata(), ytelse) registrerMottattSøknad(pilsSøknad.ytelse()) call.respond(HttpStatusCode.Accepted) } } }
1
Kotlin
0
0
8648aea9614a3568c12d2bce246a14d9e1ebd890
2,024
k9-brukerdialog-api
MIT License
features/schedule/src/main/java/dev/ryzhoov/napomnix/schedule/ui/list/items/Item.kt
v1aditech
581,266,106
false
{"Kotlin": 161157}
package dev.ryzhoov.napomnix.schedule.ui.list.items internal interface Item { val id: Long }
0
Kotlin
0
0
5b0fc12bf74f19f765d99d5671b0f599bebd17a9
97
napomnix
Apache License 2.0
api/unsplash/src/main/kotlin/com/espressodev/gptmap/api/unsplash/impl/UnsplashServiceImpl.kt
f-arslan
714,072,263
false
{"Kotlin": 312117, "Dockerfile": 852}
package com.espressodev.gptmap.api.unsplash.impl import android.util.Log import com.espressodev.gptmap.api.unsplash.UnsplashApi import com.espressodev.gptmap.api.unsplash.UnsplashService import com.espressodev.gptmap.core.model.unsplash.LocationImage import com.espressodev.gptmap.core.model.ext.classTag import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class UnsplashServiceImpl(private val unsplashApi: UnsplashApi) : UnsplashService { override suspend fun getTwoPhotos(query: String): Result<List<LocationImage>> = withContext(Dispatchers.IO) { val response = unsplashApi.getTwoPhotos(query) response.isSuccessful.let { success -> when { success -> { Log.d(classTag(), unsplashApi.getTwoPhotos(query).body().toString()) response.body()?.let { Result.success(it) } ?: Result.failure(Throwable(UnsplashApiException())) } else -> { Result.failure(Throwable(UnsplashApiException())) } } } } companion object { class UnsplashApiException : Exception() } }
0
Kotlin
0
2
dcc8c8c7a2d40a19e08dd7c4f1c56c7d18e59518
1,291
GptMap
MIT License
app/src/main/java/com/vasu/appcenter/akshay/adshelper/AdMobAdsUtils.kt
vickypathak123
381,272,556
false
{"Java": 1025225, "Kotlin": 539421, "Assembly": 18}
@file:Suppress("unused") package com.vasu.appcenter.akshay.adshelper import android.app.Activity import android.content.Context import android.os.Build import android.view.LayoutInflater import android.view.View import android.view.WindowInsets import android.view.WindowInsetsController import androidx.annotation.StringRes import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.MobileAds import com.google.android.gms.ads.RequestConfiguration var isInterstitialAdShow = false /** * Extension method to Get String resource for Context. */ internal fun Context.getStringRes(@StringRes id: Int) = resources.getString(id) /** * Extension method to get LayoutInflater */ internal inline val Context.inflater: LayoutInflater get() = LayoutInflater.from(this) /** * Show the view (visibility = View.VISIBLE) */ internal inline val View.visible: View get() { if (visibility != View.VISIBLE) { visibility = View.VISIBLE } return this } /** * Hide the view. (visibility = View.INVISIBLE) */ internal inline val View.invisible: View get() { if (visibility != View.INVISIBLE) { visibility = View.INVISIBLE } return this } /** * Remove the view (visibility = View.GONE) */ internal inline val View.gone: View get() { if (visibility != View.GONE) { visibility = View.GONE } return this } /** * Extension method for add AdMob Ads test devise id's * * Find This Log in your logcat for get your devise test id * I/Ads: Use RequestConfiguration.Builder.setTestDeviceIds(Arrays.asList("33BE2250B43518CCDA7DE426D04EE231")) */ fun setTestDeviceIds() { val lTestDeviceIds = listOf( AdRequest.DEVICE_ID_EMULATOR, ) val lConfiguration = RequestConfiguration.Builder().setTestDeviceIds(lTestDeviceIds).build() MobileAds.setRequestConfiguration(lConfiguration) } /** * Extension method for add different size of Native Ad */ enum class NativeAdsSize { Big, Medium, Small, ExitDialog, BlurImageDialog } fun Activity.hideStatusBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.insetsController?.let { it.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE it.hide(WindowInsets.Type.statusBars()) } } else { @Suppress("DEPRECATION") window.decorView.systemUiVisibility = ( View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN) } } fun Activity.showStatusBar() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { window.setDecorFitsSystemWindows(false) window.insetsController?.show(WindowInsets.Type.statusBars()) } else { @Suppress("DEPRECATION") window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE) } }
1
Java
1
2
73f9feea0fa77c9df2e6275eec837ae15e07f2be
3,031
VasundharaCommonCode
MIT License
app/src/main/java/org/simple/clinic/analytics/Analytics.kt
pratul
151,071,054
false
null
package org.simple.clinic.analytics import java.util.UUID object Analytics { private var reporters: List<Reporter> = emptyList() fun addReporter(vararg reportersToAdd: Reporter) { reporters += reportersToAdd } fun clearReporters() { reporters = emptyList() } fun removeReporter(reporter: Reporter) { reporters -= reporter } fun setUserId(uuid: UUID) { reporters.forEach { it.safely("Error setting user ID!") { val uuidString = uuid.toString() setUserIdentity(uuidString) setProperty("userId", uuidString) } } } fun reportUserInteraction(name: String) { reporters.forEach { it.safely("Error reporting interaction!") { createEvent("UserInteraction", mapOf("name" to name)) } } } fun reportScreenChange(outgoingScreen: String, incomingScreen: String) { reporters.forEach { it.safely("Error reporting screen change!") { createEvent("ScreenChange", mapOf("outgoing" to outgoingScreen, "incoming" to incomingScreen)) } } } fun reportInputValidationError(error: String) { reporters.forEach { it.safely("Error reporting input validation!") { createEvent("InputValidationError", mapOf("name" to error)) } } } fun reportViewedPatient(patientUuid: UUID, from: String) { reporters.forEach { it.safely("Error reporting viewed patient event!") { createEvent("ViewedPatient", mapOf("patientId" to patientUuid.toString(), "from" to from)) } } } fun reportNetworkCall(url: String, method: String, responseCode: Int, contentLength: Int, durationMillis: Int) { reporters.forEach { it.safely("Error reporting network call") { createEvent("NetworkCall", mapOf( "url" to url, "method" to method, "responseCode" to responseCode, "contentLength" to contentLength, "durationMs" to durationMillis )) } } } }
0
null
1
1
fa311d989cac0a167070f2e1e466191919b659b8
1,997
citest
MIT License
app/src/main/java/cherryjam/narfu/arkhdialect/ui/CardEditActivity.kt
ACherryJam
799,249,888
false
{"Kotlin": 97862}
package cherryjam.narfu.arkhdialect.ui import android.os.Build import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import cherryjam.narfu.arkhdialect.data.AppDatabase import cherryjam.narfu.arkhdialect.data.entity.Card import cherryjam.narfu.arkhdialect.databinding.ActivityCardEditBinding class CardEditActivity : AppCompatActivity() { private val binding: ActivityCardEditBinding by lazy { ActivityCardEditBinding.inflate(layoutInflater) } lateinit var card: Card private val database by lazy { AppDatabase.getInstance(this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) card = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { intent.getParcelableExtra("card", Card::class.java) } else { intent.getParcelableExtra("card") } ?: throw IllegalArgumentException("No Card entity passed to CardEditActivity") with(binding) { word.setText(card.word) location.setText(card.location) characteristics.setText(card.characteristics) meaning.setText(card.meaning) example.setText(card.example) } binding.undo.setOnClickListener { finish() } binding.save.setOnClickListener { Thread { card.word = binding.word.text.toString() card.location = binding.location.text.toString() card.characteristics = binding.characteristics.text.toString() card.meaning = binding.meaning.text.toString() card.example = binding.example.text.toString() database.cardDao().update(card) finish() }.start() } } override fun onSupportNavigateUp(): Boolean { onBackPressedDispatcher.onBackPressed() return true } }
0
Kotlin
0
1
e940d28fed814e2d7320fdcb9a4a006f96e6afa5
2,130
arkhdialect
MIT License
lib/src/main/java/io/vproxy/lib/http/RoutingContext.kt
wkgcass
166,255,932
false
null
package io.vproxy.lib.http import vjson.JSON import io.vproxy.lib.http.route.SubPath import io.vproxy.lib.http.route.WildcardSubPath @Suppress("unused") interface StorageKey<T> interface HttpServerConnection { fun base(): io.vproxy.base.connection.Connection fun response(status: Int): HttpServerResponse } interface HttpHeaders { fun get(name: String): String? } interface HttpServerRequest { fun method(): String fun uri(): String fun query(): Map<String, String> fun headers(): HttpHeaders fun body(): io.vproxy.base.util.ByteArray } interface HttpServerResponse { fun header(key: String, value: String): HttpServerResponse suspend fun send(body: io.vproxy.base.util.ByteArray?) fun isHeadersSent():Boolean suspend fun sendHeadersBeforeChunks() suspend fun sendChunk(payload: io.vproxy.base.util.ByteArray): HttpServerResponse suspend fun endChunks(trailers: List<io.vproxy.base.processor.http1.entity.Header>) suspend fun send() = send(null) suspend fun send(body: String) = send(io.vproxy.base.util.ByteArray.from(body)) suspend fun send(json: JSON.Instance<*>) = send(io.vproxy.base.util.ByteArray.from(json.stringify())) suspend fun sendChunk(payload: String): HttpServerResponse = sendChunk(io.vproxy.base.util.ByteArray.from(payload)) suspend fun sendChunk(json: JSON.Instance<*>): HttpServerResponse = sendChunk(io.vproxy.base.util.ByteArray.from(json.stringify())) } class RoutingContext( val conn: HttpServerConnection, val req: HttpServerRequest, routes: Map<HttpMethod, io.vproxy.base.util.coll.Tree<SubPath, RoutingHandler>>, ) { private var tree: io.vproxy.base.util.coll.Tree<SubPath, RoutingHandler> private val uri = req.uri().split("/").map { it.trim() }.filter { it.isNotEmpty() } private var handled = false private val storage: MutableMap<StorageKey<*>, Any?> = HashMap() private val params: MutableMap<String, String> = HashMap() init { val method = HttpMethod.valueOf(req.method()) tree = routes[method]!! } fun <T> put(key: StorageKey<T>, value: T?) { storage[key] = value } @Suppress("unchecked_cast") fun <T> get(key: StorageKey<T>): T? { return storage[key] as T? } fun putParam(key: String, value: String): RoutingContext { params[key] = value return this } fun param(key: String): String { return params[key]!! } private suspend fun send404() { conn.response(404).send("Cannot ${req.method()} ${req.uri()}\r\n") } private suspend fun send500(e: Throwable) { conn.response(500).send("${req.method()} ${req.uri()} failed: $e\r\n") } suspend fun execute() { if (uri.isEmpty()) { // special handle for `/` handleLeaves(tree) } else { executeDFS(tree, 0) } if (!handled) { send404() } } private var nextAllowed: Boolean = false fun allowNext() { nextAllowed = true } // return true if the handling must be stopped immediately private suspend fun handleLeaves(tree: io.vproxy.base.util.coll.Tree<SubPath, RoutingHandler>) { for (handler in tree.leafData()) { try { handler.handle(this) } catch (e: Throwable) { io.vproxy.base.util.Logger.error( io.vproxy.base.util.LogType.IMPROPER_USE, "handler thrown error when handling ${req.method()} ${req.uri()}", e ) handled = true send500(e) return } val nextAllowed = this.nextAllowed this.nextAllowed = false if (!nextAllowed) { handled = true return } } } // return true if the handling must be stopped immediately private suspend fun executeDFS(tree: io.vproxy.base.util.coll.Tree<SubPath, RoutingHandler>, idx: Int) { if (idx >= uri.size) { return } for (br in tree.branches()) { if (br.data.match(uri[idx])) { val subRoute = if (idx == uri.size - 1) { if (uri[idx].contains("?")) { uri[idx].substring(0, uri[idx].indexOf("?")) } else { uri[idx] } } else { uri[idx] } br.data.fill(this, subRoute) if (idx == uri.size - 1 || br.data is WildcardSubPath) { handleLeaves(br) if (handled) { return } } executeDFS(br, idx + 1) if (handled) { return } } } } } interface RoutingHandler { suspend fun handle(rctx: RoutingContext) } typealias RoutingHandlerFunc = suspend (RoutingContext) -> Unit
6
null
37
150
316ff3f0594a7b403e43c7f738862e8a9b180040
4,534
vproxy
MIT License
data/src/main/java/sample/kanda/data/mappers/mapConnectionExceptionsToDomainErrors.kt
jcaiqueoliveira
123,600,821
false
null
package sample.kanda.data.mappers import kanda.libs.domain.DomainException import java.io.IOException import java.net.SocketTimeoutException import java.net.UnknownHostException import java.util.concurrent.TimeoutException /** * Created by caique on 3/6/18. */ fun mapConnectionExceptionsToDomainErrors(err: Throwable): Throwable { if (err is DomainException) { return err } return when (err) { is IOException, is UnknownHostException, is TimeoutException, is SocketTimeoutException -> DomainException.ClientException else -> DomainException.GenericException } }
0
Kotlin
0
2
e71755ffcaffaa1b00c5b1afd4a1b64baef644a6
631
finger-burn
MIT License
cities-web/src/main/kotlin/io/pivotal/cities/web/conversion/CoordinateType.kt
pacphi
127,375,286
false
null
package io.pivotal.cities.web.conversion import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.* import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonSerialize import io.pivotal.cities.domain.location.api.CoordinateDto @JsonSerialize(using = CoordinateSerializer::class) @JsonDeserialize(using = CoordinateDeserializer::class) data class CoordinateType( val longitude: Double, val latitude: Double) { companion object { fun fromDto(dto: CoordinateDto): CoordinateType = CoordinateType( longitude = dto.longitude, latitude = dto.latitude ) } } class CoordinateSerializer : JsonSerializer<CoordinateType>() { override fun serialize( value: CoordinateType?, gen: JsonGenerator?, serializers: SerializerProvider?) { if (gen != null && value != null) { gen.writeStartObject() gen.writeNumberField("lat", value.latitude) gen.writeNumberField("long", value.longitude) gen.writeEndObject() } } } class CoordinateDeserializer : JsonDeserializer<CoordinateType?>() { override fun deserialize( p: JsonParser?, ctxt: DeserializationContext?): CoordinateType? { if (p != null && ctxt != null) { val node: JsonNode = p.codec.readTree(p) return CoordinateType( longitude = node.get("long").doubleValue(), latitude = node.get("lat").doubleValue()) } else { return null } } }
23
Kotlin
4
3
aac664f9a318a32e2a4b4b2ed47dd4697b916eaa
1,723
spring-boot-with-kotlin-and-jpa-example
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/autoscaling/RequestCountScalingPropsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.autoscaling import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.autoscaling.RequestCountScalingProps @Generated public fun buildRequestCountScalingProps(initializer: @AwsCdkDsl RequestCountScalingProps.Builder.() -> Unit): RequestCountScalingProps = RequestCountScalingProps.Builder().apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
450
aws-cdk-kt
Apache License 2.0
src/main/kotlin/no/nav/syfo/domain/Sykmelding.kt
navikt
121,716,621
false
{"Kotlin": 426054, "Dockerfile": 440}
package no.nav.syfo.domain data class Sykmelding( val id: Int, val orgnummer: String? = null )
15
Kotlin
2
4
5e7d80fa3e776803f34d67fef96db51818c6ed8b
104
syfoinntektsmelding
MIT License
spring-componentmap/src/test/kotlin/dev/krud/spring/componentmap/examples/calculator/CalculatorOperationType.kt
krud-dev
523,310,204
false
null
package dev.krud.spring.componentmap.examples.calculator enum class CalculatorOperationType { ADD, SUBTRACT, MULTIPLY, DIVIDE, NONE }
1
Kotlin
0
8
af879efc52281530f4115e1e5d9a2b0cf5f6c96c
154
spring-componentmap
MIT License
library/src/main/java/ru/yandex/money/android/sdk/impl/MaxHeightRecyclerView.kt
GorshkovNikita
144,304,854
false
null
/* * The MIT License (MIT) * Copyright © 2018 NBCO Yandex.Money LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the “Software”), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package ru.yandex.money.android.sdk.impl.view import android.content.Context import android.support.v7.widget.RecyclerView import android.util.AttributeSet import ru.yandex.money.android.sdk.R internal class MaxHeightRecyclerView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : RecyclerView(context, attrs, defStyleAttr) { var maxHeight: Int = 0 init { with(context.theme.obtainStyledAttributes(attrs, R.styleable.ym_MaxHeightRecyclerView, defStyleAttr, 0)) { if (hasValue(R.styleable.ym_MaxHeightRecyclerView_ym_maxHeight)) { maxHeight = getDimensionPixelSize(R.styleable.ym_MaxHeightRecyclerView_ym_maxHeight, 0) } recycle() } } override fun onMeasure(widthSpec: Int, heightSpec: Int) { val newHeightSpec = maxHeight .takeUnless(0::equals) ?.takeIf { MeasureSpec.getSize(heightSpec) > it } ?.let { MeasureSpec.makeMeasureSpec(it, MeasureSpec.AT_MOST) } ?: heightSpec super.onMeasure(widthSpec, newHeightSpec) } }
1
null
1
1
fa44a3b0a3872d9f1ede52ebbf90fc1d68dcf386
2,296
yandex-checkout-android-sdk
MIT License
jetbrains-core/src/software/aws/toolkits/jetbrains/services/codewhisperer/service/CodeWhispererClassifierConstants.kt
aws
91,485,909
false
null
// Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.codewhisperer.service import software.aws.toolkits.jetbrains.services.codewhisperer.language.CodeWhispererProgrammingLanguage import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererCsharp import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererJava import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererJavaScript import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererJsx import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererPlainText import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererPython import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererTsx import software.aws.toolkits.jetbrains.services.codewhisperer.language.languages.CodeWhispererTypeScript import software.aws.toolkits.telemetry.CodewhispererAutomatedTriggerType object CodeWhispererClassifierConstants { val osMap: Map<String, Double> = mapOf( "Mac OS X" to 0.0741, "win32" to 0.018, "Windows 10" to 0.2765, "Windows 7" to 0.0335, ) // these are used for 100% classifier driven auto trigger val triggerTypeCoefficientMap: Map<CodewhispererAutomatedTriggerType, Double> = mapOf( CodewhispererAutomatedTriggerType.SpecialCharacters to 0.0624, CodewhispererAutomatedTriggerType.Enter to 0.207 ) val languageMap: Map<CodeWhispererProgrammingLanguage, Double> = mapOf( CodeWhispererPython.INSTANCE to -0.2656, CodeWhispererJava.INSTANCE to -0.3737, CodeWhispererJavaScript.INSTANCE to -0.3611, CodeWhispererCsharp.INSTANCE to 0.0, CodeWhispererPlainText.INSTANCE to 0.0, CodeWhispererTypeScript.INSTANCE to -0.3931, CodeWhispererTsx.INSTANCE to 0.0, CodeWhispererJsx.INSTANCE to 0.0 ) // other metadata coefficient const val lineNumCoefficient = 2.4507 const val cursorOffsetCoefficient = -1.9998 // length of the current line of left_context const val lengthOfLeftCurrentCoefficient = -1.0103 // length of the previous line of left context const val lengthOfLeftPrevCoefficient = 0.4099 // lenght of right_context const val lengthofRightCoefficient = -0.426 const val lineDiffCoefficient = 0.377 const val prevDecisionAcceptCoefficient = 1.2233 const val prevDecisionRejectCoefficient = -0.1507 const val prevDecisionOtherCoefficient = -0.0093 // intercept of logistic regression classifier const val intercept = -0.04756079 val coefficientsMap = mapOf<String, Double>( "False" to -0.1006, "None" to 0.1757, "True" to -0.1783, "abstract" to -0.1583, "and" to -0.0246, "any" to -0.5444, "arguments" to 0.3351, "as" to 0.054, "assert" to 0.3538, "async" to -0.1247, "await" to 0.0205, "base" to -0.0734, "bool" to 0.2111, "boolean" to 0.1225, "break" to -0.241, "byte" to 0.0113, "case" to 0.3065, "catch" to 1.0111, "char" to -0.0324, "checked" to 0.12, "class" to 0.1572, "const" to -0.5621, "continue" to -0.7951, "debugger" to -0.3898, "decimal" to -0.0162, "def" to 0.7647, "default" to 0.1289, "del" to -0.1192, "delegate" to 0.2523, "delete" to 0.0804, "do" to -0.3249, "double" to 0.0515, "elif" to 1.1261, "else" to -0.1974, "enum" to -0.2813, "eval" to -0.0527, "event" to 0.2892, "except" to 1.3827, "explicit" to 0.0743, "export" to -0.4735, "extends" to 0.2279, "extern" to -0.0482, "false" to 0.1996, "final" to -1.0326, "finally" to 0.0987, "fixed" to -0.0101, "float" to 0.2225, "for" to 0.398, "foreach" to 0.1189, "from" to 0.1864, "function" to 0.6337, "get" to -0.337, "global" to 0.1947, "goto" to 0.0, "if" to 0.2856, "implements" to 0.0509, "implicit" to 0.0, "import" to -0.4132, "in" to 0.0517, "instanceof" to -0.0527, "int" to -0.3033, "interface" to -0.1086, "internal" to 0.1165, "is" to 0.1365, "lambda" to 0.871, "let" to -0.8694, "lock" to 0.0728, "long" to 0.0014, "module" to 0.6073, "namespace" to -0.0201, "native" to 0.0, "new" to 0.3862, "nonlocal" to 0.0, "not" to 0.1825, "null" to 0.2631, "number" to 0.3205, "object" to 1.0271, "operator" to 0.166, "or" to 0.7321, "out" to 0.0059, "override" to 0.0071, "package" to -0.0929, "params" to -0.1764, "pass" to -0.1964, "private" to -0.2461, "protected" to -0.2725, "public" to -0.0519, "raise" to 0.7565, "readonly" to -0.4363, "ref" to 0.3455, "return" to 0.1601, "sbyte" to 0.0, "sealed" to 0.0, "short" to 0.0, "sizeof" to 0.0, "stackalloc" to 0.0, "static" to -0.3759, "strictfp" to 0.0, "string" to 0.3221, "struct" to 0.018, "super" to -0.105, "switch" to 0.3145, "synchronized" to 0.0097, "this" to 0.6475, "throw" to 1.0519, "throws" to -0.0815, "transient" to 0.0, "true" to 0.334, "try" to -0.2083, "type" to 0.0806, "typeof" to 0.3026, "uint" to -0.1173, "ulong" to 0.0, "unchecked" to 0.0, "unsafe" to 0.0, "ushort" to 0.0, "using" to 0.239, "var" to -0.9392, "virtual" to 0.0, "void" to 0.408, "volatile" to 0.0, "while" to 0.6905, "with" to 0.0446, "yield" to -0.0593, " " to 0.0134, "!" to -0.6027, "\"" to -0.3134, "#" to -1.451, "$" to -0.5431, "%" to -0.4637, "&" to -0.2307, "'" to -0.3702, "(" to 0.3116, ")" to -0.6789, "*" to -1.5531, "+" to -0.6805, "," to -0.2927, "-" to -0.9242, "." to -0.6001, "/" to -1.5167, "0" to -1.3701, "1" to -1.1693, "2" to -1.2146, "3" to -0.5654, "4" to -1.1667, "5" to -1.0519, "6" to -1.5824, "7" to -1.4413, "8" to -1.6181, "9" to -1.2799, ":" to 0.2868, ";" to -1.2036, "<" to -0.5011, "=" to -0.1256, ">" to -0.5585, "?" to -0.7477, "@" to -0.7144, "A" to -0.3267, "B" to -0.0695, "C" to -0.3239, "D" to -0.452, "E" to -0.3843, "F" to -0.4099, "G" to -0.4143, "H" to -0.124, "I" to -0.2478, "J" to -0.4139, "K" to -0.5061, "L" to -0.245, "M" to -0.3303, "N" to -0.5471, "O" to -0.3772, "P" to -0.3847, "Q" to -0.1783, "R" to -0.3994, "S" to -0.2535, "T" to -0.3746, "U" to -0.6347, "V" to -0.2543, "W" to -0.4353, "X" to -0.105, "Y" to -0.6737, "Z" to -0.3218, "[" to -0.3086, "\\" to -1.5857, "]" to -0.9263, "^" to -0.2029, "_" to -0.291, "`" to -1.0691, "a" to -0.2392, "b" to -0.2473, "c" to -0.228, "d" to -0.13, "e" to -0.1277, "f" to -0.1625, "g" to -0.2912, "h" to -0.0463, "i" to -0.1384, "j" to -0.6122, "k" to -0.3229, "l" to -0.1911, "m" to -0.2133, "n" to -0.0712, "o" to -0.1545, "p" to -0.3171, "q" to -0.3805, "r" to -0.0471, "s" to -0.2272, "t" to -0.0944, "u" to -0.0051, "v" to -0.2343, "w" to -0.0309, "x" to -0.1762, "y" to -0.0288, "z" to -0.7588, "{" to 0.0843, "|" to -0.2508, "}" to -0.9324, "~" to -0.2903 ) }
363
Kotlin
158
694
7eda113804f1d2fdc180ec08675c200bf748ef01
8,565
aws-toolkit-jetbrains
Apache License 2.0
app/src/main/java/ru/dimon6018/metrolauncher/content/oobe/WelcomeActivity.kt
queuejw
659,118,377
false
{"Kotlin": 218672, "Java": 102442}
package ru.dimon6018.metrolauncher.content.oobe import android.app.Activity import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.WindowCompat import androidx.fragment.app.commit import ru.dimon6018.metrolauncher.Application.Companion.PREFS import ru.dimon6018.metrolauncher.Main import ru.dimon6018.metrolauncher.R class WelcomeActivity: AppCompatActivity() { private var textLabel: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.oobe) textLabel = findViewById(R.id.appbarTextView) WindowCompat.setDecorFitsSystemWindows(window, false) val coordinatorLayout: CoordinatorLayout = findViewById(R.id.coordinator) Main.applyWindowInsets(coordinatorLayout) if (savedInstanceState != null) { if(PREFS!!.launcherState != 2) { supportFragmentManager.commit { replace(R.id.fragment_container_view, WelcomeFragment(), "oobe") } } else { supportFragmentManager.commit { replace(R.id.fragment_container_view, ConfigureFragment(), "oobe") } } } } companion object { fun setText(activity: Activity, text: String) { activity.findViewById<TextView>(R.id.appbarTextView)!!.text = text } } }
0
Kotlin
0
9
1599ad6dfca9a8d3e14859d3f82ec665e9f8b5ab
1,548
MetroPhoneLauncher
MIT License
src/pt/yesmangas/src/eu/kanade/tachiyomi/extension/pt/yesmangas/YesMangas.kt
ZongerZY
287,689,898
true
{"Kotlin": 3948599, "Shell": 1958, "Java": 608}
package eu.kanade.tachiyomi.extension.pt.yesmangas import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import okhttp3.Headers import okhttp3.HttpUrl import okhttp3.Request import org.jsoup.nodes.Document import org.jsoup.nodes.Element import org.jsoup.select.Elements class YesMangas : ParsedHttpSource() { // Hardcode the id because the language wasn't specific. override val id: Long = 7187189302580957274 override val name = "YES Mangás" override val baseUrl = "https://yesmangas1.com" override val lang = "pt-BR" override val supportsLatest = true override fun headersBuilder(): Headers.Builder = Headers.Builder() .add("User-Agent", USER_AGENT) .add("Origin", baseUrl) .add("Referer", baseUrl) override fun popularMangaRequest(page: Int): Request = GET(baseUrl, headers) override fun popularMangaSelector(): String = "div#destaques div.three.columns a.img" override fun popularMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.attr("title").withoutLanguage() thumbnail_url = element.select("img").attr("data-path").toLargeUrl() url = element.attr("href") } override fun popularMangaNextPageSelector(): String? = null override fun latestUpdatesRequest(page: Int): Request = GET(baseUrl, headers) override fun latestUpdatesSelector(): String = "div#lancamentos table.u-full-width tbody tr td:eq(0) a" override fun latestUpdatesFromElement(element: Element): SManga = SManga.create().apply { title = element.attr("title").withoutLanguage() thumbnail_url = element.select("img").attr("data-path").toLargeUrl() setUrlWithoutDomain(element.attr("href")) } override fun latestUpdatesNextPageSelector(): String? = null override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { val url = HttpUrl.parse("$baseUrl/search")!!.newBuilder() .addQueryParameter("q", query) return GET(url.toString(), headers) } override fun searchMangaSelector(): String = "tbody#leituras tr td:eq(0) a" override fun searchMangaFromElement(element: Element): SManga = SManga.create().apply { title = element.attr("title").withoutLanguage() thumbnail_url = element.select("img").attr("data-path").toLargeUrl() setUrlWithoutDomain(element.attr("href")) } override fun searchMangaNextPageSelector(): String? = null override fun mangaDetailsParse(document: Document): SManga = SManga.create().apply { val container = document.select("div#descricao").first() author = container.select("ul li:contains(Autor)").textWithoutLabel() artist = container.select("ul li:contains(Desenho)").textWithoutLabel() genre = container.select("ul li:contains(Categorias)").textWithoutLabel() status = container.select("ul li:contains(Status)").text().toStatus() description = container.select("article").text() .substringBefore("Relacionados") thumbnail_url = container.select("img").first() .attr("data-path") .toLargeUrl() } override fun chapterListSelector(): String = "div#capitulos a.button" override fun chapterFromElement(element: Element): SChapter = SChapter.create().apply { name = element.attr("title").substringAfter(" - ") chapter_number = element.text().toFloatOrNull() ?: -1f setUrlWithoutDomain(element.attr("href")) } override fun pageListRequest(chapter: SChapter): Request { val newHeaders = headersBuilder() .set("Referer", baseUrl + chapter.url.substringBeforeLast("/")) .build() return GET(baseUrl + chapter.url, newHeaders) } override fun pageListParse(document: Document): List<Page> { return document.select("div.read-slideshow a img") .mapIndexed { i, el -> Page(i, document.location(), el.attr("src")) } } override fun imageUrlParse(document: Document): String = "" override fun imageRequest(page: Page): Request { val newHeaders = headersBuilder() .set("Referer", page.url) .build() return GET(page.imageUrl!!, newHeaders) } private fun String.withoutLanguage(): String = replace(LANG_REGEX, "") private fun String.toLargeUrl(): String = replace(IMAGE_REGEX, "_full.") private fun Elements.textWithoutLabel(): String = text()!!.substringAfter(":").trim() private fun String.toStatus() = when { contains("Completo") -> SManga.COMPLETED contains("Ativo") -> SManga.ONGOING else -> SManga.UNKNOWN } companion object { private const val USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" private val LANG_REGEX = "( )?\\((PT-)?BR\\)".toRegex() private val IMAGE_REGEX = "_(small|medium|xmedium|xlarge)\\.".toRegex() } }
0
Kotlin
1
8
1f40e4d4c4aff4b71fa72ffae03dbcd871e91803
5,289
tachiyomi-extensions
Apache License 2.0
design/src/main/java/com/ingresse/design/ui/component/CreditCardEnums.kt
ingresse
203,441,687
false
null
package com.ingresse.design.ui.component import androidx.annotation.DrawableRes import com.ingresse.design.R enum class CardBrands(val regex: String, @DrawableRes val brandIcon: Int) { AMEX("^3[47][0-9]{13}\$", R.drawable.ic_card_flag_amex), DINERS("^3(?:0[0-5]|[68][0-9])[0-9]{11}\$", R.drawable.ic_card_flag_diners), DISCOVER("^6011|^64([4-9])|^65", R.drawable.ic_card_flag_discover), ELO("""^(4011(78|79)|43(1274|8935)|45(1416|7393|763(1|2))| |50(4175|6699|67[0-7][0-9]|9000)|50(9[0-9][0-9][0-9])|627780|63(6297|6368)| |650(03([^4])|04([0-9])|05(0|1)|05([7-9])|06([0-9])|07([0-9])|08([0-9])|4([0-3][0-9]|8[5-9] |9[0-9])|5([0-9][0-9]|3[0-8])|9([0-6][0-9]|7[0-8])|7([0-2][0-9])|541|700|720|727|901) |65165([2-9])|6516([6-7][0-9])|65500([0-9])|6550([0-5][0-9])|655021|65505([6-7]) |6516([8-9][0-9])|65170([0-4]))""".trimMargin(), R.drawable.ic_card_flag_elo), MASTERCARD("""^5[1-5][0-9]{14}${'$'}|^26[0-9]{4}|^25[0-9]{4}|^24[0-9]{4}| |^23[0-9]{4}|^228[0-9]{3}|^227[0-9]{3}|^226[0-9]{3}|^225[0-9]{3}|^224[0-9]{3}|^223[0-9]{3}| |^2228[0-9]{2}|^2227[0-9]{2}|^2226[0-9]{2}|^2225[0-9]{2}|^2224[0-9]{2}|^2223[0-9]{2} |^2222[0-9]{2}|^22218[0-9]|^22217[0-9]|^22216[0-9]|^22215[0-9]|^22214[0-9]|^22213[0-9]| |^22212[0-9]|^22211[0-9]|^22210[0-9]|^22219[0-9]|^22298[0-9]|^22297[0-9]|^22296[0-9]| |^22295[0-9]|^22294[0-9]|^22293[0-9]|^22292[0-9]|^22291[0-9]|^22290[0-9]|^22299[0-9]| |^2298[0-9]{2}|^2297[0-9]{2}|^2296[0-9]{2}|^2295[0-9]{2}|^2294[0-9]{2}|^2293[0-9]{2}| |^2292[0-9]{2}|^2291[0-9]{2}|^22908[0-9]|^22907[0-9]|^22906[0-9]|^22905[0-9]|^22904[0-9]| |^22903[0-9]|^22902[0-9]|^22901[0-9]|^22900[0-9]|^22909[0-9]|^22998[0-9]|^22997[0-9]| |^22996[0-9]|^22995[0-9]|^22994[0-9]|^22993[0-9]|^22992[0-9]|^22991[0-9]|^22990[0-9]| |^22999[0-9]|^271[0-9]{3}|^2708[0-9]{2}|^2707[0-9]{2}|^2706[0-9]{2}|^2705[0-9]{2}| |^2704[0-9]{2}|^2703[0-9]{2}|^2702[0-9]{2}|^2701[0-9]{2}|^27008[0-9]|^27007[0-9]| |^27006[0-9]|^27005[0-9]|^27004[0-9]|^27003[0-9]|^27002[0-9]|^27001[0-9]|^27000[0-9]| |^27009[0-9]|^27098[0-9]|^27097[0-9]|^27096[0-9]|^27095[0-9]|^27094[0-9]|^27093[0-9]| |^27092[0-9]|^27091[0-9]|^27090[0-9]|^27099[0-9]|^27208[0-9]|^27207[0-9]|^27206[0-9]| |^27205[0-9]|^27204[0-9]|^27203[0-9]|^27202[0-9]|^27201[0-9]|^27200[0-9]|^27209[0-9]""" .trimMargin(), R.drawable.ic_card_flag_master_card), VISA("^4[0-9]{12}(?:[0-9]{3})?\$", R.drawable.ic_card_flag_visa), OTHER("", R.drawable.ic_card_flag_others); companion object { fun findByRegex(binCard: String) = values().firstOrNull { it.regex.toRegex().matches(binCard) } ?: OTHER } }
3
Kotlin
0
1
381d7b36d8ad693cf13c7a5ba02127bcb6278019
2,740
design-systems-android
MIT License
app/src/main/java/com/github/jing332/tts_server_android/help/ByteArrayBinder.kt
jing332
536,800,727
false
null
package com.github.jing332.tts_server_android.help import android.os.Binder // Binder 用于传递大数据 class ByteArrayBinder(val data: ByteArray) : Binder()
6
Kotlin
127
1,393
8e07e8842cf4cec70154041fcd6a64ad2352d8c8
149
tts-server-android
MIT License
function/src/main/java/app/allever/android/sample/function/im/viewmodel/ConversationViewModel.kt
devallever
522,186,250
false
{"Kotlin": 519675, "Java": 281241, "C++": 13880, "CMake": 1635, "C": 664}
package app.allever.android.sample.function.im.viewmodel import android.content.Intent import androidx.lifecycle.viewModelScope import app.allever.android.lib.core.ext.log import app.allever.android.lib.core.function.media.MediaBean import app.allever.android.lib.core.function.mediapicker.MediaPickerHelper import app.allever.android.lib.core.helper.GsonHelper import app.allever.android.lib.mvvm.base.BaseViewModel import app.allever.android.sample.function.R import app.allever.android.sample.function.im.constant.ActionType import app.allever.android.sample.function.im.function.db.IMDBController import app.allever.android.sample.function.im.message.BaseMessage import app.allever.android.sample.function.im.message.ImageMessage import app.allever.android.sample.function.im.message.TextMessage import app.allever.android.sample.function.im.message.VideoMessage import app.allever.android.sample.function.im.ui.ConversationActivity.Companion.EXTRA_OTHER_USER_ID import app.allever.android.sample.function.im.ui.adapter.ExpandAdapter import app.allever.android.sample.function.im.ui.adapter.ExpandItem import app.allever.android.sample.function.im.ui.adapter.MessageAdapter import app.allever.android.sample.function.im.user.UserInfo import kotlinx.coroutines.launch class ConversationViewModel : BaseViewModel() { val userMe = IMViewModel.loginUser ?: UserInfo() var otherUserId = 0L set(value) { field = value if (value != 0L) { viewModelScope.launch { userOther = IMDBController.getUserById(value) ?: UserInfo() } } } var userOther: UserInfo = UserInfo() val messageAdapter = MessageAdapter() val messageList = mutableListOf<BaseMessage>() val expandAdapter = ExpandAdapter() override fun init() { viewModelScope.launch { if (userMe.id == 0L) { userMe.avatar = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.win4000.com%2Fwallpaper%2F2019-05-28%2F5cecf6fe1ce3b.jpg&refer=http%3A%2F%2Fpic1.win4000.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1671440223&t=fc84daf5543856c1686bd29b9f2dbadc" userMe.nickname = "小猫咪666" } userOther = IMDBController.getUserById(otherUserId) ?: UserInfo() if (userOther.id == 0L) { userOther.avatar = "https://img2.baidu.com/it/u=1801140900,2951304091&fm=253&fmt=auto&app=120&f=JPEG?w=1280&h=800" userOther.nickname = "倾国倾城" // userOther.id = 2 } log("otherUser = ${GsonHelper.toJson(userOther)}") initTestData() } } fun initExtra(intent: Intent?) { otherUserId = intent?.getLongExtra(EXTRA_OTHER_USER_ID, 0L) ?: 0L } fun initExpandFunData() { val list = mutableListOf<ExpandItem>() list.add(ExpandItem(R.drawable.bottom_input_emo, "图片", ExpandItem.TYPE_IMAGE)) list.add(ExpandItem(R.drawable.bottom_input_emo, "视频", ExpandItem.TYPE_VIDEO)) list.add(ExpandItem(R.drawable.bottom_input_emo, "语音通话", ExpandItem.TYPE_AUDIO_CALL)) list.add(ExpandItem(R.drawable.bottom_input_emo, "视频通话", ExpandItem.TYPE_VIDEO_CALL)) list.add(ExpandItem(R.drawable.bottom_input_emo, "位置", ExpandItem.TYPE_LOCATION)) expandAdapter.setList(list) } fun getMessageList() { viewModelScope.launch { // val result = IMDBController.getMessageList() } } private fun initTestData() { val msg1 = TextMessage() msg1.actionType = ActionType.RECEIVE msg1.user = userOther msg1.content = "你好美女,能交个朋友吗?" messageList.add(0, msg1) val msg2 = TextMessage() msg2.user = userMe msg2.actionType = ActionType.SEND msg2.content = "可以的呀,你是哪里人?" messageList.add(0, msg2) val msg3 = TextMessage() msg3.user = userOther msg3.actionType = ActionType.RECEIVE msg3.content = "广州的" messageList.add(0, msg3) val msg4 = ImageMessage() msg4.user = userMe msg4.url = userMe.avatar msg4.width = 1 messageList.add(0, msg4) val msg6 = TextMessage() msg6.user = userMe msg6.actionType = ActionType.SEND msg6.content = "这是我,好看么?可以看看你的照片吗?" messageList.add(0, msg6) val msg7 = TextMessage() msg7.user = userOther msg7.actionType = ActionType.RECEIVE msg7.content = "当然可以呀" messageList.add(0, msg7) val msg8 = ImageMessage() msg8.user = userOther msg8.actionType = ActionType.RECEIVE msg8.url = userOther.avatar msg8.height = 1 messageList.add(0, msg8) val msg9 = TextMessage() msg9.user = userMe msg9.actionType = ActionType.SEND msg9.content = "这是我拍的视频?好看吗?点个赞呗" messageList.add(0, msg9) val msg10 = VideoMessage() msg10.user = userMe msg10.actionType = ActionType.SEND msg10.url = userMe.avatar msg10.height = 1 messageList.add(0, msg10) val msg11 = TextMessage() msg11.user = userOther msg11.actionType = ActionType.RECEIVE msg11.content = "这也太好看了吧,我也拍了一个,给你看看" messageList.add(0, msg11) val msg12 = VideoMessage() msg12.user = userOther msg12.actionType = ActionType.RECEIVE msg12.url = userOther.avatar msg12.width = 1 messageList.add(0, msg12) messageAdapter.setList(messageList) messageAdapter.recyclerView.scrollToPosition(0) } fun sendTextMessage(content: String) { val message = TextMessage() message.user = userMe message.actionType = ActionType.SEND message.content = content message.fromUserId = userMe.id message.toUserId = userOther.id message.time = System.currentTimeMillis() messageAdapter.addData(0, message) // val messageEntity = message.createMessageEntity(ActionType.SEND) // viewModelScope.launch { // IMDBController.insertMessage(messageEntity) // IMDBController.printAllMessage() // } } fun sendMediaMessage(media: MediaBean, mediaType: String) { when (mediaType) { MediaPickerHelper.TYPE_IMAGE -> sendImageMessage(media) MediaPickerHelper.TYPE_VIDEO -> sendVideoMessage(media) } } fun sendImageMessage(media: MediaBean) { val message = ImageMessage() message.user = userMe message.actionType = ActionType.SEND message.path = media.path message.url = media.path message.width = media.width message.height = media.height messageAdapter.addData(0, message) } fun sendVideoMessage(media: MediaBean) { val message = VideoMessage() message.user = userMe message.actionType = ActionType.SEND message.path = media.path message.cover = media.path message.url = media.path message.width = media.width message.height = media.height messageAdapter.addData(0, message) } }
1
Kotlin
0
3
9c4250e2a070b1a51e5e67d3735edbe7b38a90fa
7,277
AndroidSampleLibs
Apache License 2.0
app/src/main/java/com/eccard/popularmovies/PopularMoviesApp.kt
eccard
151,618,036
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 25, "Kotlin": 64}
package com.eccard.popularmovies import android.app.Activity import android.app.Application import com.eccard.popularmovies.di.component.DaggerAppComponent import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import javax.inject.Inject class PopularMoviesApp : Application(), HasActivityInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> override fun activityInjector() = dispatchingAndroidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.builder() .application(this) .build() .inject(this) } }
1
null
1
1
20423e23dc44578c7599caee95335a92757b0c6d
692
Filmes-Famosos
MIT License
app/src/main/java/com/eccard/popularmovies/PopularMoviesApp.kt
eccard
151,618,036
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 25, "Kotlin": 64}
package com.eccard.popularmovies import android.app.Activity import android.app.Application import com.eccard.popularmovies.di.component.DaggerAppComponent import dagger.android.DispatchingAndroidInjector import dagger.android.HasActivityInjector import javax.inject.Inject class PopularMoviesApp : Application(), HasActivityInjector { @Inject lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Activity> override fun activityInjector() = dispatchingAndroidInjector override fun onCreate() { super.onCreate() DaggerAppComponent.builder() .application(this) .build() .inject(this) } }
1
null
1
1
20423e23dc44578c7599caee95335a92757b0c6d
692
Filmes-Famosos
MIT License
data/src/main/java/ch/srg/dataProvider/integrationlayer/data/remote/Page.kt
SRGSSR
469,671,723
false
{"Kotlin": 139259, "Java": 15427, "Shell": 555}
package ch.srg.dataProvider.integrationlayer.data.remote import kotlinx.serialization.Serializable /** * Copyright (c) SRG SSR. All rights reserved. * <p> * License information is available from the LICENSE file. */ @Serializable data class Page( override val id: String, override val vendor: Vendor, val title: String, val isPublished: Boolean, val type: String, val sectionList: List<Section>? = null, val topicUrn: String? = null, val description: String? = null, ) : ILObject
5
Kotlin
0
0
cf55609aab4410dc2ae53e57b899384b7d6e53a0
518
srgdataprovider-android
MIT License
app/src/main/java/com/jeanca/gitapp/utils/Colors.kt
hajc1294
501,025,933
false
null
package com.jeanca.gitapp.utils import androidx.compose.ui.graphics.Color class Colors { companion object { fun getColorFromLanguage(language: String): Color = when (language) { "Java" -> Color(185, 119, 14) "Dart" -> Color(26, 188, 156) "Kotlin" -> Color(175, 122, 197) "Swift" -> Color(231, 76, 60) "JavaScript" -> Color(247, 220, 111) else -> Color.Black } } }
0
Kotlin
1
0
936a4a27f1e8ffd2e1e03585be36cf217cbe91fa
463
android-app-kotlin-gitapp
MIT License
compiler/testData/diagnostics/nativeTests/nativeProtectedFunCall.fir.kt
JetBrains
3,432,266
false
null
// ISSUE: KT-58623 package pack open class ProtectedInsideInlineParent { protected var protectedParentVar = 0 protected fun protectedParentFun() = 0 } open class ProtectedInsideInlineError : ProtectedInsideInlineParent() { protected var protectedVar = 0 protected fun protectedFun() = 0 <!NOTHING_TO_INLINE!>inline<!> fun publicInlineUserFun(): Int { println(<!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedVar<!> + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentVar<!>) <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedFun<!>() <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentFun<!>() return <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedVar<!> + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentVar<!> } inline var publicInlineUserVal: Int get() = <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedVar<!> + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedFun<!>() + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentVar<!> + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentFun<!>() set(value) { <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedVar<!> + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedFun<!>() + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentVar<!> + <!PROTECTED_CALL_FROM_PUBLIC_INLINE_ERROR!>protectedParentFun<!>() } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,407
kotlin
Apache License 2.0
tinn-core/src/main/kotlin/com/virusbear/tinn/shader/VertexShader.kt
virusbear
809,423,131
false
{"Kotlin": 65340}
package com.virusbear.tinn.shader interface VertexShader: Shader { }
0
Kotlin
0
0
2bede64a6c92dbf2148ef08bc0f3efc8f5008edf
70
tinn
Apache License 2.0
app/src/main/java/com/better/alarm/ui/list/InfoFragment.kt
yuriykulikov
4,096,259
false
null
package com.better.alarm.presenter import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.content.res.Resources import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.AnimationUtils import android.widget.TextSwitcher import android.widget.TextView import android.widget.ViewSwitcher import androidx.fragment.app.Fragment import com.better.alarm.R import com.better.alarm.configuration.Prefs import com.better.alarm.configuration.Store import com.better.alarm.configuration.globalInject import com.better.alarm.util.Optional import io.reactivex.Observable import io.reactivex.disposables.Disposable import io.reactivex.functions.BiFunction /** @author Yuriy */ class InfoFragment : Fragment() { private val prefs: Prefs by globalInject() private val store: Store by globalInject() private var disposable: Disposable? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) val view = inflater.inflate(R.layout.info_fragment, container, false) val fadeIn = AnimationUtils.loadAnimation(requireActivity(), android.R.anim.fade_in) val fadeOut = AnimationUtils.loadAnimation(requireActivity(), android.R.anim.fade_out) val viewFactory = ViewSwitcher.ViewFactory { requireActivity().layoutInflater.inflate(R.layout.info_fragment_text, container, false) as TextView } val remainingTime: TextSwitcher = view.findViewById<TextSwitcher>(R.id.info_fragment_text_view_remaining_time).apply { setFactory(viewFactory) inAnimation = fadeIn outAnimation = fadeOut } disposable = Observable.combineLatest<Optional<Store.Next>, Long, String>( store.next(), now(), BiFunction { next, now -> next.getOrNull()?.let { computeTexts( resources, it, now, prefs.preAlarmDuration.value, ) } ?: "" }) .distinctUntilChanged() .subscribe { remainingText -> remainingTime.setText(remainingText) } return view } override fun onDestroy() { super.onDestroy() disposable?.dispose() } private fun now(): Observable<Long> { return Observable.create<Long> { emitter -> val tickReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { emitter.onNext(System.currentTimeMillis()) } } requireActivity().registerReceiver(tickReceiver, IntentFilter(Intent.ACTION_TIME_TICK)) emitter.setCancellable { requireActivity().unregisterReceiver(tickReceiver) } } .startWith(System.currentTimeMillis()) } } fun computeTexts( res: Resources, alarm: Store.Next, now: Long, prealarmDuration: Int, ): String { val nextMillis = alarm.nextNonPrealarmTime() val formatRemainingTimeString = formatRemainingTimeString(res, nextMillis, now) return if (alarm.isPrealarm) { val prealarmSummary = res.getString(R.string.info_fragment_prealarm_summary, prealarmDuration) """$formatRemainingTimeString $prealarmSummary""".trimIndent() formatRemainingTimeString.plus("\n$prealarmSummary") } else { formatRemainingTimeString } } /** format "Alarm set for 2 days 7 hours and 53 minutes from now" */ private fun formatRemainingTimeString(res: Resources, timeInMillis: Long, now: Long): String { val delta = timeInMillis - now val days = delta / (1000 * 60 * 60) / 24 val hours = delta / (1000 * 60 * 60) % 24 val minutes = delta / (1000 * 60) % 60 val daySeq = when (days) { 0L -> "" 1L -> res.getString(R.string.day) else -> res.getString(R.string.days, days.toString()) } val minSeq = when (minutes) { 0L -> "" 1L -> res.getString(R.string.minute) else -> res.getString(R.string.minutes, minutes.toString()) } val hourSeq = when (hours) { 0L -> "" 1L -> res.getString(R.string.hour) else -> res.getString(R.string.hours, hours.toString()) } // bitmask val index = (if (days > 0) 1 else 0) or (if (hours > 0) 2 else 0) or (if (minutes > 0) 4 else 0) val formats = res.getStringArray(R.array.alarm_set_short) return String.format(formats[index], daySeq, hourSeq, minSeq) }
63
null
161
482
8293b5229e3b05095894efcdcde924f4188c15e8
4,838
AlarmClock
Apache License 2.0
app/src/main/java/com/lianyi/paimonsnotebook/ui/screen/geetest/viewmodel/GeeTestScreenViewModel.kt
QooLianyi
435,314,581
false
{"Kotlin": 2026028}
package com.lianyi.paimonsnotebook.ui.screen.geetest.viewmodel import android.content.Intent import androidx.lifecycle.ViewModel class GeeTestScreenViewModel : ViewModel() { fun init(intent: Intent?, onFail: () -> Unit) { if (intent == null) { onFail.invoke() return } } }
1
Kotlin
2
36
59fd15325dfccfd0d5e888b8e77d37bcb5ca7d56
326
PaimonsNotebook
MIT License
eql-compiler/src/test/kotlin/cz/vutbr/fit/knot/enticing/eql/compiler/ast/visitor/AstDefinitionsGeneratingVisitorTest.kt
d-kozak
180,137,313
false
{"Kotlin": 1104829, "TypeScript": 477922, "Python": 23617, "Shell": 19609, "HTML": 8510, "ANTLR": 2005, "CSS": 1432}
package cz.vutbr.fit.knot.enticing.eql.compiler.ast.visitor internal class AstDefinitionsGeneratingVisitorTest { }
0
Kotlin
0
0
1ea9f874c6d2e4ea158e20bbf672fc45bcb4a561
116
enticing
MIT License
kmongo-shared/src/main/kotlin/org/litote/kmongo/util/SimpleExpression.kt
Litote
58,964,537
false
null
/* * Copyright (C) 2016/2020 Litote * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.litote.kmongo.util import org.bson.BsonDocument import org.bson.BsonDocumentWriter import org.bson.codecs.configuration.CodecRegistry import org.bson.conversions.Bson import org.litote.kmongo.util.KMongoUtil.encodeValue /** * */ internal class SimpleExpression<TExpression : Any>( private val name: String, private val expression: TExpression ) : Bson { override fun <TDocument> toBsonDocument( documentClass: Class<TDocument>, codecRegistry: CodecRegistry ): BsonDocument { val writer = BsonDocumentWriter(BsonDocument()) writer.writeStartDocument() writer.writeName(name) encodeValue(writer, expression, codecRegistry) writer.writeEndDocument() return writer.document } override fun toString(): String { return ("Expression{" + "name='" + name + '\''.toString() + ", expression=" + expression + '}'.toString()) } }
42
Kotlin
74
797
4ee6939272ca54a342955130ae6d98eb947ace01
1,580
kmongo
Apache License 2.0
app/src/androidMain/java/PlatformServiceLocator.kt
cmota
228,910,680
false
null
import com.squareup.sqldelight.android.AndroidSqliteDriver import com.squareup.sqldelight.db.SqlDriver import data.ScheduleDb import data.createDatabase import io.ktor.client.engine.HttpClientEngine import io.ktor.client.engine.okhttp.OkHttp import okhttp3.logging.HttpLoggingInterceptor import presentation.AppApplication actual object PlatformServiceLocator { actual val httpClientEngine: HttpClientEngine by lazy { OkHttp.create { val networkInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.HEADERS } addNetworkInterceptor(networkInterceptor) } } actual val databaseEngine: ScheduleDb by lazy { setupDatabase() } private fun setupDatabase(): ScheduleDb { val driver: SqlDriver = AndroidSqliteDriver(ScheduleDb.Schema, AppApplication.appContext, "droidcon.db") return createDatabase(driver) } }
0
Kotlin
2
24
ad4e3711428d2827561cdee4c78a8bba97fd9286
951
droidconMAD
Apache License 2.0
app/src/main/java/com/xda/nachonotch/activities/SettingsActivity.kt
zacharee
127,220,159
false
{"Kotlin": 102537, "AIDL": 103}
package com.xda.nachonotch.activities import android.annotation.SuppressLint import android.os.Bundle import android.view.View import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.WindowInsetsSides import androidx.compose.foundation.layout.add import androidx.compose.foundation.layout.asPaddingValues import androidx.compose.foundation.layout.displayCutout import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.navigationBars import androidx.compose.foundation.layout.only import androidx.compose.foundation.layout.systemBars import androidx.compose.foundation.layout.windowInsetsPadding import androidx.compose.material3.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.viewinterop.AndroidView import androidx.core.os.bundleOf import androidx.core.view.updatePaddingRelative import androidx.fragment.app.FragmentContainerView import androidx.preference.PreferenceFragmentCompat import com.xda.nachonotch.R import com.xda.nachonotch.components.TitleBar import com.xda.nachonotch.util.PrefManager import com.xda.nachonotch.util.enforceTerms import com.xda.nachonotch.util.resourceNavBarHeight import com.xda.nachonotch.util.resourceStatusBarHeight import tk.zwander.seekbarpreference.SeekBarPreference class SettingsActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) if (!enforceTerms()) finish() } @SuppressLint("InflateParams") @Composable override fun Content() { Surface( modifier = Modifier.fillMaxSize() .windowInsetsPadding( WindowInsets.systemBars.add(WindowInsets.ime) .add(WindowInsets.displayCutout.only(WindowInsetsSides.Horizontal)) .only(WindowInsetsSides.Top + WindowInsetsSides.Horizontal), ), ) { Column( modifier = Modifier.fillMaxSize(), ) { TitleBar(title = title.toString()) val bottomPadding = with(LocalDensity.current) { WindowInsets.navigationBars.add(WindowInsets.ime) .asPaddingValues().calculateBottomPadding().toPx() } AndroidView( factory = { FragmentContainerView(it).apply { id = R.id.content } }, modifier = Modifier.fillMaxWidth() .weight(1f), ) { view -> val fragment = MainFragment() fragment.arguments = bundleOf("bottomInset" to bottomPadding) supportFragmentManager.beginTransaction() .setReorderingAllowed(true) .replace(view.id, fragment, null) .commitNowAllowingStateLoss() } } } } class MainFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.prefs_main, rootKey) setListeners() } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) view.findViewById<View>(R.id.recycler_view) ?.updatePaddingRelative( bottom = requireArguments().getFloat("bottomInset").toInt(), ) } private fun setListeners() { val statusHeight = findPreference<SeekBarPreference>(PrefManager.STATUS_HEIGHT) as SeekBarPreference val navHeight = findPreference<SeekBarPreference>(PrefManager.NAV_HEIGHT) as SeekBarPreference preferenceManager.sharedPreferences?.apply { if (!contains(PrefManager.STATUS_HEIGHT)) statusHeight.progress = requireActivity().resourceStatusBarHeight if (!contains(PrefManager.NAV_HEIGHT)) navHeight.progress = requireActivity().resourceNavBarHeight } statusHeight.setDefaultValue(requireActivity().resourceStatusBarHeight) navHeight.setDefaultValue(requireActivity().resourceNavBarHeight) } } }
4
Kotlin
17
78
cbea9323fd43d5f84f39c7999bb2318ddcfedfe1
4,650
NachoNotch
MIT License
mbcarkit/src/main/java/com/daimler/mbcarkit/business/model/vehicle/EcoScore.kt
Daimler
199,815,262
false
null
package com.daimler.mbcarkit.business.model.vehicle import com.daimler.mbcarkit.business.model.vehicle.unit.DistanceUnit import com.daimler.mbcarkit.business.model.vehicle.unit.RatioUnit data class EcoScore( /** * Rating acceleration percentage points (0% - 100%) * Range: 0..100 */ var accel: VehicleAttribute<Int, RatioUnit>, /** * Rating bonus range in km * Range: 0..1638.0 */ var bonusRange: VehicleAttribute<Double, DistanceUnit>, /** * Rating constancy percentage points (0% - 100%) * Range: 0..100 */ var const: VehicleAttribute<Int, RatioUnit>, /** * Rating free wheeling percentage points (0% - 100%) * Range: 0..100 */ var freeWhl: VehicleAttribute<Int, RatioUnit>, /** * Overall rating percentage points (0% - 100%) * Range: 0..100 */ var total: VehicleAttribute<Int, RatioUnit> )
1
null
8
15
3721af583408721b9cd5cf89dd7b99256e9d7dda
914
MBSDK-Mobile-Android
MIT License
app/src/main/java/com/pechuro/cashdebts/ui/fragment/picturetakeoptions/PictureTakeOptionDialogProvider.kt
Ilyshka991
171,679,797
false
null
package com.pechuro.cashdebts.ui.fragment.picturetakeoptions import com.pechuro.cashdebts.di.annotations.ChildFragmentScope import dagger.Module import dagger.android.ContributesAndroidInjector @Module interface PictureTakeOptionDialogProvider { @ChildFragmentScope @ContributesAndroidInjector fun bind(): PictureTakeOptionsDialog }
0
Kotlin
0
3
afb871ebb70b2863a1f2c290f7e06a3f5b9feab6
347
CashDebts
Apache License 2.0
plugins/world/player/skill/woodcutting/cutTree/cutTree.kts
Phynvi
233,257,304
true
{"Java": 921214, "Kotlin": 317275, "CSS": 129}
package world.player.skill.woodcutting.cutTree import api.predef.* import io.luna.game.event.impl.ObjectClickEvent.ObjectFirstClickEvent import io.luna.game.model.`object`.GameObject import io.luna.game.model.mob.Player import io.luna.util.ExecutorUtils /** * Determines which axe the player has and cuts the [treeObj] if they have one. */ fun cutTree(plr: Player, tree: Tree, treeObj: GameObject) { val currentAxe = Axe.computeAxeType(plr) if (currentAxe == null) { plr.sendMessage("You do not have an axe which you have the required level to use.") return } plr.submitAction(CutTreeAction(plr, currentAxe, tree, treeObj)) } on(ObjectFirstClickEvent::class) { val treeStump = TreeStump.TREE_ID_MAP[id] if (treeStump != null) { cutTree(plr, treeStump.tree, gameObject) } }
0
Java
0
0
f3e81a236e6d21379c319eac1f3d0392f6537b2f
833
luna
MIT License
fitness-center/src/main/kotlin/base/clock/NormalClock.kt
pavponn
296,904,749
false
{"Text": 2, "Ignore List": 4, "Markdown": 1, "Maven POM": 2, "Java": 27, "Gradle": 20, "INI": 16, "Shell": 10, "Batchfile": 10, "Kotlin": 166, "SQL": 2, "Java Properties": 4, "AspectJ": 1, "XML": 8, "HTML": 1}
package base.clock import java.time.Instant /** * @author pavponn */ class NormalClock : Clock { override fun now(): Instant { return Instant.now() } }
1
null
1
1
3a72e61bb66a7eb79385ec8945f3ef8572e4b60e
172
software-engineering
MIT License
app/src/main/java/com/example/tentwentyassignment/activities/DetailPageActivity.kt
zohaibmuhammadf
442,167,821
false
{"Kotlin": 23662}
package com.example.tentwentyassignment.activities import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Window import android.view.WindowManager import androidx.recyclerview.widget.LinearLayoutManager import com.example.tentwentyassignment.R import com.example.tentwentyassignment.adapters.GenresListingAdapter import com.example.tentwentyassignment.databinding.ActivityDetailPageBinding import com.example.tentwentyassignment.models.GenreItemModel class DetailPageActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailPageBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) hideStatusBar() setBindings() setGenreAdapter() callBacks() } private fun callBacks() { binding.txtReleaseDate.text = intent.getStringExtra("mReleaseDate") binding.txtDescription.text = intent.getStringExtra("mDescription") binding.imageBackFromDetail.setOnClickListener { finish() } } private fun hideStatusBar() { requestWindowFeature(Window.FEATURE_NO_TITLE) window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN) } private fun setGenreAdapter() { val mGenreItemModelList = ArrayList<GenreItemModel>() mGenreItemModelList.add(GenreItemModel("Action", R.color.genre_one)) mGenreItemModelList.add(GenreItemModel("Thriller", R.color.genre_two)) mGenreItemModelList.add(GenreItemModel("Science", R.color.genre_three)) mGenreItemModelList.add(GenreItemModel("Friction", R.color.genre_four)) binding.recyclerGenres.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) val adapter = GenresListingAdapter(this, mGenreItemModelList) binding.recyclerGenres.adapter = adapter } private fun setBindings() { binding = ActivityDetailPageBinding.inflate(layoutInflater) setContentView(binding.root) } }
0
Kotlin
0
0
2f3e7509d1490a0144b61d951475af9528fbf811
2,102
CustomTabbarFragment-Android
Apache License 2.0
Android/Retrofit demo/app/src/main/java/com/example/retrofittut/MainActivity.kt
keshavsingh4522
298,358,641
false
null
package com.example.retrofittut import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.example.retrofittut.databinding.ActivityMainBinding import retrofit2.HttpException import java.io.IOException const val TAG = "MainAcctivity" class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding private lateinit var todoAdapter : TodoAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupRecyclerView() lifecycleScope.launchWhenCreated { binding.progressBar.isVisible = true val response = try { RetrofitInstance.api.getTodos() }catch (e : IOException){ binding.progressBar.isVisible = false Log.e(TAG,"internet expection") return@launchWhenCreated }catch (e : HttpException){ binding.progressBar.isVisible = false Log.e(TAG,"http expection , unexpexted") return@launchWhenCreated } if (response.isSuccessful && response.body() != null ){ todoAdapter.todos = response.body()!! }else { Log.e(TAG, "Response not successful") } binding.progressBar.isVisible = false } } private fun setupRecyclerView() = binding.rvTodos.apply { todoAdapter = TodoAdapter() adapter = todoAdapter layoutManager = LinearLayoutManager(this@MainActivity) } }
2,951
null
3984
851
6beac31cf93ae1a4556335c775cc77e12efe1e8a
1,821
hacktoberfest
Creative Commons Zero v1.0 Universal
Android/Retrofit demo/app/src/main/java/com/example/retrofittut/MainActivity.kt
keshavsingh4522
298,358,641
false
null
package com.example.retrofittut import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import androidx.core.view.isVisible import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.example.retrofittut.databinding.ActivityMainBinding import retrofit2.HttpException import java.io.IOException const val TAG = "MainAcctivity" class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding private lateinit var todoAdapter : TodoAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupRecyclerView() lifecycleScope.launchWhenCreated { binding.progressBar.isVisible = true val response = try { RetrofitInstance.api.getTodos() }catch (e : IOException){ binding.progressBar.isVisible = false Log.e(TAG,"internet expection") return@launchWhenCreated }catch (e : HttpException){ binding.progressBar.isVisible = false Log.e(TAG,"http expection , unexpexted") return@launchWhenCreated } if (response.isSuccessful && response.body() != null ){ todoAdapter.todos = response.body()!! }else { Log.e(TAG, "Response not successful") } binding.progressBar.isVisible = false } } private fun setupRecyclerView() = binding.rvTodos.apply { todoAdapter = TodoAdapter() adapter = todoAdapter layoutManager = LinearLayoutManager(this@MainActivity) } }
2,951
null
3984
851
6beac31cf93ae1a4556335c775cc77e12efe1e8a
1,821
hacktoberfest
Creative Commons Zero v1.0 Universal
idea/testData/refactoring/move/kotlin/moveFile/moveFileAndDirWithJavaFileReferringToPackageFragementWithUnmatchedDir/after/test2/FooUsage.kt
JakeWharton
99,388,807
true
null
package test2 import test.pack.Foo val foo = Foo()
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
53
kotlin
Apache License 2.0
src/test/kotlin/no/nav/hn/grunndata/rapid/dto/ProductRegistrationDTOTest.kt
navikt
599,930,610
false
{"Kotlin": 37339, "Shell": 1505}
package no.nav.hn.grunndata.rapid.dto import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import no.nav.hm.grunndata.rapid.dto.AdminStatus import no.nav.hm.grunndata.rapid.dto.AgreementInfo import no.nav.hm.grunndata.rapid.dto.Attributes import no.nav.hm.grunndata.rapid.dto.CompatibleWith import no.nav.hm.grunndata.rapid.dto.DraftStatus import no.nav.hm.grunndata.rapid.dto.MediaInfo import no.nav.hm.grunndata.rapid.dto.MediaSourceType import no.nav.hm.grunndata.rapid.dto.ProductAgreementStatus import no.nav.hm.grunndata.rapid.dto.ProductRapidDTO import no.nav.hm.grunndata.rapid.dto.ProductRegistrationRapidDTO import no.nav.hm.grunndata.rapid.dto.RegistrationStatus import no.nav.hm.grunndata.rapid.dto.TechData import org.junit.jupiter.api.Test import java.io.FileOutputStream import java.time.LocalDateTime import java.util.* class ProductRegistrationDTOTest { @Test fun testProductRegistrationDTO() { val uuid = UUID.fromString("a42185cd-d7a2-496a-8d8a-f3d4a02bc9d2") val productDTO = ProductRapidDTO( id = uuid, created = LocalDateTime.MAX, updated = LocalDateTime.MAX, expired = LocalDateTime.MAX, published = LocalDateTime.MAX, supplier = supplier, title = "Dette er produkt 1", articleName = "Dette er produkt 1 med og med", attributes = Attributes( shortdescription = "En kort beskrivelse av produktet", text = "En lang beskrivelse av produktet", compatibleWidth = CompatibleWith(seriesIds = setOf(uuid)) ), hmsArtNr = "111", identifier = "hmdb-111", supplierRef = "eksternref-111", isoCategory = "12001314", accessory = false, sparePart = true, seriesUUID = uuid, seriesId = "series-123", techData = listOf(TechData(key = "maksvekt", unit = "kg", value = "120")), media = setOf( MediaInfo( uri = "123.jpg", text = "bilde av produktet", source = MediaSourceType.EXTERNALURL, sourceUri = "https://ekstern.url/123.jpg", updated = LocalDateTime.MAX ) ), agreementInfo = AgreementInfo( id = uuid, identifier = "hmdbid-1", rank = 1, postNr = 1, reference = "AV-142", expired = LocalDateTime.MAX, status = ProductAgreementStatus.ACTIVE ), createdBy = "REGISTER", updatedBy = "REGISTER" ) val productRegistration = ProductRegistrationRapidDTO( id = uuid, created = LocalDateTime.MAX, updated = LocalDateTime.MAX, draftStatus = DraftStatus.DRAFT, adminStatus = AdminStatus.PENDING, registrationStatus = RegistrationStatus.ACTIVE, message = "Melding til leverandør", createdByAdmin = false, expired = LocalDateTime.MAX, published = LocalDateTime.MAX, productDTO = productDTO, version = 1, createdBy = "REGISTER", updatedBy = "REGISTER" ) //Serialize the object to a file FileOutputStream("./src/test/resources/latest/ProductRegistration.json").use { it.write(objectMapper().writerWithDefaultPrettyPrinter().writeValueAsBytes(productRegistration)) } //Deserialize old version if it works with this version val oldProductRegistration = objectMapper().readValue( this::class.java.getResourceAsStream("/old/ProductRegistration.json"), ProductRegistrationRapidDTO::class.java ) oldProductRegistration.shouldNotBeNull() productRegistration.adminStatus shouldBe AdminStatus.PENDING } }
0
Kotlin
0
2
a660d0135d2bfc079dfe84b402eedb70086b8125
4,032
hm-grunndata-rapid-dto
MIT License
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/flow/terminal_operators/2_collect.kt
Deepankur-Sadana
813,232,584
false
{"Kotlin": 255315}
package com.lukaslechner.coroutineusecasesonandroid.playground.flow.terminal_operators import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.flow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking fun main() { val flow = flow { delay(100) println("Emitting 1st value") emit(1) delay(100) println("Emitting 1st value") emit(2) while (true) { delay(5000) println() } } val scope = CoroutineScope((Job())) scope.launch { flow.collect{ println("collecting $it") } }.invokeOnCompletion { println("Completion listener of scope $it") } Thread.sleep(400) }
0
Kotlin
0
0
3b7d6fe5a5bb0c336ced96f5c6f70f6e825e7232
844
Coroutines-test
Apache License 2.0
app/src/main/java/com/app/composedemo/api/ApiService.kt
Dinesh2510
773,084,082
false
{"Kotlin": 18632}
package com.app.composedemo.api import com.app.composedemo.Constants.Companion.List_Of_product import com.app.composedemo.model.ProductList import retrofit2.http.GET interface ApiService { @GET(List_Of_product) suspend fun getProducts(): ProductList }
0
Kotlin
0
0
959f78f59b7aba9509d87f36eeaa45536876144a
262
EShop-Jetpack-Compose-API-Demo
MIT License
app/src/main/java/ir/ayantech/sdk_ocr/MainActivity.kt
AyanTech
754,078,135
false
{"Kotlin": 69046}
package ir.ayantech.sdk_ocr import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import ir.ayantech.ocr_sdk.OCRConfig import ir.ayantech.ocr_sdk.OCRConstant import ir.ayantech.ocr_sdk.OcrActivity import ir.ayantech.ocr_sdk.model.GetCardOcrResult import ir.ayantech.sdk_ocr.databinding.ActivityMainBinding import ir.ayantech.whygoogle.activity.WhyGoogleActivity class MainActivity : WhyGoogleActivity<ActivityMainBinding>() { override val binder: (LayoutInflater) -> ActivityMainBinding get() = ActivityMainBinding::inflate override val containerId: Int = R.id.fragmentContainerFl var packageNamee: String = "" var ocrResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val data = result.data?.extras } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) OCRConstant.context = this binding.btnOcrCar.setOnClickListener { callApi("VehicleCard", false) } binding.btnIdCard.setOnClickListener { callApi("NationalCard", true) } binding.btnOcrBank.setOnClickListener { callApi("BankCard", true) } } fun callApi(cardType: String, singlePhoto: Boolean) { OCRConfig.builder() .setContext(this) .setApplicationID("ir.ayantech.sdk_ocr") .setBaseUrl("https://core.pishkhan24.ayantech.ir/webservices/Proxy.svc/") .setToken("1AEDF1D7398E4C6A92D8FE2DA77789D1") .setUploadImageEndPoint("UploadNewCardOcrImage") .setGetResultEndPoint("GetCardOcrResult") .build() val intent = Intent(this, OcrActivity::class.java) intent.putExtra("cardType", cardType) intent.putExtra("singlePhoto", singlePhoto) intent.putExtra("className", "ir.ayantech.sdk_ocr.MainActivity") ocrResult.launch(intent) } override fun onNewIntent(intent: Intent?) { super.onNewIntent(intent) val data = intent?.getParcelableArrayExtra("GetCardOcrResult").toString() Log.d("asdasdkjahdkjahskjd", "onNewIntent: $data") } }
0
Kotlin
0
0
c607f4ae500fafeb38814aa8e6ea844679c18c64
2,459
OCR-SDK
Apache License 2.0
units/src/commonMain/kotlin/me/y9san9/calkt/units/calculate/UnitsMathCalculateInfixOperator.kt
y9san9
842,898,431
false
{"Kotlin": 79012}
package me.y9san9.calkt.units.calculate import me.y9san9.calkt.calculate.CalculateContext import me.y9san9.calkt.calculate.CalculateResult import me.y9san9.calkt.math.DefaultInfixKeys import me.y9san9.calkt.math.InfixKey import me.y9san9.calkt.math.MathExpression import me.y9san9.calkt.math.calculate.MathCalculateInfixOperatorFunction import me.y9san9.calkt.math.calculate.MathCalculateSuccess import me.y9san9.calkt.math.calculate.plus import me.y9san9.calkt.math.calculate.unsupportedInfixOperator import me.y9san9.calkt.number.PreciseNumber import me.y9san9.calkt.units.UnitKey import me.y9san9.calkt.units.UnitsExpression public object UnitsMathCalculateInfixOperator : MathCalculateInfixOperatorFunction { private val delegate = Sum( supportedOperators = setOf(DefaultInfixKeys.Plus, DefaultInfixKeys.Minus) ) + Prod( supportedOperators = setOf(DefaultInfixKeys.Times, DefaultInfixKeys.Div) ) override fun invoke( context: CalculateContext, left: CalculateResult.Success, right: CalculateResult.Success, key: InfixKey ): CalculateResult.Success { return delegate(context, left, right, key) } private class Sum( private val supportedOperators: Set<InfixKey> ) : MathCalculateInfixOperatorFunction { override fun invoke( context: CalculateContext, left: CalculateResult.Success, right: CalculateResult.Success, key: InfixKey ): CalculateResult.Success { if (key !in supportedOperators) context.unsupportedInfixOperator() val leftNumber = extractNumber(left) ?: context.unsupportedInfixOperator() val leftUnits = extractUnits(left) val rightNumber = extractNumber(right) ?: context.unsupportedInfixOperator() val rightUnits = extractUnits(right) // If none of operands have units, it's not a task for this function val commonUnits = leftUnits ?: rightUnits ?: context.unsupportedInfixOperator() val leftConverted = convertUnits(context, leftNumber, leftUnits, commonUnits) if (leftConverted !is UnitsCalculateSuccess) context.unsupportedInfixOperator() val rightConverted = convertUnits(context, rightNumber, rightUnits, commonUnits) if (rightConverted !is UnitsCalculateSuccess) context.unsupportedInfixOperator() val mathExpression = MathExpression.Infix( left = MathExpression.Number(leftConverted.number), right = MathExpression.Number(rightConverted.number), key = key ) val result = context.recursive(mathExpression) as? MathCalculateSuccess ?: context.unsupportedInfixOperator() return UnitsCalculateSuccess(result.number, commonUnits) } private fun extractUnits(result: CalculateResult): UnitKey? { if (result is UnitsCalculateSuccess) return result.key return null } private fun convertUnits( context: CalculateContext, number: PreciseNumber, from: UnitKey?, to: UnitKey ): CalculateResult { if (from == null) return UnitsCalculateSuccess(number, to) val fromExpression = UnitsExpression.Conversion(MathExpression.Number(number), from) val toExpression = UnitsExpression.Conversion(fromExpression, to) return context.recursive(toExpression) } } public class Prod( private val supportedOperators: Set<InfixKey> ) : MathCalculateInfixOperatorFunction { override fun invoke( context: CalculateContext, left: CalculateResult.Success, right: CalculateResult.Success, key: InfixKey ): CalculateResult.Success { if (key !in supportedOperators) context.unsupportedInfixOperator() val units = extractUnits(left, right) ?: context.unsupportedInfixOperator() val leftNumber = extractNumber(left)?.let(MathExpression::Number) ?: context.unsupportedInfixOperator() val rightNumber = extractNumber(right)?.let(MathExpression::Number) ?: context.unsupportedInfixOperator() val mathExpression = MathExpression.Infix(leftNumber, rightNumber, key) val result = context.recursive(mathExpression) as? MathCalculateSuccess ?: context.unsupportedInfixOperator() return UnitsCalculateSuccess(result.number, units) } private fun extractUnits( left: CalculateResult, right: CalculateResult ): UnitKey? { // Both operands cannot have units if multiplying if (left is UnitsCalculateSuccess && right is UnitsCalculateSuccess) return null if (left is UnitsCalculateSuccess) return left.key if (right is UnitsCalculateSuccess) return right.key return null } } private fun extractNumber(result: CalculateResult): PreciseNumber? { if (result is UnitsCalculateSuccess) return result.number if (result is MathCalculateSuccess) return result.number return null } }
1
Kotlin
1
21
06d1ecbca749ad4107d08d719916a10aa95aa6df
5,322
calkt
MIT License
src/main/kotlin/org/arend/psi/ext/ArendLevelExpr.kt
JetBrains
96,068,447
false
{"Kotlin": 2655823, "Lex": 16187, "Java": 5894, "HTML": 2144, "CSS": 1108, "JavaScript": 713}
package org.arend.psi.ext import org.arend.term.abs.AbstractLevelExpressionVisitor import com.intellij.lang.ASTNode import com.intellij.psi.util.elementType import org.arend.psi.ArendElementTypes import org.arend.psi.firstRelevantChild import org.arend.psi.getChildOfType import org.arend.term.abs.Abstract open class ArendLevelExpr(node: ASTNode) : ArendSourceNodeImpl(node), Abstract.LevelExpression { override fun getData() = this override fun <P : Any?, R : Any?> accept(visitor: AbstractLevelExpressionVisitor<in P, out R>, params: P?): R = when (firstRelevantChild.elementType) { ArendElementTypes.SUC_KW -> visitor.visitSuc(this, getChildOfType<ArendAtomLevelExpr>(), params) ArendElementTypes.MAX_KW -> visitor.visitMax(this, getChildOfType<ArendAtomLevelExpr>(), getChildOfType<ArendAtomLevelExpr>(1), params) else -> error("Unknown ArendLevelExpr") } }
73
Kotlin
15
90
7a6608a2e44369e11c5baad3ef2928d6f9c971b2
903
intellij-arend
Apache License 2.0
app/src/main/java/com/example/beokweather/domain/WeatherService.kt
ParkChan
274,966,026
true
{"Kotlin": 40144}
package com.example.beokweather.domain import com.example.beokweather.domain.entity.ForecastResponse import com.example.beokweather.domain.entity.WeatherResponse import retrofit2.http.GET import retrofit2.http.Query interface WeatherService { @GET("weather") suspend fun getCurrentWeather( @Query("lat") lat: Double, @Query("lon") lon: Double, @Query("units") units: String ): WeatherResponse @GET("forecast") suspend fun getForecastWeather( @Query("lat") lat: Double, @Query("lon") lon: Double, @Query("units") units: String ): ForecastResponse }
0
null
0
0
640142e31d54f718fcc56c8f9ac740fc88dbdba3
671
BeokWeather
MIT License
src/main/kotlin/ru/dageev/compiler/parser/ErrorListener.kt
rmnn
54,289,657
false
null
package ru.dageev.compiler.parser import org.antlr.v4.runtime.BaseErrorListener import org.antlr.v4.runtime.RecognitionException import org.antlr.v4.runtime.Recognizer /** * Created by dageev * on 15-May-16. */ class ErrorListener : BaseErrorListener() { override fun syntaxError(recognizer: Recognizer<*, *>, offendingSymbol: Any, line: Int, charPositionInLine: Int, msg: String?, e: RecognitionException?) { throw CompilationException("You failed at line $line,char $charPositionInLine :(. Details: $msg") } }
0
Kotlin
0
0
ea5213229ef4037ff02665854ccd15d9f16d56a0
535
compiler
Apache License 2.0
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/flow/terminal_operators/1_flows_vs_lists.kt
LukasLechnerDev
248,218,113
false
null
package com.example.kotlin_coroutines_and_flow.playground.flow.terminal_operators import kotlinx.coroutines.delay import kotlinx.coroutines.flow.flow fun main() { //it does not execute without terminal operation val flow = flow { delay(100) println("Emitting first value") emit(1) delay(100) println("Emitting second value") emit(2) } val list = buildList { add(1) println("add 1 to list") add(2) println("add 2 to list") } }
5
null
436
2,664
636b1038c42073a45bfccb25afbedc294b0f032d
534
Kotlin-Coroutines-and-Flow-UseCases-on-Android
Apache License 2.0
app/src/main/java/io/fastkv/fastkvdemo/MainActivity.kt
BillyWei01
416,593,131
false
null
package io.fastkv.fastkvdemo import android.annotation.SuppressLint import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import io.fastkv.FastKV import io.fastkv.fastkvdemo.account.AccountManager import io.fastkv.fastkvdemo.data.UserInfo import io.fastkv.fastkvdemo.base.AppContext import io.fastkv.fastkvdemo.manager.PathManager import io.fastkv.fastkvdemo.data.SpCase import io.fastkv.fastkvdemo.data.UsageData import io.fastkv.fastkvdemo.util.onClick import kotlinx.android.synthetic.main.activity_main.account_info_tv import kotlinx.android.synthetic.main.activity_main.login_btn import kotlinx.android.synthetic.main.activity_main.switch_account_btn import kotlinx.android.synthetic.main.activity_main.test_multi_process_btn import kotlinx.android.synthetic.main.activity_main.test_performance_btn import kotlinx.android.synthetic.main.activity_main.tips_tv import kotlinx.android.synthetic.main.activity_main.user_info_tv import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) printLaunchTime() refreshAccountInfoViews() login_btn.onClick { if (AccountManager.isLogin()) { AccountManager.logout() switch_account_btn.isEnabled = false } else { if (UsageData.lastLoginUid == 0L) { AccountManager.login(10001L) } else { AccountManager.login(UsageData.lastLoginUid) } switch_account_btn.isEnabled = true } refreshAccountInfoViews() } switch_account_btn.onClick { if (AppContext.isLogin()) { if (AppContext.uid == 10001L) { AccountManager.switchAccount(10002L) } else { AccountManager.switchAccount(10001L) } } else { tips_tv.text = getString(R.string.login_first_tips) } refreshAccountInfoViews() } test_multi_process_btn.onClick { val intent = Intent(this, MultiProcessTestActivity::class.java) startActivity(intent) } test_performance_btn.onClick { startBenchMark() } } @SuppressLint("SetTextI18n") private fun startBenchMark() { tips_tv.text = getString(R.string.running_tips) tips_tv.setTextColor(Color.parseColor("#FFFF8247")) test_performance_btn.isEnabled = false CoroutineScope(Dispatchers.Default).launch { Benchmark.start { kvCount -> CoroutineScope(Dispatchers.Main).launch { if (kvCount >= 0) { tips_tv.text = "Testing, kvCount: $kvCount" } else { tips_tv.text = getString(R.string.test_tips) test_performance_btn.isEnabled = true } tips_tv.setTextColor(Color.parseColor("#FF009900")) } } } } @SuppressLint("SetTextI18n") private fun refreshAccountInfoViews() { if (AccountManager.isLogin()) { login_btn.text = getString(R.string.logout) account_info_tv.visibility = View.VISIBLE user_info_tv.visibility = View.VISIBLE UserInfo.get().userAccount?.run { account_info_tv.text = "uid: $uid\nnickname: $nickname\nphone: $phoneNo\nemail: $email" } user_info_tv.text = AccountManager.formatUserInfo() } else { login_btn.text = getString(R.string.login) account_info_tv.visibility = View.GONE user_info_tv.visibility = View.GONE } } private fun printLaunchTime() { case1() } /** * If use SharedPreferences to store data before, * you could import old values to new store framework, * with the same interface with SharedPreferences. */ fun case1() { val preferences = SpCase.preferences val t = preferences.getInt(SpCase.LAUNCH_COUNT, 0) + 1 tips_tv.text = getString(R.string.main_tips, t) preferences.edit().putInt(SpCase.LAUNCH_COUNT, t).apply() } /** * If there is no data storing to SharedPreferences before. * just use new API of FastKV. */ fun case2() { val kv = FastKV.Builder(PathManager.fastKVDir, "common_store").build() val t = kv.getInt("launch_count") + 1 tips_tv.text = getString(R.string.main_tips, t) kv.putInt("launch_count", t) } /** * With kotlin's syntactic sugar, read/write key-value data just like accessing variable. */ fun case3() { val t = UsageData.launchCount + 1 tips_tv.text = getString(R.string.main_tips, t) UsageData.launchCount = t } }
0
null
37
347
8b5bc2bfc128100d32188bcb32b6e3bec640510b
5,221
FastKV
MIT License
app-inspection/ide/src/com/android/tools/idea/appinspection/ide/resolver/ArtifactResolverFactory.kt
JetBrains
60,701,247
false
{"Kotlin": 47327090, "Java": 36711107, "HTML": 1217549, "Starlark": 856686, "C++": 321587, "Python": 100400, "C": 71515, "Lex": 66732, "NSIS": 58538, "AIDL": 35209, "Shell": 28699, "CMake": 26717, "JavaScript": 18437, "Batchfile": 7828, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.appinspection.ide.resolver import com.android.tools.idea.analytics.currentIdeBrand import com.android.tools.idea.appinspection.ide.resolver.blaze.BlazeArtifactResolver import com.android.tools.idea.appinspection.ide.resolver.http.HttpArtifactResolver import com.android.tools.idea.appinspection.ide.resolver.moduleSystem.ModuleSystemArtifactResolver import com.android.tools.idea.appinspection.inspector.ide.resolver.ArtifactResolver import com.android.tools.idea.appinspection.inspector.ide.resolver.ArtifactResolverFactory import com.android.tools.idea.flags.StudioFlags import com.android.tools.idea.io.FileService import com.google.wireless.android.sdk.stats.AndroidStudioEvent import com.intellij.openapi.project.Project class ArtifactResolverFactory( private val fileService: FileService, private val getIdeBrand: () -> AndroidStudioEvent.IdeBrand = { currentIdeBrand() } ) : ArtifactResolverFactory { private val httpArtifactResolver = HttpArtifactResolver(fileService, AppInspectorArtifactPaths(fileService)) override fun getArtifactResolver(project: Project): ArtifactResolver = if (getIdeBrand() == AndroidStudioEvent.IdeBrand.ANDROID_STUDIO_WITH_BLAZE) { BlazeArtifactResolver(fileService, ModuleSystemArtifactFinder(project)) } else { if (StudioFlags.APP_INSPECTION_USE_SNAPSHOT_JAR.get()) { ModuleSystemArtifactResolver(fileService, ModuleSystemArtifactFinder(project)) } else { httpArtifactResolver } } }
3
Kotlin
220
912
d88742a5542b0852e7cb2dd6571e01576cb52841
2,136
android
Apache License 2.0
app/src/main/java/me/ibrahimsn/wallet/di/module/SendFragmentBuilder.kt
ibrahimsn98
188,556,561
false
null
package me.ibrahimsn.wallet.di.module import dagger.Module import dagger.android.ContributesAndroidInjector import me.ibrahimsn.wallet.ui.send.confirm.ConfirmFragment import me.ibrahimsn.wallet.ui.send.send.SendFragment @Module abstract class SendFragmentBuilder { /** * Build Send Transaction Fragment */ @ContributesAndroidInjector internal abstract fun buildSendFragment(): SendFragment /** * Build Confirm Transaction Fragment */ @ContributesAndroidInjector internal abstract fun buildConfirmFragment(): ConfirmFragment }
0
Kotlin
11
37
e8ee5997813979fade2cf8496b0ec1bc3fbec7fa
573
android-eth-wallet
MIT License
lib/src/commonMain/kotlin/xyz/mcxross/ksui/internal/Transaction.kt
mcxross
611,172,630
false
{"Kotlin": 269236, "Shell": 3152}
/* * Copyright 2024 McXross * * 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 xyz.mcxross.ksui.internal import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import xyz.mcxross.bcs.Bcs import xyz.mcxross.ksui.account.Account import xyz.mcxross.ksui.client.getGraphqlClient import xyz.mcxross.ksui.core.crypto.Hash import xyz.mcxross.ksui.core.crypto.hash import xyz.mcxross.ksui.exception.SuiException import xyz.mcxross.ksui.generated.DryRunTransactionBlock import xyz.mcxross.ksui.generated.ExecuteTransactionBlock import xyz.mcxross.ksui.generated.GetTotalTransactionBlocks import xyz.mcxross.ksui.generated.QueryTransactionBlocks import xyz.mcxross.ksui.model.AccountAddress import xyz.mcxross.ksui.model.Digest import xyz.mcxross.ksui.model.ExecuteTransactionBlockResponseOptions import xyz.mcxross.ksui.model.Intent import xyz.mcxross.ksui.model.IntentMessage import xyz.mcxross.ksui.model.ObjectDigest import xyz.mcxross.ksui.model.ObjectReference import xyz.mcxross.ksui.model.Option import xyz.mcxross.ksui.model.Reference import xyz.mcxross.ksui.model.SuiAddress import xyz.mcxross.ksui.model.SuiConfig import xyz.mcxross.ksui.model.TransactionBlockResponseOptions import xyz.mcxross.ksui.model.TransactionBlocks import xyz.mcxross.ksui.model.TransactionDataComposer import xyz.mcxross.ksui.model.content import xyz.mcxross.ksui.model.with import xyz.mcxross.ksui.ptb.ProgrammableTransaction suspend fun executeTransactionBlock( config: SuiConfig, txnBytes: String, signatures: List<String>, option: ExecuteTransactionBlockResponseOptions, ): Option.Some<ExecuteTransactionBlock.Result?> { val response = getGraphqlClient(config) .execute<ExecuteTransactionBlock.Result>( ExecuteTransactionBlock( ExecuteTransactionBlock.Variables(txBytes = txnBytes, signatures = signatures) ) ) if (response.errors != null) { throw SuiException(response.errors.toString()) } return Option.Some(response.data) } internal suspend fun dryRunTransactionBlock( config: SuiConfig, txnBytes: String, option: ExecuteTransactionBlockResponseOptions, ): Option.Some<DryRunTransactionBlock.Result?> { val response = getGraphqlClient(config) .execute<DryRunTransactionBlock.Result>( DryRunTransactionBlock(DryRunTransactionBlock.Variables(txBytes = txnBytes)) ) if (response.errors != null) { throw SuiException(response.errors.toString()) } return Option.Some(response.data) } suspend fun getTotalTransactionBlocks(config: SuiConfig): Option<Long?> { val response = getGraphqlClient(config).execute<GetTotalTransactionBlocks.Result>(GetTotalTransactionBlocks()) if (response.errors != null) { throw SuiException(response.errors.toString()) } if (response.data == null) { return Option.None } return Option.Some(response.data?.checkpoint?.networkTotalTransactions?.toLong()) } suspend fun queryTransactionBlocks( config: SuiConfig, transactionBlockResponseOptions: TransactionBlockResponseOptions, ): Option<TransactionBlocks> { val response = getGraphqlClient(config) .execute<QueryTransactionBlocks.Result>( QueryTransactionBlocks( QueryTransactionBlocks.Variables( first = transactionBlockResponseOptions.first, last = transactionBlockResponseOptions.last, before = transactionBlockResponseOptions.before, after = transactionBlockResponseOptions.after, showBalanceChanges = transactionBlockResponseOptions.showBalanceChanges, showEffects = transactionBlockResponseOptions.showEffects, showRawEffects = transactionBlockResponseOptions.showRawEffects, showEvents = transactionBlockResponseOptions.showEvents, showInput = transactionBlockResponseOptions.showInput, showObjectChanges = transactionBlockResponseOptions.showObjectChanges, showRawInput = transactionBlockResponseOptions.showRawInput, filter = transactionBlockResponseOptions.filter, ) ) ) if (response.errors != null) { throw SuiException(response.errors.toString()) } if (response.data == null) { return Option.None } return Option.Some(response.data) } internal fun signTransaction(message: ByteArray, signer: Account): ByteArray { return signer.sign(message) } @OptIn(ExperimentalEncodingApi::class) internal suspend fun signAndSubmitTransaction( config: SuiConfig, ptb: ProgrammableTransaction, signer: Account, gasBudget: ULong, ): Option.Some<ExecuteTransactionBlock.Result?> { val gasPrice = when (val gp = getReferenceGasPrice(config)) { is Option.Some -> gp.value is Option.None -> throw SuiException("Failed to get gas price") } val paymentObject = when (val po = getCoins(config, SuiAddress.fromString(signer.address.toString()))) { is Option.Some -> po.value is Option.None -> throw SuiException("Failed to get payment object") } val sightedCoin = paymentObject?.address?.coins?.nodes?.get(0) val address = sightedCoin?.address ?: throw SuiException("Failed to get address") val digest = ObjectDigest(Digest(sightedCoin.digest ?: throw SuiException("Failed to get digest"))) val txData = TransactionDataComposer.programmable( sender = SuiAddress.fromString(signer.address.toString()), gapPayment = listOf( ObjectReference( Reference(AccountAddress.fromString(address)), sightedCoin.version.toLong(), digest, ) ), pt = ptb, gasBudget = gasBudget, gasPrice = gasPrice?.toULong() ?: throw SuiException("Failed to get gas price"), ) val intentMessage = IntentMessage(Intent.suiTransaction(), txData) val sig = signer.sign(hash(Hash.BLAKE2B256, Bcs.encodeToByteArray(intentMessage))) val serializedSignatureBytes = byteArrayOf(signer.scheme.scheme) + sig + signer.publicKey.data val tx = txData with listOf(Base64.encode(serializedSignatureBytes)) val content = tx.content() val response = getGraphqlClient(config) .execute<ExecuteTransactionBlock.Result>( ExecuteTransactionBlock( ExecuteTransactionBlock.Variables(txBytes = content.first, signatures = content.second) ) ) if (response.errors != null) { throw SuiException(response.errors.toString()) } return Option.Some(response.data) }
0
Kotlin
2
5
e456766ba489e09f710c2ed3a41f83b27100f4f4
7,013
ksui
Apache License 2.0
src/main/java/com/adityaamolbavadekar/android/apps/culture/ConfigureTheme.kt
AdityaBavadekar
424,247,862
false
null
package com.adityaamolbavadekar.android.apps.culture import android.content.Context import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.preference.PreferenceManager class ConfigureTheme { fun onCreate(TAG: String, activity: Context) { val prefs = PreferenceManager.getDefaultSharedPreferences(activity) try { when (prefs.getString("theme", "3")) { "1" -> { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) } "2" -> { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) } "3" -> { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) } } } catch (e: Exception) { } } }
0
Kotlin
0
1
b6418f4784ff51749cb2e9487f6e5a3af42e1db1
924
Culture
Apache License 2.0
common/src/main/java/io/novafoundation/nova/common/utils/formatting/TimerValue.kt
novasamatech
415,834,480
false
{"Kotlin": 8137060, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.common.utils.formatting import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.toDuration class TimerValue( val millis: Long, val millisCalculatedAt: Long, // used to offset timer value if timer is rerun, e.g. in the RecyclerView ) { companion object { fun fromCurrentTime(millis: Long): TimerValue { return TimerValue(millis, System.currentTimeMillis()) } } override fun toString(): String { return millis.toDuration(DurationUnit.MILLISECONDS).toString() } } fun Duration.toTimerValue() = TimerValue.fromCurrentTime(millis = inWholeMilliseconds) fun TimerValue.remainingTime(): Long { val currentTimer = System.currentTimeMillis() val passedTime = currentTimer - millisCalculatedAt val remainingTime = millis - passedTime return remainingTime.coerceAtLeast(0) }
12
Kotlin
6
9
618357859a4b7af95391fc0991339b78aff1be82
901
nova-wallet-android
Apache License 2.0
app/src/main/kotlin/io/github/d4isdavid/educhat/http/request/HttpFormDataPart.kt
D4isDAVID
763,254,966
false
{"Kotlin": 355508}
package io.github.d4isdavid.educhat.http.request data class HttpFormDataPart( val content: String, val name: String, val contentType: String? = null, val filename: String? = null )
0
Kotlin
0
0
9f1d235cdc787c4c011c686703926c8f0fa2919a
198
EduChat-app
MIT License
miniapp/src/test/java/com/rakuten/tech/mobile/miniapp/js/ShareContentBridgeSpec.kt
rakutentech
225,744,634
false
null
package com.rakuten.tech.mobile.miniapp.js import androidx.test.core.app.ActivityScenario import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.gson.Gson import com.rakuten.tech.mobile.miniapp.TEST_CALLBACK_ID import com.rakuten.tech.mobile.miniapp.TEST_MA_ID import com.rakuten.tech.mobile.miniapp.TestActivity import com.rakuten.tech.mobile.miniapp.TestFilesDirActivity import org.amshove.kluent.When import org.amshove.kluent.calling import org.amshove.kluent.itReturns import org.amshove.kluent.shouldBeEqualTo import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify @RunWith(AndroidJUnit4::class) class ShareContentBridgeSpec : BridgeCommon() { private val miniAppBridge = Mockito.spy(createDefaultMiniAppMessageBridge()) @Before fun setupShareInfo() { ActivityScenario.launch(TestActivity::class.java).onActivity { activity -> When calling miniAppBridge.createBridgeExecutor(webViewListener) itReturns bridgeExecutor miniAppBridge.updateApiClient(mock()) miniAppBridge.init( activity = activity, webViewListener = webViewListener, customPermissionCache = mock(), downloadedManifestCache = mock(), miniAppId = TEST_MA_ID, ratDispatcher = mock(), secureStorageDispatcher = mock(), miniAppIAPVerifier = mock() ) } } private val shareContentJsonStr = createShareCallbackJsonStr("This is content") private fun createShareCallbackJsonStr(content: String) = Gson().toJson( CallbackObj( action = ActionType.SHARE_INFO.action, param = ShareInfoCallbackObj.ShareInfoParam( ShareInfo(content) ), id = TEST_CALLBACK_ID ) ) @Test fun `postValue should be called when content is shared successfully`() { ActivityScenario.launch(TestActivity::class.java).onActivity { activity -> val miniAppBridge = Mockito.spy(createDefaultMiniAppMessageBridge()) When calling miniAppBridge.createBridgeExecutor(webViewListener) itReturns bridgeExecutor miniAppBridge.updateApiClient(mock()) miniAppBridge.init( activity = activity, webViewListener = webViewListener, customPermissionCache = mock(), downloadedManifestCache = mock(), miniAppId = TEST_MA_ID, ratDispatcher = mock(), secureStorageDispatcher = mock(), miniAppIAPVerifier = mock() ) miniAppBridge.postMessage(shareContentJsonStr) verify(bridgeExecutor).postValue(TEST_CALLBACK_ID, SUCCESS) } } @Test fun `dispatchEvent should not be called if bridge executor is not initialized`() { ActivityScenario.launch(TestActivity::class.java).onActivity { activity -> val miniAppBridge = Mockito.spy(createDefaultMiniAppMessageBridge()) // When calling miniAppBridge.createBridgeExecutor(webViewListener) itReturns bridgeExecutor miniAppBridge.updateApiClient(mock()) miniAppBridge.init( activity = activity, webViewListener = webViewListener, customPermissionCache = mock(), downloadedManifestCache = mock(), miniAppId = TEST_MA_ID, ratDispatcher = mock(), secureStorageDispatcher = mock(), miniAppIAPVerifier = mock() ) miniAppBridge.dispatchNativeEvent(NativeEventType.EXTERNAL_WEBVIEW_CLOSE, "") verify( bridgeExecutor, times(0) ).dispatchEvent(NativeEventType.EXTERNAL_WEBVIEW_CLOSE.value, "") } } @Test fun `dispatchEvent should be called if bridge executor is not initialized`() { ActivityScenario.launch(TestActivity::class.java).onActivity { activity -> val miniAppBridge = Mockito.spy(createDefaultMiniAppMessageBridge()) When calling miniAppBridge.createBridgeExecutor(webViewListener) itReturns bridgeExecutor miniAppBridge.updateApiClient(mock()) miniAppBridge.init( activity = activity, webViewListener = webViewListener, customPermissionCache = mock(), downloadedManifestCache = mock(), miniAppId = TEST_MA_ID, ratDispatcher = mock(), secureStorageDispatcher = mock(), miniAppIAPVerifier = mock() ) miniAppBridge.dispatchNativeEvent(NativeEventType.EXTERNAL_WEBVIEW_CLOSE, "") verify(bridgeExecutor).dispatchEvent(NativeEventType.EXTERNAL_WEBVIEW_CLOSE.value, "") } } @Test fun `native event type should return the correct value`() { NativeEventType.EXTERNAL_WEBVIEW_CLOSE.value shouldBeEqualTo "miniappwebviewclosed" NativeEventType.MINIAPP_ON_PAUSE.value shouldBeEqualTo "miniapppause" NativeEventType.MINIAPP_ON_RESUME.value shouldBeEqualTo "miniappresume" } @Test fun `postError should be called when cannot share content`() { ActivityScenario.launch(TestActivity::class.java).onActivity { activity -> val miniAppBridge = Mockito.spy(createMiniAppMessageBridge(false)) val errMsg = "${ErrorBridgeMessage.ERR_SHARE_CONTENT} null" val webViewListener = createErrorWebViewListener(errMsg) val bridgeExecutor = Mockito.spy(miniAppBridge.createBridgeExecutor(webViewListener)) When calling miniAppBridge.createBridgeExecutor(webViewListener) itReturns bridgeExecutor miniAppBridge.updateApiClient(mock()) miniAppBridge.init( activity = activity, webViewListener = webViewListener, customPermissionCache = mock(), downloadedManifestCache = mock(), miniAppId = TEST_MA_ID, ratDispatcher = mock(), secureStorageDispatcher = mock(), miniAppIAPVerifier = mock() ) miniAppBridge.postMessage(shareContentJsonStr) verify(bridgeExecutor).postError(TEST_CALLBACK_ID, errMsg) } } @Test fun `postValue should not be called when using default method without Activity`() { miniAppBridge.updateApiClient(mock()) miniAppBridge.init( activity = TestFilesDirActivity(), webViewListener = webViewListener, customPermissionCache = mock(), downloadedManifestCache = mock(), miniAppId = TEST_MA_ID, ratDispatcher = mock(), secureStorageDispatcher = mock(), miniAppIAPVerifier = mock() ) miniAppBridge.postMessage(shareContentJsonStr) verify(bridgeExecutor, times(0)).postValue(TEST_CALLBACK_ID, SUCCESS) } @Test fun `postValue should not be called when sharing empty content`() { val shareContentJsonStr = createShareCallbackJsonStr(" ") miniAppBridge.postMessage(shareContentJsonStr) verify(bridgeExecutor, times(0)).postValue(TEST_CALLBACK_ID, SUCCESS) } }
8
null
34
73
9111d5080f211cf3d6104a2531f4439ac3eb8bcd
7,481
android-miniapp
MIT License
libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/room/member/RoomMemberMapper.kt
element-hq
546,522,002
false
{"Kotlin": 7171042, "Shell": 34494, "Python": 30426, "JavaScript": 20003, "Java": 9607, "HTML": 9416, "CSS": 2519, "Ruby": 44}
/* * Copyright (c) 2024 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.element.android.libraries.matrix.impl.room.member import io.element.android.libraries.matrix.api.core.UserId import io.element.android.libraries.matrix.api.room.RoomMember import io.element.android.libraries.matrix.api.room.RoomMembershipState import uniffi.matrix_sdk.RoomMemberRole import org.matrix.rustcomponents.sdk.MembershipState as RustMembershipState import org.matrix.rustcomponents.sdk.RoomMember as RustRoomMember object RoomMemberMapper { fun map(roomMember: RustRoomMember): RoomMember = RoomMember( UserId(roomMember.userId), roomMember.displayName, roomMember.avatarUrl, mapMembership(roomMember.membership), roomMember.isNameAmbiguous, roomMember.powerLevel, roomMember.normalizedPowerLevel, roomMember.isIgnored, mapRole(roomMember.suggestedRoleForPowerLevel), ) fun mapRole(role: RoomMemberRole): RoomMember.Role = when (role) { RoomMemberRole.ADMINISTRATOR -> RoomMember.Role.ADMIN RoomMemberRole.MODERATOR -> RoomMember.Role.MODERATOR RoomMemberRole.USER -> RoomMember.Role.USER } fun mapMembership(membershipState: RustMembershipState): RoomMembershipState = when (membershipState) { RustMembershipState.BAN -> RoomMembershipState.BAN RustMembershipState.INVITE -> RoomMembershipState.INVITE RustMembershipState.JOIN -> RoomMembershipState.JOIN RustMembershipState.KNOCK -> RoomMembershipState.KNOCK RustMembershipState.LEAVE -> RoomMembershipState.LEAVE } }
222
Kotlin
93
769
a8db707314c68951b5b9c724bd84f4ddeed67677
2,255
element-x-android
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/SquareX.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold 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.Bold.SquareX: ImageVector get() { if (_squareX != null) { return _squareX!! } _squareX = Builder(name = "SquareX", 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) { moveToRelative(18.5f, 0.0f) lineTo(5.5f, 0.0f) curveTo(2.468f, 0.0f, 0.0f, 2.468f, 0.0f, 5.5f) verticalLineToRelative(13.0f) curveToRelative(0.0f, 3.032f, 2.468f, 5.5f, 5.5f, 5.5f) horizontalLineToRelative(13.0f) curveToRelative(3.032f, 0.0f, 5.5f, -2.468f, 5.5f, -5.5f) lineTo(24.0f, 5.5f) curveToRelative(0.0f, -3.032f, -2.468f, -5.5f, -5.5f, -5.5f) close() moveTo(21.0f, 18.5f) curveToRelative(0.0f, 1.379f, -1.121f, 2.5f, -2.5f, 2.5f) lineTo(5.5f, 21.0f) curveToRelative(-1.379f, 0.0f, -2.5f, -1.121f, -2.5f, -2.5f) lineTo(3.0f, 5.5f) curveToRelative(0.0f, -1.379f, 1.121f, -2.5f, 2.5f, -2.5f) horizontalLineToRelative(13.0f) curveToRelative(1.379f, 0.0f, 2.5f, 1.121f, 2.5f, 2.5f) verticalLineToRelative(13.0f) close() moveTo(17.661f, 7.45f) lineToRelative(-3.723f, 4.55f) lineToRelative(3.723f, 4.55f) curveToRelative(0.524f, 0.642f, 0.43f, 1.587f, -0.211f, 2.111f) curveToRelative(-0.279f, 0.228f, -0.615f, 0.339f, -0.949f, 0.339f) curveToRelative(-0.435f, 0.0f, -0.865f, -0.188f, -1.162f, -0.55f) lineToRelative(-3.339f, -4.081f) lineToRelative(-3.339f, 4.081f) curveToRelative(-0.297f, 0.362f, -0.728f, 0.55f, -1.162f, 0.55f) curveToRelative(-0.334f, 0.0f, -0.67f, -0.111f, -0.949f, -0.339f) curveToRelative(-0.641f, -0.524f, -0.735f, -1.47f, -0.211f, -2.111f) lineToRelative(3.723f, -4.55f) lineToRelative(-3.723f, -4.55f) curveToRelative(-0.524f, -0.642f, -0.43f, -1.587f, 0.211f, -2.111f) curveToRelative(0.643f, -0.523f, 1.586f, -0.43f, 2.111f, 0.211f) lineToRelative(3.339f, 4.081f) lineToRelative(3.339f, -4.081f) curveToRelative(0.525f, -0.641f, 1.469f, -0.734f, 2.111f, -0.211f) curveToRelative(0.641f, 0.524f, 0.735f, 1.47f, 0.211f, 2.111f) close() } } .build() return _squareX!! } private var _squareX: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,504
icons
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/domain/move/MoveQueryRepository.kt
ministryofjustice
292,861,912
false
null
package uk.gov.justice.digital.hmpps.pecs.jpc.move import org.springframework.beans.factory.annotation.Autowired import org.springframework.jdbc.core.JdbcTemplate import org.springframework.jdbc.core.RowMapper import org.springframework.stereotype.Component import uk.gov.justice.digital.hmpps.pecs.jpc.importer.report.Person import uk.gov.justice.digital.hmpps.pecs.jpc.location.LocationType import uk.gov.justice.digital.hmpps.pecs.jpc.price.Supplier import java.sql.ResultSet import java.sql.Timestamp import java.time.LocalDate @Component class MoveQueryRepository(@Autowired val jdbcTemplate: JdbcTemplate) { fun moveCountInDateRange(supplier: Supplier, startDate: LocalDate, endDateInclusive: LocalDate): Int { val rowMapper: RowMapper<Int> = RowMapper<Int> { resultSet: ResultSet, _: Int -> resultSet.getInt("moves_count") } return jdbcTemplate.query( "select count(move_id) as moves_count from moves " + "where move_type is not null and supplier = ? and drop_off_or_cancelled >= ? and drop_off_or_cancelled < ?", rowMapper, supplier.name, Timestamp.valueOf(startDate.atStartOfDay()), Timestamp.valueOf(endDateInclusive.plusDays(1).atStartOfDay()) )[0] } fun summariesInDateRange( supplier: Supplier, startDate: LocalDate, endDateInclusive: LocalDate, totalMoves: Int ): List<MovesSummary> { val movesSummaryRowMapper = RowMapper { resultSet: ResultSet, _: Int -> with(resultSet) { val count = getInt("moves_count") MovesSummary( moveType = MoveType.valueOfCaseInsensitive(getString("move_type")), percentage = count.toDouble() / totalMoves, volume = count, volumeUnpriced = getInt("count_unpriced"), totalPriceInPence = getInt("total_price_in_pence") ) } } val movesSummarySQL = "select m.move_type, " + " count(s.move_id) as moves_count, " + " sum(s.move_price_in_pence) as total_price_in_pence, " + " sum(s.move_unpriced) as count_unpriced " + " from MOVES m inner join (" + " select sm.move_id, " + " sum(case when j.billable then p.price_in_pence else 0 end) as move_price_in_pence, " + " max(case when p.price_in_pence is null then 1 else 0 end) as move_unpriced " + " from MOVES sm " + " left join JOURNEYS j on j.move_id = sm.move_id " + " left join LOCATIONS jfl on j.from_nomis_agency_id = jfl.nomis_agency_id " + " left join LOCATIONS jtl on j.to_nomis_agency_id = jtl.nomis_agency_id " + " left join PRICES p on jfl.location_id = p.from_location_id and jtl.location_id = p.to_location_id and j.effective_year = p.effective_year and p.supplier = ?" + " where sm.move_type is not null and sm.supplier = ? and sm.drop_off_or_cancelled >= ? and sm.drop_off_or_cancelled < ?" + " group by sm.move_id) as s on m.move_id = s.move_id " + "GROUP BY m.move_type" return jdbcTemplate.query( movesSummarySQL, movesSummaryRowMapper, supplier.name, supplier.name, Timestamp.valueOf(startDate.atStartOfDay()), Timestamp.valueOf(endDateInclusive.plusDays(1).atStartOfDay()) ) } val moveJourneySelectSQL = """ select m.move_id, m.profile_id, m.updated_at, m.supplier, m.status, m.move_type, m.reference, m.move_date, m.from_nomis_agency_id, m.to_nomis_agency_id, m.pick_up, m.drop_off_or_cancelled, m.notes, m.vehicle_registration, m.report_from_location_type, m.report_to_location_type, pp.person_id, pp.updated_at as person_updated_at, pp.prison_number, pp.first_names, pp.last_name, pp.date_of_birth, pp.latest_nomis_booking_id, pp.gender, pp.ethnicity, fl.site_name as from_site_name, fl.location_type as from_location_type, tl.site_name as to_site_name, tl.location_type as to_location_type, j.journey_id, j.effective_year, j.supplier as journey_supplier, j.client_timestamp as journey_client_timestamp, j.updated_at as journey_updated_at, j.billable, j.vehicle_registration, j.state as journey_state, j.from_nomis_agency_id as journey_from_nomis_agency_id, j.to_nomis_agency_id as journey_to_nomis_agency_id, j.pick_up as journey_pick_up, j.drop_off as journey_drop_off, j.notes as journey_notes, jfl.site_name as journey_from_site_name, jfl.location_type as journey_from_location_type, jtl.site_name as journey_to_site_name, jtl.location_type as journey_to_location_type, CASE WHEN j.billable THEN p.price_in_pence ELSE NULL END as price_in_pence from MOVES m left join PROFILES pr on m.profile_id = pr.profile_id left join PEOPLE pp on pr.person_id = pp.person_id left join LOCATIONS fl on m.from_nomis_agency_id = fl.nomis_agency_id left join LOCATIONS tl on m.to_nomis_agency_id = tl.nomis_agency_id left join JOURNEYS j on j.move_id = m.move_id left join LOCATIONS jfl on j.from_nomis_agency_id = jfl.nomis_agency_id left join LOCATIONS jtl on j.to_nomis_agency_id = jtl.nomis_agency_id left join PRICES p on jfl.location_id = p.from_location_id and jtl.location_id = p.to_location_id and j.effective_year = p.effective_year and p.supplier = ? """.trimIndent() val moveJourneyRowMapper = RowMapper { resultSet: ResultSet, _: Int -> with(resultSet) { val move = Move( moveId = getString("move_id"), profileId = getString("profile_id"), updatedAt = getTimestamp("updated_at").toLocalDateTime(), supplier = Supplier.valueOfCaseInsensitive(getString("supplier")), status = MoveStatus.valueOfCaseInsensitive(getString("status")), moveType = MoveType.valueOfCaseInsensitive(getString("move_type")), reference = getString("reference"), moveDate = getDate("move_date")?.toLocalDate(), fromNomisAgencyId = getString("from_nomis_agency_id"), fromSiteName = getString("from_site_name"), fromLocationType = getString("from_location_type")?.let { LocationType.valueOf(it) }, toNomisAgencyId = getString("to_nomis_agency_id"), toSiteName = getString("to_site_name"), toLocationType = getString("to_location_type")?.let { LocationType.valueOf(it) }, pickUpDateTime = getTimestamp("pick_up")?.toLocalDateTime(), dropOffOrCancelledDateTime = getTimestamp("drop_off_or_cancelled")?.toLocalDateTime(), notes = getString("notes"), vehicleRegistration = getString("vehicle_registration"), reportFromLocationType = getString("report_from_location_type"), reportToLocationType = getString("report_to_location_type") ) val personId = getString("person_id") val person = personId?.let { // There is a person for this move Person( personId = it, updatedAt = getTimestamp("person_updated_at").toLocalDateTime(), prisonNumber = getString("prison_number"), latestNomisBookingId = getInt("latest_nomis_booking_id"), firstNames = getString("first_names"), lastName = getString("last_name"), ethnicity = getString("ethnicity"), gender = getString("gender"), dateOfBirth = getDate("date_of_birth")?.toLocalDate() ) } val journeyId = getString("journey_id") val journey = journeyId?.let { // there is a journey for this move Journey( journeyId = it, updatedAt = getTimestamp("journey_updated_at").toLocalDateTime(), moveId = getString("move_id"), state = JourneyState.valueOfCaseInsensitive(getString("journey_state")), supplier = Supplier.valueOfCaseInsensitive(getString("journey_supplier")), clientTimeStamp = getTimestamp("journey_client_timestamp")?.toLocalDateTime(), fromNomisAgencyId = getString("journey_from_nomis_agency_id"), fromSiteName = getString("journey_from_site_name"), fromLocationType = getString("journey_from_location_type")?.let { LocationType.valueOf(it) }, toNomisAgencyId = getString("journey_to_nomis_agency_id"), toSiteName = getString("journey_to_site_name"), toLocationType = getString("journey_to_location_type")?.let { LocationType.valueOf(it) }, pickUpDateTime = getTimestamp("journey_pick_up")?.toLocalDateTime(), dropOffDateTime = getTimestamp("journey_drop_off")?.toLocalDateTime(), vehicleRegistration = getString("vehicle_registration"), billable = getBoolean("billable"), notes = getString("journey_notes"), priceInPence = if (getInt("price_in_pence") == 0 && wasNull()) null else getInt("price_in_pence"), effectiveYear = getInt("effective_year") ) } MovePersonJourney(move, person, journey) } } /** * Excludes moves without a move_type. This is an indication of bad reporting data in the JSON data feeds. */ fun moveWithPersonAndJourneys(moveId: String, supplier: Supplier): Move? { val movePersonJourney = jdbcTemplate.query( "$moveJourneySelectSQL where m.move_id = ? and m.supplier = ? and m.move_type is not null", moveJourneyRowMapper, supplier.name, moveId, supplier.name ).groupBy { it.move.moveId } val moves = movePersonJourney.keys.map { k -> movePersonJourney.getValue(k).move() } return if (moves.isEmpty()) null else moves[0] } fun movesForMoveTypeInDateRange( supplier: Supplier, moveType: MoveType, startDate: LocalDate, endDateInclusive: LocalDate, limit: Int = 50, offset: Long = 0 ): List<Move> { val movesWithPersonAndJourneys = jdbcTemplate.query( moveJourneySelectSQL + "where m.supplier = ? and m.move_type = ? and m.drop_off_or_cancelled >= ? and m.drop_off_or_cancelled < ? " + "order by m.drop_off_or_cancelled, journey_drop_off NULLS LAST ", moveJourneyRowMapper, supplier.name, supplier.name, moveType.name, Timestamp.valueOf(startDate.atStartOfDay()), Timestamp.valueOf(endDateInclusive.plusDays(1).atStartOfDay()) ).groupBy { it.move.moveId } return movesWithPersonAndJourneys.keys.map { k -> movesWithPersonAndJourneys.getValue(k).move() } } fun movesInDateRange(supplier: Supplier, startDate: LocalDate, endDateInclusive: LocalDate) = MoveType.values().map { movesForMoveTypeInDateRange(supplier, it, startDate, endDateInclusive) } class MovePersonJourney(val move: Move, val person: Person?, val journey: Journey?) fun List<MovePersonJourney>.move() = this[0].move.copy( journeys = this.mapNotNull { it.journey }, person = this[0].person ) }
3
null
2
3
f53ee728d5bea3453a5cde02d8751a13069cc335
10,846
calculate-journey-variable-payments
MIT License
app/src/main/java/com/junenine/composeTemplate/ui/theme/Themes.kt
krissirk0906
535,999,045
false
{"Kotlin": 16730}
package com.junenine.composeTemplate.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MaterialTheme.colorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable private val LightColorScheme = lightColorScheme( primary = Purple200, onPrimary = Purple500, primaryContainer = Purple700, onPrimaryContainer = Teal200, ) private val DarkColorScheme = darkColorScheme( primary = Purple200, onPrimary = Purple500, primaryContainer = Purple700, onPrimaryContainer = Teal200, ) @Composable fun AppTheme( darkTheme : Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colorScheme = if (!darkTheme) { LightColorScheme } else { DarkColorScheme } MaterialTheme( colorScheme = colorScheme, typography = typography, content = content ) }
0
Kotlin
1
1
78973d3e2fe3e178e93e639732e8cc1fc7a9cc5d
1,062
ComposeMVVMTemplate
Apache License 2.0
osmunda/src/main/java/moe/sunjiao/osmunda/model/SearchResult.kt
sun-jiao
257,820,207
false
null
package moe.sunjiao.osmunda.model import android.database.sqlite.SQLiteDatabase /** * search result of geocoder and reverse geocoder * can be converted to address * created on 4/22/2020. * * @author Sun Jiao(孙娇) * * @param lat latitude of location * @param lon longitude of location * @param name name of location * @param database database in which this element could be found * @param databaseId element id in osm data */ class SearchResult ( val lat: Double, val lon: Double, val name: String, val database: SQLiteDatabase, val databaseId: Long ){ /** * convert search result to a Address */ fun toAddress() : Address = Address(this) }
2
Kotlin
5
42
c8dbf04e8a0983254edb3910f4f4bbcf6439942d
694
Osmunda
Apache License 2.0
app/src/main/java/com/king/mvvmframe/app/adapter/SearchHistoryAdapter.kt
jenly1314
161,462,436
false
{"Kotlin": 92766, "Java": 7135, "Shell": 760}
package com.king.mvvmframe.app.adapter import android.view.LayoutInflater import android.view.View import android.widget.TextView import com.king.mvvmframe.R import com.king.mvvmframe.app.Constants import com.king.mvvmframe.bean.SearchHistory import com.king.mvvmframe.util.RandomUtil.randomColor import com.zhy.view.flowlayout.FlowLayout import com.zhy.view.flowlayout.TagAdapter /** * @author <a href="mailto:<EMAIL>">Jenly</a> * <p> * <a href="https://github.com/jenly1314">Follow me</a> */ class SearchHistoryAdapter(datas: MutableList<SearchHistory>?) : TagAdapter<SearchHistory>(datas) { override fun getView(parent: FlowLayout, position: Int, data: SearchHistory): View? { val tv = LayoutInflater.from(parent.context) .inflate(R.layout.search_history_item, parent, false) as TextView tv.text = data.word tv.setTextColor(randomColor(Constants.COLOR_RGB_MIN, Constants.COLOR_RGB_MAX)) return tv } }
0
Kotlin
53
362
bda62f6da0e506849686247bb53b6ae4670bf7ae
962
MVVMFrame
MIT License
app/src/main/java/com/tomg/githubreleasemonitor/main/data/GitHubRepository.kt
Tommy-Geenexus
275,373,591
false
null
/* * Copyright (c) 2020-2022, <NAME> (<EMAIL>) * * 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.tomg.githubreleasemonitor.main.data import android.os.Parcelable import androidx.annotation.Keep import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.tomg.githubreleasemonitor.Empty import kotlinx.parcelize.Parcelize @Keep @Entity @Parcelize data class GitHubRepository( @PrimaryKey val id: String = String.Empty, val owner: String = String.Empty, val name: String = String.Empty, @ColumnInfo(name = "author_avatar_url") val authorAvatarUrl: String = String.Empty, @ColumnInfo(name = "author_html_url") val authorHtmlUrl: String = String.Empty, @ColumnInfo(name = "latest_release_html_url") val latestReleaseHtmlUrl: String = String.Empty, @ColumnInfo(name = "latest_release_name") val latestReleaseName: String = String.Empty, @ColumnInfo(name = "latest_release_timestamp") val latestReleaseTimestamp: String = String.Empty ) : Parcelable
2
null
2
2
a42c6cd7ba2f8b8fc150048582ba3bbd68c48f94
2,057
gh-release-monitor
MIT License