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
cekrek/src/main/java/id/zelory/cekrek/extension/ViewExt.kt
zetbaitsu
284,382,545
false
null
package id.zelory.cekrek.extension import android.graphics.Bitmap import android.view.View import id.zelory.cekrek.Cekrek import id.zelory.cekrek.config.CekrekConfig import id.zelory.cekrek.config.CekrekImageFileConfig import java.io.File /** * Created on : August 02, 2020 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ fun View.cekrekToBitmap(config: CekrekConfig): Bitmap { return Cekrek.toBitmap(this, config) } @JvmOverloads fun View.cekrekToBitmap(configPatch: CekrekConfig.() -> Unit = {}): Bitmap { return cekrekToBitmap(CekrekConfig().apply(configPatch)) } fun View.cekrekToImageFile(config: CekrekImageFileConfig): File { return Cekrek.toImageFile(this, config) } @JvmOverloads fun View.cekrekToImageFile( destination: File, configPatch: CekrekImageFileConfig.() -> Unit = {} ): File { return cekrekToImageFile(CekrekImageFileConfig(destination).apply(configPatch)) }
0
Kotlin
10
94
e1d98c1df9b489890c18ece0f619160ddabcb5b0
957
Cekrek
Apache License 2.0
feature_feed/src/main/kotlin/ru/razrabs/feature_feed/data/FeedCacheImpl.kt
razrabs-media
526,204,757
false
{"Kotlin": 155001, "JavaScript": 139465, "CSS": 5916, "HTML": 1062}
package ru.razrabs.feature_feed.data import org.koin.core.annotation.Single import ru.razrabs.feature_feed.domain.FeedCache import ru.razrabs.network.models.front_page.FrontPage import ru.razrabs.network.models.post.Post @Single class FeedCacheImpl: FeedCache { override var frontPage: FrontPage? = null private val postMap = HashMap<String, Post>() override fun savePost(post: Post) { postMap[post.uid] = post } override fun getPost(postUid: String): Post? { return postMap[postUid] } }
16
Kotlin
1
9
05391253a150d30203f98bdf772783fddbea22b5
532
journal-android
MIT License
src/test/kotlin/com/exactpro/th2/codec/xml/XmlAttributeTest.kt
th2-net
407,058,570
false
{"Kotlin": 73896, "Dockerfile": 283}
/* * Copyright 2021-2022 Exactpro (Exactpro Systems Limited) * 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.exactpro.th2.codec.xml import com.exactpro.th2.codec.xml.utils.XmlTest import com.exactpro.th2.codec.xml.utils.parsedMessage import com.exactpro.th2.common.message.addField import com.exactpro.th2.common.message.addFields import com.exactpro.th2.common.message.message import org.junit.jupiter.api.Test class XmlAttributeTest : XmlTest() { @Test fun `test attributes fields`() { val xml = """<TestAttrMessage> <b> <c> <d> <e f="123" g="1">asd</e> </d> </c> </b> <b> <c> <d> <e f="456" g="2" n="48">fgh</e> <h>A</h> </d> </c> </b> <b> <c> <d> <e f="789" g="3">fgh</e> </d> </c> </b> </TestAttrMessage> """.trimIndent() val msg = parsedMessage("TestAttrMessage").addFields( "TestAttrMessage", message().apply { addField("b", listOf(message().apply { addField("c", message().apply { addField("d", message().apply { addField("e", message().apply { addFields("-f", "123") addFields("-g", "1") addFields("#text", "asd") }) }) }) }, message().apply { addField("c", message().apply { addField("d", message().apply { addField("e", message().apply { addFields("-f", "456") addFields("-g", "2") addFields("-n", "48") addFields("#text", "fgh") }) addField("h", "A") }) }) }, message().apply { addField("c", message().apply { addField("d", message().apply { addField("e", message().apply { addFields("-f", "789") addFields("-g", "3") addFields("#text", "fgh") }) }) }) })) }, ) checkDecode( xml, msg ) } @Test fun `test decode attrs in different places`() { val xml = """ <Attributes defaultMsgAttrA="123" msgAttrA="45" msgAttrB="67"> <commonWithAttrs commonAttrA="54" commonAttrB="76">abc</commonWithAttrs> <withAttrs defaultFieldAttrA="456" fieldAttrA="10" fieldAttrB="30">def</withAttrs> </Attributes> """.trimIndent() val msg = parsedMessage("Attributes").addFields( "Attributes", message().apply { addFields("-defaultMsgAttrA", "123", "-msgAttrA", "45", "-msgAttrB", "67", "commonWithAttrs", message().apply { addField("-commonAttrA", "54") addField("-commonAttrB", "76") addField("#text", "abc") }, "withAttrs", message().apply { addField("-defaultFieldAttrA", "456") addField("-fieldAttrA", "10") addField("-fieldAttrB", "30") addField("#text", "def") } ) } ) checkDecode( xml, msg ) } @Test fun `test encode attrs in different place`() { val xml = """ <Attributes defaultMsgAttrA="123" msgAttrA="45" msgAttrB="67"> <commonWithAttrs commonAttrA="54" commonAttrB="76">abc</commonWithAttrs> <withAttrs defaultFieldAttrA="456" fieldAttrA="10" fieldAttrB="30">def</withAttrs> </Attributes> """.trimIndent() val msg = parsedMessage("Attributes").apply { addField("Attributes", message().apply { addFields("-defaultMsgAttrA", "123", "-msgAttrA", "45", "-msgAttrB", "67", "commonWithAttrs", message().apply { addField("-commonAttrA", "54") addField("-commonAttrB", "76") addField("#text", "abc") }, "withAttrs", message().apply { addField("-defaultFieldAttrA", "456") addField("-fieldAttrA", "10") addField("-fieldAttrB", "30") addField("#text", "def") } ) }) } checkEncode( xml, msg ) } }
1
Kotlin
1
0
a9c35fd786dba9ac8059660ddfe5bbbb9b0861fe
6,014
th2-codec-xml-via-xsd
Apache License 2.0
frontend/actor/src/commonMain/kotlin/actor/ShapeActor.kt
85vmh
543,628,296
false
{"Kotlin": 956103, "C++": 75148, "Java": 7157, "Makefile": 2742, "HTML": 419, "Shell": 398, "CSS": 108}
package actor interface ShapeActor : CanvasActor { }
0
Kotlin
1
3
5cf42426895ba8691c9b53ba1b97c274bbdabc07
54
mindovercnclathe
Apache License 2.0
frontend/actor/src/commonMain/kotlin/actor/ShapeActor.kt
85vmh
543,628,296
false
{"Kotlin": 956103, "C++": 75148, "Java": 7157, "Makefile": 2742, "HTML": 419, "Shell": 398, "CSS": 108}
package actor interface ShapeActor : CanvasActor { }
0
Kotlin
1
3
5cf42426895ba8691c9b53ba1b97c274bbdabc07
54
mindovercnclathe
Apache License 2.0
src/main/java/com/example/navigation/ui/bottomnav/NavigationUiBottomNavSettingsFragment.kt
vshpyrka
754,325,488
false
{"Kotlin": 192615}
package com.example.navigation.ui.bottomnav import android.os.Bundle import android.view.View import androidx.fragment.app.Fragment import com.example.navigation.R import com.example.navigation.databinding.FragmentNavigationUiBottomNavSettingsBinding import com.example.navigation.getLoremIpsum class NavigationUiBottomNavSettingsFragment : Fragment( R.layout.fragment_navigation_ui_bottom_nav_settings ) { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val binding = FragmentNavigationUiBottomNavSettingsBinding.bind(view) binding.text.text = getLoremIpsum() } }
0
Kotlin
0
0
c750297e8a941c6632dff9263d60fbe8d8baaa70
672
android-navigation-example
Apache License 2.0
app/src/main/java/com/keepcoding/instagramparapobres/session/Session.kt
jsmdev
374,087,040
false
null
package com.keepcoding.instagramparapobres.session data class Session(val accessToken: String, val accountName: String)
0
Kotlin
0
0
90cc840e15a42e51ac4b00aea4971024e2e91e34
121
xi-bootcamp-mobile-android-advanced
MIT License
home/src/main/java/com/topview/purejoy/home/data/bean/BannerJson.kt
giagor
421,858,760
false
{"Kotlin": 800571, "AIDL": 3111}
package com.topview.purejoy.home.data.bean class BannerJson { var banners: MutableList<Banner>? = null class Banner { var pic: String? = null var url: String? = null } }
1
Kotlin
1
5
f58ca9570486871066d99fc5e0827af66d6f0c3b
199
PureJoy
MIT License
app/src/main/java/com/example/MainActivity.kt
caohuisheng
628,598,132
false
null
package com.example import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.ImageButton import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.example.entity.Temp import com.example.ui.Adapter.TempAdapter import java.util.* import kotlin.collections.ArrayList /*List<String> xDataList = new ArrayList<>();// x轴数据源 List<Entry> yDataList = new ArrayList<>();// y轴数据数据源 //给上面的X、Y轴数据源做假数据测试 for (int i = 0; i < 24; i++) { // x轴显示的数据 xDataList.add(i + ":00"); //y轴生成float类型的随机数 float value = (float) (Math.random() * range) + 3; yDataList.add(new Entry(value, i)); } //显示图表,参数( 上下文,图表对象, X轴数据,Y轴数据,图表标题,曲线图例名称,坐标点击弹出提示框中数字单位) ChartUtil.showChart(this, lineChart, xDataList, yDataList, "供热趋势图", "供热量/时间","kw/h");*/ class MainActivity : StatusBar() { private lateinit var btn_control_car:ImageButton; override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) //cancelTitle() setContentView(R.layout.activity_main) val lv:RecyclerView = findViewById(R.id.lv_main) as RecyclerView; val btn_update:Button = findViewById(R.id.btn_update) val tempList = ArrayList<Temp>() for(i in 1..10){ tempList.add(Temp("name"+i,true,18,36f, Date(System.currentTimeMillis()))) } val layoutManager = LinearLayoutManager(this) lv.layoutManager = layoutManager Log.e("TAG","size"+tempList.size) lv.adapter = TempAdapter(this,tempList) } }
0
Kotlin
0
0
420da132e26eec8a02293deed4353748e05e3bf7
1,617
TemperatureCar
Apache License 2.0
plugins/gradle-dsl-impl/src/com/android/tools/idea/gradle/dsl/parser/dependencies/GradleDependenciesComparator.kt
dai-pei
316,296,645
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.android.tools.idea.gradle.dsl.parser.dependencies private val KNOWN_CONFIGURATIONS_IN_ORDER = listOf( "feature", "api", "implementation", "compile", "testApi", "testImplementation", "testCompile", "androidTestApi", "androidTestImplementation", "androidTestCompile", "androidTestUtil") /** * Defined an ordering on gradle configuration names. */ @JvmField val CONFIGURATION_ORDERING = compareBy<String> { val result = KNOWN_CONFIGURATIONS_IN_ORDER.indexOf(it) if (result != -1) result else KNOWN_CONFIGURATIONS_IN_ORDER.size }.thenBy { it }
1
null
1
1
adb89951109732e585d04f33e3fabbc9f9d3b256
708
intellij-community
Apache License 2.0
compose/ui/ui/src/uikitMain/kotlin/androidx/compose/ui/platform/UIKitTextInputService.uikit.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.platform import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.InternalKeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.type import androidx.compose.ui.scene.getConstraintsToFillParent import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.input.CommitTextCommand import androidx.compose.ui.text.input.EditCommand import androidx.compose.ui.text.input.EditProcessor import androidx.compose.ui.text.input.FinishComposingTextCommand import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeOptions import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.PlatformTextInputService import androidx.compose.ui.text.input.SetComposingRegionCommand import androidx.compose.ui.text.input.SetComposingTextCommand import androidx.compose.ui.text.input.SetSelectionCommand import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.asCGRect import androidx.compose.ui.unit.toDpRect import androidx.compose.ui.unit.toOffset import androidx.compose.ui.window.FocusStack import androidx.compose.ui.window.IntermediateTextInputUIView import kotlin.math.absoluteValue import kotlin.math.min import kotlinx.coroutines.MainScope import kotlinx.coroutines.launch import org.jetbrains.skia.BreakIterator import platform.UIKit.NSLayoutConstraint import platform.UIKit.UIPress import platform.UIKit.UIView import platform.UIKit.reloadInputViews internal class UIKitTextInputService( private val updateView: () -> Unit, private val rootViewProvider: () -> UIView, private val densityProvider: () -> Density, private val viewConfiguration: ViewConfiguration, private val focusStack: FocusStack<UIView>?, /** * Callback to handle keyboard presses. The parameter is a [Set] of [UIPress] objects. * Erasure happens due to K/N not supporting Obj-C lightweight generics. */ private val onKeyboardPresses: (Set<*>) -> Unit, ) : PlatformTextInputService, TextToolbar { private val rootView get() = rootViewProvider() private var currentInput: CurrentInput? = null private var currentImeOptions: ImeOptions? = null private var currentImeActionHandler: ((ImeAction) -> Unit)? = null private var textUIView: IntermediateTextInputUIView? = null private var textLayoutResult : TextLayoutResult? = null /** * Workaround to prevent calling textWillChange, textDidChange, selectionWillChange, and * selectionDidChange when the value of the current input is changed by the system (i.e., by the user * input) not by the state change of the Compose side. These 4 functions call methods of * UITextInputDelegateProtocol, which notifies the system that the text or the selection of the * current input has changed. * * This is to properly handle multi-stage input methods that depend on text selection, required by * languages such as Korean (Chinese and Japanese input methods depend on text marking). The writing * system of these languages contains letters that can be broken into multiple parts, and each keyboard * key corresponds to those parts. Therefore, the input system holds an internal state to combine these * parts correctly. However, the methods of UITextInputDelegateProtocol reset this state, resulting in * incorrect input. (e.g., 컴포즈 becomes ㅋㅓㅁㅍㅗㅈㅡ when not handled properly) * * @see _tempCurrentInputSession holds the same text and selection of the current input. It is used * instead of the old value passed to updateState. When the current value change is due to the * user input, updateState is not effective because _tempCurrentInputSession holds the same value. * However, when the current value change is due to the change of the user selection or to the * state change in the Compose side, updateState calls the 4 methods because the new value holds * these changes. */ private var _tempCurrentInputSession: EditProcessor? = null /** * Workaround to prevent IME action from being called multiple times with hardware keyboards. * When the hardware return key is held down, iOS sends multiple newline characters to the application, * which makes UIKitTextInputService call the current IME action multiple times without an additional * debouncing logic. * * @see _tempHardwareReturnKeyPressed is set to true when the return key is pressed with a * hardware keyboard. * @see _tempImeActionIsCalledWithHardwareReturnKey is set to true when the * current IME action has been called within the current hardware return key press. */ private var _tempHardwareReturnKeyPressed: Boolean = false private var _tempImeActionIsCalledWithHardwareReturnKey: Boolean = false /** * Workaround to fix voice dictation. * UIKit call insertText(text) and replaceRange(range,text) immediately, * but Compose recomposition happen on next draw frame. * So the value of getSelectedTextRange is in the old state when the replaceRange function is called. * @see _tempCursorPos helps to fix this behaviour. Permanently update _tempCursorPos in function insertText. * And after clear in updateState function. */ private var _tempCursorPos: Int? = null private val mainScope = MainScope() override fun startInput( value: TextFieldValue, imeOptions: ImeOptions, onEditCommand: (List<EditCommand>) -> Unit, onImeActionPerformed: (ImeAction) -> Unit ) { currentInput = CurrentInput(value, onEditCommand) _tempCurrentInputSession = EditProcessor().apply { reset(value, null) } currentImeOptions = imeOptions currentImeActionHandler = onImeActionPerformed attachIntermediateTextInputView() textUIView?.input = createSkikoInput(value) textUIView?.inputTraits = getUITextInputTraits(imeOptions) showSoftwareKeyboard() } override fun stopInput() { currentInput = null _tempCurrentInputSession = null currentImeOptions = null currentImeActionHandler = null hideSoftwareKeyboard() textUIView?.inputTraits = EmptyInputTraits textUIView?.input = null detachIntermediateTextInputView() } override fun showSoftwareKeyboard() { textUIView?.let { focusStack?.pushAndFocus(it) } } override fun hideSoftwareKeyboard() { textUIView?.let { focusStack?.popUntilNext(it) } } override fun updateState(oldValue: TextFieldValue?, newValue: TextFieldValue) { val internalOldValue = _tempCurrentInputSession?.toTextFieldValue() val textChanged = internalOldValue == null || internalOldValue.text != newValue.text val selectionChanged = textChanged || internalOldValue == null || internalOldValue.selection != newValue.selection if (textChanged) { textUIView?.textWillChange() } if (selectionChanged) { textUIView?.selectionWillChange() } _tempCurrentInputSession?.reset(newValue, null) currentInput?.let { input -> input.value = newValue _tempCursorPos = null } if (textChanged) { textUIView?.textDidChange() } if (selectionChanged) { textUIView?.selectionDidChange() } if (textChanged || selectionChanged) { updateView() textUIView?.reloadInputViews() } } fun onPreviewKeyEvent(event: InternalKeyEvent): Boolean { return when (event.key) { Key.Enter -> handleEnterKey(event) Key.Backspace -> handleBackspace(event) else -> false } } override fun updateTextLayoutResult( textFieldValue: TextFieldValue, offsetMapping: OffsetMapping, textLayoutResult: TextLayoutResult, textFieldToRootTransform: (Matrix) -> Unit, innerTextFieldBounds: Rect, decorationBoxBounds: Rect ) { super.updateTextLayoutResult( textFieldValue, offsetMapping, textLayoutResult, textFieldToRootTransform, innerTextFieldBounds, decorationBoxBounds ) this.textLayoutResult = textLayoutResult } private fun handleEnterKey(event: InternalKeyEvent): Boolean { _tempImeActionIsCalledWithHardwareReturnKey = false return when (event.type) { KeyEventType.KeyUp -> { _tempHardwareReturnKeyPressed = false false } KeyEventType.KeyDown -> { _tempHardwareReturnKeyPressed = true // This prevents two new line characters from being added for one hardware return key press. true } else -> false } } private fun handleBackspace(event: InternalKeyEvent): Boolean { // This prevents two characters from being removed for one hardware backspace key press. return event.type == KeyEventType.KeyDown } private fun sendEditCommand(vararg commands: EditCommand) { val commandList = commands.toList() _tempCurrentInputSession?.apply(commandList) currentInput?.let { input -> input.onEditCommand(commandList) } } private fun getCursorPos(): Int? { if (_tempCursorPos != null) { return _tempCursorPos } val selection = getState()?.selection if (selection != null && selection.start == selection.end) { return selection.start } return null } private fun imeActionRequired(): Boolean = currentImeOptions?.run { singleLine || ( imeAction != ImeAction.None && imeAction != ImeAction.Default && !(imeAction == ImeAction.Search && _tempHardwareReturnKeyPressed) ) } ?: false private fun runImeActionIfRequired(): Boolean { val imeAction = currentImeOptions?.imeAction ?: return false val imeActionHandler = currentImeActionHandler ?: return false if (!imeActionRequired()) { return false } if (!_tempImeActionIsCalledWithHardwareReturnKey) { if (imeAction == ImeAction.Default) { imeActionHandler(ImeAction.Done) } else { imeActionHandler(imeAction) } } if (_tempHardwareReturnKeyPressed) { _tempImeActionIsCalledWithHardwareReturnKey = true } return true } private fun getState(): TextFieldValue? = currentInput?.value override fun showMenu( rect: Rect, onCopyRequested: (() -> Unit)?, onPasteRequested: (() -> Unit)?, onCutRequested: (() -> Unit)?, onSelectAllRequested: (() -> Unit)? ) { if (textUIView == null) { // If showMenu() is called and textUIView is not created, // then it means that showMenu() called in SelectionContainer without any textfields, // and IntermediateTextInputView must be created to show an editing menu attachIntermediateTextInputView() updateView() } textUIView?.showTextMenu( targetRect = rect.toDpRect(densityProvider()).asCGRect(), textActions = object : TextActions { override val copy: (() -> Unit)? = onCopyRequested override val cut: (() -> Unit)? = onCutRequested override val paste: (() -> Unit)? = onPasteRequested override val selectAll: (() -> Unit)? = onSelectAllRequested } ) } /** * TODO on UIKit native behaviour is hide text menu, when touch outside */ override fun hide() { textUIView?.hideTextMenu() if ((textUIView != null) && (currentInput == null)) { // means that editing context menu shown in selection container textUIView?.resignFirstResponder() detachIntermediateTextInputView() } } override val status: TextToolbarStatus get() = if (textUIView?.isTextMenuShown() == true) TextToolbarStatus.Shown else TextToolbarStatus.Hidden private fun attachIntermediateTextInputView() { textUIView?.removeFromSuperview() textUIView = IntermediateTextInputUIView( viewConfiguration = viewConfiguration ).also { it.onKeyboardPresses = onKeyboardPresses rootView.addSubview(it) it.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activateConstraints( getConstraintsToFillParent(it, rootView) ) } } private fun detachIntermediateTextInputView() { textUIView?.let { view -> view.resetOnKeyboardPressesCallback() mainScope.launch { view.removeFromSuperview() } } textUIView = null } private fun createSkikoInput(value: TextFieldValue) = object : IOSSkikoInput { private var floatingCursorTranslation : Offset? = null override fun beginFloatingCursor(offset: DpOffset) { val cursorPos = getCursorPos() ?: getState()?.selection?.start ?: return val cursorRect = textLayoutResult?.getCursorRect(cursorPos) ?: return floatingCursorTranslation = cursorRect.center - offset.toOffset(densityProvider()) } override fun updateFloatingCursor(offset: DpOffset) { val translation = floatingCursorTranslation ?: return val offsetPx = offset.toOffset(densityProvider()) val pos = textLayoutResult ?.getOffsetForPosition(offsetPx + translation) ?: return sendEditCommand(SetSelectionCommand(pos, pos)) } override fun endFloatingCursor() { floatingCursorTranslation = null } /** * A Boolean value that indicates whether the text-entry object has any text. * https://developer.apple.com/documentation/uikit/uikeyinput/1614457-hastext */ override fun hasText(): Boolean = getState()?.text?.isNotEmpty() ?: false /** * Inserts a character into the displayed text. * Add the character text to your class’s backing store at the index corresponding to the cursor and redisplay the text. * https://developer.apple.com/documentation/uikit/uikeyinput/1614543-inserttext * @param text A string object representing the character typed on the system keyboard. */ override fun insertText(text: String) { if (text == "\n") { if (runImeActionIfRequired()) { return } } getCursorPos()?.let { _tempCursorPos = it + text.length } sendEditCommand(CommitTextCommand(text, 1)) } /** * Deletes a character from the displayed text. * Remove the character just before the cursor from your class’s backing store and redisplay the text. * https://developer.apple.com/documentation/uikit/uikeyinput/1614572-deletebackward */ override fun deleteBackward() { // Before this function calls, iOS changes selection in setSelectedTextRange. // All needed characters should be allready selected, and we can just remove them. sendEditCommand( CommitTextCommand("", 0) ) } /** * The text position for the end of a document. * https://developer.apple.com/documentation/uikit/uitextinput/1614555-endofdocument */ override fun endOfDocument(): Long = getState()?.text?.length?.toLong() ?: 0L /** * The range of selected text in a document. * If the text range has a length, it indicates the currently selected text. * If it has zero length, it indicates the caret (insertion point). * If the text-range object is nil, it indicates that there is no current selection. * https://developer.apple.com/documentation/uikit/uitextinput/1614541-selectedtextrange */ override fun getSelectedTextRange(): IntRange? { val cursorPos = getCursorPos() if (cursorPos != null) { return cursorPos until cursorPos } val selection = getState()?.selection return if (selection != null) { selection.start until selection.end } else { null } } override fun setSelectedTextRange(range: IntRange?) { if (range != null) { sendEditCommand( SetSelectionCommand(range.start, range.endInclusive + 1) ) } else { sendEditCommand( SetSelectionCommand(endOfDocument().toInt(), endOfDocument().toInt()) ) } } override fun selectAll() { sendEditCommand( SetSelectionCommand(0, endOfDocument().toInt()) ) } /** * Returns the text in the specified range. * https://developer.apple.com/documentation/uikit/uitextinput/1614527-text * @param range A range of text in a document. * @return A substring of a document that falls within the specified range. */ override fun textInRange(range: IntRange): String { val text = getState()?.text return text?.substring(range.first, min(range.last + 1, text.length)) ?: "" } /** * Replaces the text in a document that is in the specified range. * https://developer.apple.com/documentation/uikit/uitextinput/1614558-replace * @param range A range of text in a document. * @param text A string to replace the text in range. */ override fun replaceRange(range: IntRange, text: String) { sendEditCommand( SetComposingRegionCommand(range.start, range.endInclusive + 1), SetComposingTextCommand(text, 1), FinishComposingTextCommand(), ) } /** * Inserts the provided text and marks it to indicate that it is part of an active input session. * Setting marked text either replaces the existing marked text or, * if none is present, inserts it in place of the current selection. * https://developer.apple.com/documentation/uikit/uitextinput/1614465-setmarkedtext * @param markedText The text to be marked. * @param selectedRange A range within markedText that indicates the current selection. * This range is always relative to markedText. */ override fun setMarkedText(markedText: String?, selectedRange: IntRange) { if (markedText != null) { sendEditCommand( SetComposingTextCommand(markedText, 1) ) } } /** * The range of currently marked text in a document. * If there is no marked text, the value of the property is nil. * Marked text is provisionally inserted text that requires user confirmation; * it occurs in multistage text input. * The current selection, which can be a caret or an extended range, always occurs within the marked text. * https://developer.apple.com/documentation/uikit/uitextinput/1614489-markedtextrange */ override fun markedTextRange(): IntRange? { val composition = getState()?.composition return if (composition != null) { composition.start until composition.end } else { null } } /** * Unmarks the currently marked text. * After this method is called, the value of markedTextRange is nil. * https://developer.apple.com/documentation/uikit/uitextinput/1614512-unmarktext */ override fun unmarkText() { sendEditCommand(FinishComposingTextCommand()) } /** * Returns the text position at a specified offset from another text position. * Returned value must be in range between 0 and length of text (inclusive). */ override fun positionFromPosition(position: Long, offset: Long): Long { val text = getState()?.text ?: return 0 if (position + offset >= text.lastIndex + 1) { return (text.lastIndex + 1).toLong() } if (position + offset <= 0) { return 0 } var resultPosition = position.toInt() val iterator = BreakIterator.makeCharacterInstance() iterator.setText(text) repeat(offset.absoluteValue.toInt()) { val iteratorResult = if (offset > 0) { iterator.following(resultPosition) } else { iterator.preceding(resultPosition) } if (iteratorResult == BreakIterator.DONE) { return resultPosition.toLong() } else { resultPosition = iteratorResult } } return resultPosition.toLong() } } } private data class CurrentInput( var value: TextFieldValue, val onEditCommand: (List<EditCommand>) -> Unit )
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
22,864
compose
Apache License 2.0
src/y2017/Day21.kt
gaetjen
572,857,330
false
{"Kotlin": 420343, "Mermaid": 571}
package y2017 import util.readInput import util.timingStatistics object Day21 { val start = listOf(".#.", "..#", "###") private fun parse(input: List<String>): Map<List<String>, List<String>> { return input.flatMap { line -> val (lh, rh) = line.split(" => ") val output = rh.split("/") flipAndRotate(lh).map { it to output } }.toMap() } private fun flipAndRotate(input: String): List<List<String>> { val inputGrid = input.split("/") val variants = listOf( inputGrid, inputGrid.reversed(), inputGrid.map { it.reversed() }, inputGrid.reversed().map { it.reversed() }, (inputGrid.indices.reversed()).map { col -> inputGrid.indices.map { row -> inputGrid[row][col] }.joinToString("") }, (inputGrid.indices).map { col -> inputGrid.indices.map { row -> inputGrid[row][col] }.joinToString("") }, (inputGrid.indices).map { col -> inputGrid.indices.reversed().map { row -> inputGrid[row][col] }.joinToString("") }, (inputGrid.indices.reversed()).map { col -> inputGrid.indices.reversed().map { row -> inputGrid[row][col] }.joinToString("") } ) return variants } fun part1( input: List<String>, iterations: Int ): Int { val rules = parse(input) var image = start repeat(iterations) { val chunks = if (image.size % 2 == 0) { imageChunks(2, image) } else { imageChunks(3, image) } val newChunks = chunks.map { chunkRow -> chunkRow.map { rules[it] ?: error("missing rule for $it") } } image = stitch(newChunks) } return image.joinToString("").count { it == '#' } } private fun stitch(imageChunks: List<List<List<String>>>): List<String> { return imageChunks.flatMap { row -> row.first().indices.map { rowOffset -> row.joinToString("") { it[rowOffset] } } } } private fun imageChunks( chunkSize: Int, imageGrid: List<String> ): List<List<List<String>>> { return (0..<imageGrid.size / chunkSize).map { row -> (0..<imageGrid.size / chunkSize).map { col -> (0..<chunkSize).map { rowOffset -> (0..<chunkSize).map { colOffset -> imageGrid[row * chunkSize + rowOffset][col * chunkSize + colOffset] }.joinToString("") } } } } } fun main() { val testInput = """ ../.# => ##./#../... .#./..#/### => #..#/..../..../#..# """.trimIndent().split("\n") println("------Tests------") println(Day21.part1(testInput, 2)) println("------Real------") val input = readInput(2017, 21) println("Part 1 result: ${Day21.part1(input, 5)}") println("Part 2 result: ${Day21.part1(input, 18)}") timingStatistics { Day21.part1(input, 5) } timingStatistics { Day21.part1(input, 18) } }
0
Kotlin
0
0
d1404159148b683fe456a9ed61f8ff735426d42e
3,217
advent-of-code
Apache License 2.0
app/src/main/java/com/example/simplecleanarchitecture/MainApplication.kt
tom2048
350,885,111
false
null
package com.example.simplecleanarchitecture import android.app.Application import com.example.simplecleanarchitecture.core.lib.di.AppSchedulers import com.example.simplecleanarchitecture.core.lib.di.AppSchedulersDefault import com.example.simplecleanarchitecture.core.lib.resources.AppResources import com.example.simplecleanarchitecture.core.lib.resources.AppResourcesDefault import com.example.simplecleanarchitecture.core.repository.AssetsRepository import com.example.simplecleanarchitecture.core.repository.AssetsRepositoryMemory import com.example.simplecleanarchitecture.core.repository.UsersRepository import com.example.simplecleanarchitecture.core.repository.UsersRepositoryMemory import com.example.simplecleanarchitecture.users.ui.passwordchange.UserPasswordChangeViewModel import com.example.simplecleanarchitecture.users.ui.useredit.UserEditViewModel import com.example.simplecleanarchitecture.users.ui.userlist.UserListViewModel import com.example.simplecleanarchitecture.users.usecase.user.* import com.github.terrakok.cicerone.Cicerone import com.github.terrakok.cicerone.NavigatorHolder import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.context.startKoin import org.koin.dsl.module class MainApplication : Application() { override fun onCreate() { super.onCreate() startKoin { androidContext(this@MainApplication) modules( listOf( viewModelModule(), repositoryModule(), useCaseModule(), navigationModule(), otherModule() ) ) } } private fun viewModelModule() = module { viewModel { UserListViewModel(get(), get(), get(), get()) } viewModel { UserEditViewModel(get(), get(), get(), get()) } viewModel { UserPasswordChangeViewModel(get(), get(), get()) } } private fun repositoryModule() = module { single<UsersRepository> { UsersRepositoryMemory(get()) } single<AssetsRepository> { AssetsRepositoryMemory(get()) } } private fun useCaseModule() = module { single<UserShowListUseCase> { UserShowListUseCaseDefault(get()) } single<UserShowDetailsUseCase> { UserShowDetailsUseCaseDefault(get(), get()) } single<UserUpdateUseCase> { UserUpdateUseCaseDefault(get(), get(), get()) } single<UserDeleteUseCase> { UserDeleteUseCaseDefault(get()) } single<UserPasswordUpdateUseCase> { UserPasswordUpdateUseCaseDefault(get()) } } private fun navigationModule() = module { single<Cicerone<MainRouter>> { Cicerone.create(MainRouter()) } factory<MainRouter> { get<Cicerone<MainRouter>>().router } factory<NavigatorHolder> { get<Cicerone<MainRouter>>().getNavigatorHolder() } } private fun otherModule() = module { single<AppResources> { AppResourcesDefault(get()) } single<AppSchedulers> { AppSchedulersDefault() } } }
0
Kotlin
0
1
0d416936071ad0ede169434e70f1a1cf3ccf76d4
3,057
simple-clean-architecture-android-example
MIT License
src/main/java/com/silverhetch/vesta/tag/Tag.kt
LarryHsiao
164,227,499
false
null
package com.silverhetch.vesta.tag /** * Tag that contents information */ interface Tag { fun id(): Long /** * The name of this tag */ fun name(): String /** * Delete this tag. */ fun delete() }
5
Kotlin
1
1
5795894581bf205518a8dcca48cd1d3ca240d372
237
Vesta
MIT License
petblocks-sponge-plugin/src/main/java/com/github/shynixn/petblocks/sponge/logic/business/listener/InventoryListener.kt
Tominous
180,851,910
true
{"Kotlin": 1474097, "Shell": 2544}
@file:Suppress("CAST_NEVER_SUCCEEDS", "unused") package com.github.shynixn.petblocks.sponge.logic.business.listener import com.github.shynixn.petblocks.api.business.service.GUIService import com.github.shynixn.petblocks.api.business.service.ProxyService import com.github.shynixn.petblocks.sponge.logic.business.extension.updateInventory import com.google.inject.Inject import org.spongepowered.api.entity.living.player.Player import org.spongepowered.api.event.Listener import org.spongepowered.api.event.filter.cause.First import org.spongepowered.api.event.item.inventory.ClickInventoryEvent import org.spongepowered.api.event.network.ClientConnectionEvent import org.spongepowered.api.item.ItemTypes import org.spongepowered.api.item.inventory.property.SlotIndex /** * Handles clicking into the PetBlocks GUI. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class InventoryListener @Inject constructor(private val guiService: GUIService, private val proxyService: ProxyService) { /** * Gets called to handle actions to the inventory. */ @Listener fun playerClickInInventoryEvent(event: ClickInventoryEvent, @First(typeFilter = [Player::class]) player: Player) { if (!guiService.isGUIInventory(event.targetInventory)) { return } if (event.transactions.isEmpty()) { return } val currentItemStack = event.transactions[0].original.createStack() if (currentItemStack.type == ItemTypes.AIR) { return } event.isCancelled = true player.inventory.updateInventory() val slot = event.transactions[0].slot.getProperties(SlotIndex::class.java).toTypedArray()[0].value!! guiService.clickInventoryItem(player, slot, currentItemStack) } /** * Gets called to handle cleaning up remaining resources. */ @Listener fun playerQuitEvent(event: ClientConnectionEvent.Disconnect) { guiService.cleanResources(event.targetEntity) proxyService.cleanResources(event.targetEntity) } }
0
Kotlin
0
1
8ca7dcc8083200dab6869fdb4e0a493ebc6ea2b0
3,189
PetBlocks
Apache License 2.0
script-definition/src/main/kotlin/br/com/devsrsouza/bukkript/script/definition/api/Skedule.kt
DevSrSouza
128,554,342
false
null
package br.com.devsrsouza.bukkript.script.definition.api import br.com.devsrsouza.bukkript.script.definition.BukkriptScript import br.com.devsrsouza.kotlinbukkitapi.extensions.skedule.BukkitDispatchers import com.okkero.skedule.BukkitSchedulerController import com.okkero.skedule.SynchronizationContext import com.okkero.skedule.schedule fun BukkriptScript.schedule( initialContext: SynchronizationContext = SynchronizationContext.SYNC, co: suspend BukkitSchedulerController.() -> Unit ) = plugin.schedule(initialContext, co).also { onDisable { it.cancel() } } val BukkriptScript.BukkitDispatchers get() = plugin.BukkitDispatchers
4
Kotlin
8
66
d1057957d16821d12c739fe07ea6116842a7163d
658
Bukkript
MIT License
src/test/aoc2023/Day5Test.kt
nibarius
154,152,607
false
{"Kotlin": 859326}
package test.aoc2023 import aoc2023.Day5 import org.junit.Assert.assertEquals import org.junit.Test import resourceAsList import resourceSplitOnBlankLines class Day5Test { private val exampleInput = """ seeds: 79 14 55 13 seed-to-soil map: 50 98 2 52 50 48 soil-to-fertilizer map: 0 15 37 37 52 2 39 0 15 fertilizer-to-water map: 49 53 8 0 11 42 42 0 7 57 7 4 water-to-light map: 88 18 7 18 25 70 light-to-temperature map: 45 77 23 81 45 19 68 64 13 temperature-to-humidity map: 0 69 1 1 0 69 humidity-to-location map: 60 56 37 56 93 4 """.trimIndent().split("\n\n") @Test fun testPartOneExample1() { val day5 = Day5(exampleInput) assertEquals(35, day5.solvePart1()) } @Test fun partOneRealInput() { val day5 = Day5(resourceSplitOnBlankLines("2023/day5.txt")) assertEquals(309796150, day5.solvePart1()) } @Test fun testPartTwoExample1() { val day5 = Day5(exampleInput) assertEquals(46, day5.solvePart2()) } @Test fun partTwoRealInput() { val day5 = Day5(resourceSplitOnBlankLines("2023/day5.txt")) assertEquals(50716416, day5.solvePart2()) } }
0
Kotlin
0
6
b9cf4b756470e6dabdbc913285f8cb74d6bd4c0d
1,384
aoc
MIT License
app/src/main/java/org/p2p/wallet/settings/ui/reset/seedinfo/SeedInfoFragment.kt
p2p-org
306,035,988
false
null
package org.p2p.wallet.settings.ui.reset.seedinfo import android.os.Bundle import android.view.View import org.koin.android.ext.android.inject import org.p2p.wallet.R import org.p2p.wallet.common.analytics.interactor.ScreensAnalyticsInteractor import org.p2p.wallet.common.analytics.constants.ScreenNames import org.p2p.wallet.common.mvp.BaseFragment import org.p2p.wallet.databinding.FragmentResetSeedInfoBinding import org.p2p.wallet.root.SystemIconsStyle import org.p2p.wallet.utils.popBackStack import org.p2p.wallet.utils.viewbinding.viewBinding class SeedInfoFragment : BaseFragment(R.layout.fragment_reset_seed_info) { companion object { fun create() = SeedInfoFragment() } private val binding: FragmentResetSeedInfoBinding by viewBinding() private val analyticsInteractor: ScreensAnalyticsInteractor by inject() override val customStatusBarStyle = SystemIconsStyle.WHITE override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) analyticsInteractor.logScreenOpenEvent(ScreenNames.OnBoarding.SEED_INFO) binding.toolbar.setNavigationOnClickListener { popBackStack() } } }
9
null
6
23
2badf683d824c57654b12ea0c023f96e1a5d0c19
1,202
key-app-android
MIT License
stores/src/main/kotlin/com/tormenteddan/stores/SandwichStoreSupervisor.kt
tormenteddan
129,966,876
false
null
package com.tormenteddan.stores import com.tormenteddan.util.Article import com.tormenteddan.util.Transaction import com.tormenteddan.util.TransactionType import java.util.* /** * A sandwich store supervisor that watches over and collects information * from the stores it controls. * * @property globalBalance The supervisor's current balance, calculated by * adding the supervisor's stores' balance. * @property balanceMap Maps each of the supervised stores to their balance. * @property shoppingMap Maps each of the supervised stores to a list of * their missing items. * @property ledger Using this collection, the supervisor keeps track of all * the transactions that take place inside his/her network. */ open class SandwichStoreSupervisor : Observer { val globalBalance: Int get() = balanceMap.toList().sumBy { (_, b) -> b } val balanceMap = hashMapOf<SandwichStore, Int>() val shoppingMap = hashMapOf<SandwichStore, List<Article>>() val ledger = arrayListOf<Transaction>() /** * This method is called whenever the observed object is changed. An * application calls an [Observable] object's * [notifyObservers][Observable.notifyObservers] method to have all the * object's observers notified of the change. * * @param o the observable object. * @param arg argument passed to the * [notifyObservers][Observable.notifyObservers] method. */ override fun update(o: Observable?, arg: Any?) { if (o is SandwichStore) { if (arg is Transaction) ledger.add(arg) balanceMap[o] = o.balance shoppingMap[o] = o.missingArticles } } /** * This function iterates over all the stores that have reported to the * supervisor and have [missing articles][SandwichStore.missingArticles]; * it[replenishes][SandwichStore.replenish] their inventories, creates a * [transaction][Transaction] and makes each store update its supervisors * accordingly. */ fun buyMissingItems() { for (store in shoppingMap.keys) { store.missingArticles.forEach { val missing = it.required - it.current if (store.replenish(it, missing)) { val transaction = Transaction(TransactionType.SPENT, store.address, it.description, (missing * it.cost)) store.update(store, transaction) } } } } }
0
Kotlin
0
0
b01a61a51774936074ccf3c49a920421e14add38
2,523
MP20182_Project01
MIT License
gradle-plugin/src/test/kotlin/schwarz/it/lightsaber/gradle/truth/ProjectSubject.kt
SchwarzIT
670,612,131
false
{"Kotlin": 148414, "Java": 368}
package schwarz.it.lightsaber.gradle.truth import com.google.common.truth.Fact import com.google.common.truth.FailureMetadata import com.google.common.truth.Subject import com.google.common.truth.Truth import org.gradle.api.Project fun assertThat(actual: Project?): ProjectSubject { return Truth.assertAbout(ProjectSubject.Factory).that(actual) } class ProjectSubject( metadata: FailureMetadata, private val actual: Project?, ) : Subject(metadata, actual) { fun hasTask(taskName: String): TaskSubject { actual!! val task = actual.tasks.findByName(taskName) if (task == null) { failWithActual(Fact.simpleFact("The task $taskName shouldn't exist")) error("WTF?") // this shouldn't be called } return assertThat(task) } fun doesntHaveTask(taskName: String) { actual!! if (actual.tasks.findByName(taskName) != null) { failWithActual(Fact.simpleFact("The task $taskName shouldn't exist")) error("WTF?") // this shouldn't be called } } internal object Factory : Subject.Factory<ProjectSubject, Project> { override fun createSubject(metadata: FailureMetadata, actual: Project?): ProjectSubject { return ProjectSubject(metadata, actual) } } }
8
Kotlin
0
12
760e6b4ed6cf4bf3cfe6dbfbc4297d807a537e44
1,320
dagger-lightsaber
Apache License 2.0
app/src/main/java/com/example/dotoring/ui/register/first/RegisterFirstUiState.kt
JNU-econovation
643,536,042
false
null
package com.example.dotoring.ui.register.first data class RegisterFirstUiState( val company: String = "", val careerLevel: String = "", val job: String = "", val major: String = "", val firstBtnState: Boolean = false )
14
Kotlin
2
0
9e956900771fdc88423d1bd0753f99b6ab169775
240
Dotoring_AOS
MIT License
samples/openapi3/client/petstore/kotlin-jvm-retrofit2-rx/src/main/kotlin/org/openapitools/client/apis/DefaultApi.kt
oxidecomputer
334,329,847
true
{"Java": 6236548, "JavaScript": 146416, "TypeScript": 127904, "Shell": 101613, "PHP": 79715, "Kotlin": 79704, "Ruby": 30990, "Apex": 26879, "Handlebars": 11259, "CSS": 10452, "Rust": 7820, "HTML": 5382, "Scala": 5228, "Dockerfile": 4794, "Groovy": 3245, "Blade": 2953, "Dart": 473, "SCSS": 3}
package org.openapitools.client.apis import org.openapitools.client.infrastructure.CollectionFormats.* import retrofit2.http.* import okhttp3.RequestBody import rx.Observable import org.openapitools.client.models.InlineResponseDefault interface DefaultApi { /** * * * Responses: * - 0: response * * @return [Call]<[InlineResponseDefault]> */ @GET("foo") fun fooGet(): Observable<InlineResponseDefault> }
5
Java
3
5
f8770d7c3388d9f1a5069a7f37378aeadcb81e16
458
openapi-generator
Apache License 2.0
sql/src/commonMain/kotlin/dev/brella/amber/sql/postgres/string/lexer/tokens/PostgreSqlRightShiftAppendable.kt
UnderMybrella
630,935,125
false
null
package dev.brella.amber.sql.postgres.string.lexer.tokens import dev.brella.amber.sql.postgres.PostgreSqlAppendable public interface PostgreSqlRightShiftAppendable<SELF : PostgreSqlRightShiftAppendable<SELF>> : PostgreSqlAppendable<SELF> { public fun appendRightShift(): SELF = append(">>") } public inline fun <SELF : PostgreSqlRightShiftAppendable<*>> SELF.rightShift(): SELF { appendRightShift() return this }
0
Kotlin
0
0
4b328e4df9692a13cb9c9921aeb0a80788fbfc0e
431
amber
MIT License
core/presentation/src/main/java/com/pilinhas/android/core/presentation/constants/StringConstants.kt
pilinhasapp
587,541,347
false
null
package com.pilinhas.android.core.presentation.constants object StringConstants { const val LINE_BREAK = "\n" const val SPACE = " " }
0
Kotlin
0
0
075edd796b36203b4950567aecd303e22a330b43
142
Android
MIT License
app/src/main/java/com/kharismarizqii/cocktail/ui/dialog/FilterBottomSheetAdapter.kt
kharismarizqii
430,041,403
false
{"Kotlin": 102574}
package com.kharismarizqii.cocktail.ui.dialog import android.view.LayoutInflater import android.view.ViewGroup import com.kharismarizqii.cocktail.databinding.ItemFilterBottomDialogBinding import com.kharismarizqii.core_cocktail.abstraction.BaseRecyclerViewAdapter import com.kharismarizqii.core_cocktail.abstraction.BaseViewHolder /** * Created by Kharisma Rizqi on 20/11/21 * github.com/kharismarizqii */ class FilterBottomSheetAdapter: BaseRecyclerViewAdapter<FilterBottomSheetAdapter.Holder>(){ private var listData = mutableListOf<String>() private var onClick :((String,Int) -> Unit)? = null fun submitList(newList : List<String>){ listData.clear() listData.addAll(newList) notifyDataSetChanged() } override val viewHolderInflater: (LayoutInflater, ViewGroup, Boolean) -> Holder get() = {layoutInflater, viewGroup, b -> Holder(ItemFilterBottomDialogBinding.inflate(layoutInflater,viewGroup,b)) } override fun onBindViewHolder(holder: Holder, position: Int) { holder.bindWithPosition(data = listData[position],position) } inner class Holder (itemView: ItemFilterBottomDialogBinding) : BaseViewHolder<String, ItemFilterBottomDialogBinding>(itemView){ override fun bind(data: String) { } override fun bindWithPosition(data: String, position: Int) { super.bindWithPosition(data, position) binding.tvArrayFilter.text = data binding.root.setOnClickListener { onClick?.invoke(data,position) } } } fun setOnClickItemListener(onClick: (String,Int) -> Unit){ this.onClick = onClick } override fun getItemCount(): Int { return listData.size } }
0
Kotlin
1
0
fe2f3cfd52fbcec0dac5161a1173d33cea8c1ae8
1,784
cocktail-app
MIT License
buildSrc/src/main/kotlin/androidx/compose/material/symbols/generator/ImageVectorGenerator.kt
tclement0922
694,507,062
false
{"Kotlin": 184754}
/* * Copyright 2020 The Android Open Source Project * Copyright 2023 <NAME> (@tclement0922) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.material.symbols.generator import androidx.compose.material.symbols.generator.IconWriter.Companion.addSuppressAnnotation import androidx.compose.material.symbols.generator.vector.FillType import androidx.compose.material.symbols.generator.vector.Vector import androidx.compose.material.symbols.generator.vector.VectorNode import com.squareup.kotlinpoet.AnnotationSpec import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.FunSpec import com.squareup.kotlinpoet.KModifier import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.buildCodeBlock import java.util.Locale /** * Generator for creating a Kotlin source file with an ImageVector property for the given [vector], * from the icon [icon] * * @param icon the icon used to generate the property and the file. * @param vector the parsed vector to generate ImageVector.Builder commands for */ class ImageVectorGenerator( private val icon: Icon, private val vector: Vector ) { /** * @return a [FileSpec] representing a Kotlin source file containing the property for this * programmatic [vector] representation. */ fun editFileSpec(builder: FileSpec.Builder) { val backingProperty = getBackingProperty(autoMirror = false) // Create a property with a getter. The autoMirror is always false in this case. val propertySpecBuilder = PropertySpec.builder(name = icon.kotlinName, type = ClassNames.ImageVector) .receiver( with(icon.variance) { if (isFilled) filledClassName else className } ) .getter( iconGetter( backingProperty = backingProperty, icon = icon, autoMirror = false ) ) // Add a deprecation warning with a suggestion to replace this icon's usage with its // equivalent that was generated under the automirrored package. if (vector.autoMirrored) { val autoMirroredPackage = icon.variance.packageName propertySpecBuilder.addAnnotation( AnnotationSpec.builder(Deprecated::class) .addMember( "\"\"\"Use the AutoMirrored version at %N.%N.%N.%N.%N.%N\"\"\"", ClassNames.Symbols.simpleName, AutoMirroredName, icon.variance.theme.themeClassName, icon.variance.grade.className, icon.variance.weight.className, icon.kotlinName ) .addMember( "ReplaceWith( \"%N.%N.%N.%N.%N.%N\", \"$autoMirroredPackage.%N\")", ClassNames.Symbols.simpleName, AutoMirroredName, icon.variance.theme.themeClassName, icon.variance.grade.className, icon.variance.weight.className, icon.kotlinName, icon.kotlinName ) .build() ) } builder.addProperty(propertySpecBuilder.build()) builder.addProperty(backingProperty) } /** * @return a [FileSpec] representing a Kotlin source file containing the property for this * programmatic, auto-mirrored, [vector] representation. */ fun editAutoMirroredFileSpec(builder: FileSpec.Builder) { val backingProperty = getBackingProperty(autoMirror = true) // Create a property with a getter. The autoMirror is always false in this case. builder.addProperty( PropertySpec.builder(name = icon.kotlinName, type = ClassNames.ImageVector) .receiver( with(icon.variance) { if (isFilled) autoMirroredFilledClassName else autoMirroredClassName } ) .getter( iconGetter( backingProperty = backingProperty, icon = icon, autoMirror = true ) ) .build() ) builder.addProperty(backingProperty) } private fun createFileSpecBuilder(): FileSpec.Builder { return FileSpec.builder( packageName = with (icon.variance) { if (isFilled) filledPackageName else packageName }, fileName = icon.kotlinName ) } fun createFileSpec(): FileSpec { val builder = createFileSpecBuilder() builder.addSuppressAnnotation() editFileSpec(builder) return builder.build() } private fun createAutoMirroredFileSpecBuilder(): FileSpec.Builder { return FileSpec.builder( packageName = with (icon.variance) { if (isFilled) autoMirroredFilledPackageName else autoMirroredPackageName }, fileName = icon.kotlinName ) } fun createAutoMirroredFileSpec(): FileSpec { val builder = createAutoMirroredFileSpecBuilder() builder.addSuppressAnnotation() editAutoMirroredFileSpec(builder) return builder.build() } private fun getBackingProperty(autoMirror: Boolean): PropertySpec { // Use a unique property name for the private backing property. This is because (as of // Kotlin 1.4) each property with the same name will be considered as a possible candidate // for resolution, regardless of the access modifier, so by using unique names we reduce // the size from ~6000 to 1, and speed up compilation time for these icons. var backingPropertyName = "_" + icon.kotlinName.replaceFirstChar { it.lowercase(Locale.ROOT) } if (autoMirror) backingPropertyName += "_$AutoMirroredPackageName" if (icon.variance.isFilled) backingPropertyName += "_filled" return backingProperty(name = backingPropertyName) } /** * @return the body of the getter for the icon property. This getter returns the backing * property if it is not null, otherwise creates the icon and 'caches' it in the backing * property, and then returns the backing property. */ private fun iconGetter( backingProperty: PropertySpec, icon: Icon, autoMirror: Boolean ): FunSpec { return FunSpec.getterBuilder() .addCode( buildCodeBlock { beginControlFlow("if (%N != null)", backingProperty) addStatement("return %N!!", backingProperty) endControlFlow() } ) .addCode( buildCodeBlock { val controlFlow = buildString { append("%N = %M(name=\"") if (autoMirror) append("$AutoMirroredName.") append("%N.%N.%N") if (icon.variance.isFilled) append(".Filled") append(".%N") append("\", viewportWidth=${vector.viewportWidth.kotlinString()}, viewportHeight=${vector.viewportHeight.kotlinString()}") if (autoMirror) append(", autoMirror=true") append(")") } beginControlFlow( controlFlow, backingProperty, MemberNames.MaterialSymbol, icon.variance.theme.themeClassName, icon.variance.grade.className, icon.variance.weight.className, icon.kotlinName ) vector.nodes.forEach { node -> addRecursively(node) } endControlFlow() } ) .addStatement("return %N!!", backingProperty) .build() } /** * @return The private backing property that is used to cache the ImageVector for a given * icon once created. * * @param name the name of this property */ private fun backingProperty(name: String): PropertySpec { val nullableImageVector = ClassNames.ImageVector.copy(nullable = true) return PropertySpec.builder(name = name, type = nullableImageVector) .mutable() .addModifiers(KModifier.PRIVATE) .initializer("null") .build() } } /** * Recursively adds function calls to construct the given [vectorNode] and its children. */ private fun CodeBlock.Builder.addRecursively(vectorNode: VectorNode) { when (vectorNode) { // TODO: b/147418351 - add clip-paths once they are supported is VectorNode.Group -> { beginControlFlow("%M", MemberNames.Group) vectorNode.paths.forEach { path -> addRecursively(path) } endControlFlow() } is VectorNode.Path -> { addPath(vectorNode) { vectorNode.nodes.forEach { pathNode -> addStatement(pathNode.asFunctionCall()) } } } } } /** * Adds a function call to create the given [path], with [pathBody] containing the commands for * the path. */ private fun CodeBlock.Builder.addPath( path: VectorNode.Path, pathBody: CodeBlock.Builder.() -> Unit ) { // Only set the fill type if it is EvenOdd - otherwise it will just be the default. val setFillType = path.fillType == FillType.EvenOdd val parameterList = with(path) { listOfNotNull( "fillAlpha = ${fillAlpha}f".takeIf { fillAlpha != 1f }, "strokeAlpha = ${strokeAlpha}f".takeIf { strokeAlpha != 1f }, "pathFillType = %M".takeIf { setFillType } ) } val parameters = if (parameterList.isNotEmpty()) { parameterList.joinToString(prefix = "(", postfix = ")") } else { "" } if (setFillType) { beginControlFlow("%M$parameters", MemberNames.MaterialPath, MemberNames.EvenOdd) } else { beginControlFlow("%M$parameters", MemberNames.MaterialPath) } pathBody() endControlFlow() } private fun Float?.kotlinString(): String { if (this == null) return "null" return "${this}f" }
0
Kotlin
0
2
f90309a0b828e78dba08d83a1dffaa1ab63f1817
11,370
material-symbols-compose
Apache License 2.0
android/src/main/kotlin/media/bcc/bccm_player/utils/EmptySurfaceView.kt
bcc-code
673,723,873
false
{"Dart": 338039, "Kotlin": 151547, "Java": 148719, "Swift": 134908, "Objective-C": 94010, "Ruby": 2479, "HTML": 1867, "Makefile": 253}
package media.bcc.bccm_player.utils import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.os.Build import android.view.SurfaceHolder import android.view.SurfaceView import androidx.annotation.RequiresApi class EmptySurfaceView(context: Context?) : SurfaceView(context), SurfaceHolder.Callback { override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {} @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) override fun surfaceCreated(holder: SurfaceHolder) { var canvas: Canvas? = null try { canvas = holder.lockCanvas(null) synchronized(holder) { canvas?.drawColor(Color.RED) } } catch (e: Exception) { e.printStackTrace() } finally { if (canvas != null) { holder.unlockCanvasAndPost(canvas) } } } override fun surfaceDestroyed(holder: SurfaceHolder) { // TODO Auto-generated method stub } init { holder.addCallback(this) } }
16
Dart
7
15
5bd129980a01ec1adf6c7f6478598618373e1cd0
1,106
bccm-player
Apache License 2.0
favouriteapp/src/main/java/com/lonedev/favouriteapp/di/util/ViewModelKey.kt
BYogatama
194,830,761
false
null
/* * Created by <NAME> on 7/20/19 8:21 PM * Copyright (c) 2019 . All rights reserved. * Last modified 6/27/19 1:36 PM */ package com.lonedev.favouriteapp.di.util import androidx.lifecycle.ViewModel import dagger.MapKey import kotlin.reflect.KClass @MustBeDocumented @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER ) @Retention(AnnotationRetention.RUNTIME) @MapKey annotation class ViewModelKey(val value: KClass<out ViewModel>)
0
Kotlin
0
1
eb7bd86ec44c763f077f57b2e206b12e1c2e70ff
501
MovieCatalogue
MIT License
app/src/main/java/com/mailerdaemon/app/clubs/ClubListModel.kt
Pratham2305
263,718,757
true
{"Java": 111257, "Kotlin": 60719}
package com.mailerdaemon.app.clubs data class ClubListModel( var modelList: List<ClubIconModel>? = null )
0
Java
0
0
bfb6f18d0d5cb557b874de088dda2304b060ff39
111
mailer-daemon
MIT License
app/src/main/java/com/tanmay/composegallery/GalleryApp.kt
Patil-Tanmay
634,550,870
false
null
package com.tanmay.composegallery import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class GalleryApp: Application() { }
0
Kotlin
0
1
46c15aa91a4284b1837d96e0b9f305e0dc3303d3
160
Compose-Gallery
MIT License
application/module/module_main/src/main/java/afkt_replace/module/main/AppLauncherActivity.kt
afkT
343,177,221
false
{"Kotlin": 592177}
package afkt_replace.module.main import afkt_replace.core.lib.base.app.BaseAppActivity import afkt_replace.core.lib.base.controller.ui.theme.defaultAppLauncherUITheme import afkt_replace.core.lib.config.AppLibConfig import afkt_replace.core.lib.router.module.main.MainNav import afkt_replace.core.lib.router.module.main.MainRouter import afkt_replace.module.main.databinding.MainAppLauncherBinding import android.os.Bundle import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import me.jessyan.autosize.internal.CancelAdapt class AppLauncherActivity : BaseAppActivity<MainAppLauncherBinding, MainViewModel>( R.layout.main_app_launcher, BR.viewModel, simple_UITheme = { it.defaultAppLauncherUITheme() } ), CancelAdapt { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 非组件化编译运行直接关闭页面 if (!BuildConfig.isModular) { finish() return } lifecycleScope.launch { delay(AppLibConfig.ROUTER_DELAY_MILLIS) MainNav.build(MainRouter.PATH_MAIN).navigation() finish() } } }
2
Kotlin
17
72
710033ee53928e30f8dc7b37aacdbde7283a7841
1,194
DevComponent
Apache License 2.0
app/src/main/java/com/example/burakselcuk/model/ship.kt
burakselcuk1
470,219,631
false
{"Kotlin": 26156}
package com.example.burakselcuk.model class ship : ArrayList<shipItem>()
0
Kotlin
0
0
01f5ebfc64d761e85e51352f261ff516cbf3815b
73
d8bc5ee7a3f14b6837a3a7f769513d8d
The Unlicense
genesis-core/src/main/kotlin/com/github/kennarddh/mindustry/genesis/core/commands/senders/CommandSender.kt
kennarddh-mindustry
727,669,980
false
{"Kotlin": 145945, "Dockerfile": 256}
package com.github.kennarddh.mindustry.genesis.core.commands.senders import kotlin.reflect.full.createType abstract class CommandSender { companion object { val type = CommandSender::class.createType() } abstract fun sendMessage(string: String) abstract fun sendSuccess(string: String) abstract fun sendError(string: String) }
0
Kotlin
0
4
ad25e6a976b0badf26d8e38dbf9b71cf15ee59e4
360
genesis
MIT License
src/exceptions/main7.kt
Herael
199,467,267
false
null
package exceptions /** * ----- INITIEZ-VOUS A KOTLIN ----- * * Partie 2 - Chapitre 4 : Maitrisez les exceptions * * ----- ENONCE ----- * * Dans cet exercice interactif, vous allez devoir : * * - Creer une fonction, isUserOld(), retournant vrai si l'age fournit en parametre * est superieur a 65. Sinon, cette fonction renverra faux. * En revanche, vous devrez lever une exception differente si : * * l'age est inferieur a 0 ("too young !") * * l'age est superieur a 100 ("too old !") * * - Afficher le resultat de cette fonction dans la console. * * * * A vous de jouer, et bon courage ! * */ fun main(args: Array<String>) { print(isUserOld(102)) } private fun isUserOld(age: Int) = when { age > 100 -> throw Exception("too old !") age > 65 -> true age < 0 -> throw Exception("too young !") else -> false }
0
Kotlin
0
0
36e0ea96c3ba933f73fe4f7904f9eacdbca4ae18
854
kotlin_discovery
MIT License
src/main/kotlin/dev/shtanko/jmm/obj/ObjectCreation.kt
ashtanko
203,993,092
false
null
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.jmm.obj class SomeClass private const val LIMIT = 10000 @Suppress("unused", "UNUSED_VARIABLE") fun createObjects() { for (i in 1..LIMIT) { val obj = SomeClass() // Object created // obj goes out of scope after each iteration } // At this point, objects created in the loop are eligible for garbage collection }
4
null
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
954
kotlab
Apache License 2.0
src/test/kotlin/org/rust/lang/core/type/RsCfgAttrTypeInferenceTest.kt
intellij-rust
42,619,487
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.type import org.rust.MockAdditionalCfgOptions import org.rust.ProjectDescriptor import org.rust.WithStdlibRustProjectDescriptor class RsCfgAttrTypeInferenceTest : RsTypificationTestBase() { @MockAdditionalCfgOptions("intellij_rust") fun `test function parameter under cfg 1`() = testExpr(""" fn foo( #[cfg(intellij_rust)] a: u8, #[cfg(not(intellij_rust))] a: i8, ) {} fn main() { let a = 0; foo(a); a; } //^ u8 """) fun `test function parameter under cfg 2`() = testExpr(""" fn foo( #[cfg(intellij_rust)] a: u8, #[cfg(not(intellij_rust))] a: i8, ) {} fn main() { let a = 0; foo(a); a; } //^ i8 """) @MockAdditionalCfgOptions("intellij_rust") @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test infer type of derivable trait method call 1`() = stubOnlyTypeInfer(""" //- main.rs #[cfg_attr(intellij_rust, derive(Clone))] struct Foo; fn bar(foo: Foo) { let foo2 = foo.clone(); foo2; //^ Foo } """) @MockAdditionalCfgOptions("intellij_rust") @ProjectDescriptor(WithStdlibRustProjectDescriptor::class) fun `test infer type of derivable trait method call 2`() = stubOnlyTypeInfer(""" //- main.rs #[cfg_attr(not(intellij_rust), derive(Clone))] struct Foo; fn bar(foo: Foo) { let foo2 = foo.clone(); foo2; //^ <unknown> } """) }
1,841
null
380
4,528
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
1,768
intellij-rust
MIT License
lcc-content/src/main/kotlin/com/joshmanisdabomb/lcc/recipe/arcane/DungeonTableShapelessRecipe.kt
joshmanisdabomb
537,458,013
false
{"Kotlin": 2724329, "Java": 138822}
package com.joshmanisdabomb.lcc.recipe.arcane import com.google.gson.JsonObject import com.joshmanisdabomb.lcc.directory.LCCRecipeSerializers import com.joshmanisdabomb.lcc.extensions.getShapelessIngredients import com.joshmanisdabomb.lcc.extensions.getStack import net.minecraft.inventory.Inventory import net.minecraft.item.ItemStack import net.minecraft.network.PacketByteBuf import net.minecraft.recipe.Ingredient import net.minecraft.recipe.RecipeMatcher import net.minecraft.recipe.RecipeSerializer import net.minecraft.util.Identifier import net.minecraft.util.JsonHelper import net.minecraft.util.collection.DefaultedList import net.minecraft.world.World class DungeonTableShapelessRecipe(private val _id: Identifier, private val _group: String, private val ingredients: DefaultedList<Ingredient>, private val _output: ItemStack) : DungeonTableRecipe { override fun matches(inv: Inventory, world: World): Boolean { val recipeFinder = RecipeMatcher() var i = 0 for (j in 0 until inv.size()) { val stack = inv.getStack(j) if (!stack.isEmpty) { ++i recipeFinder.addInput(stack, 1) } } return i == ingredients.size && recipeFinder.match(this, null) } override fun craft(inv: Inventory) = output.copy() override fun fits(width: Int, height: Int) = true override fun getId() = _id override fun getGroup() = _group override fun getIngredients() = ingredients override fun getOutput() = _output override fun getSerializer() = LCCRecipeSerializers.spawner_table_shapeless class Serializer : RecipeSerializer<DungeonTableShapelessRecipe> { override fun read(id: Identifier, json: JsonObject): DungeonTableShapelessRecipe { val group = JsonHelper.getString(json, "group", "")!! val ingredients = getShapelessIngredients(JsonHelper.getArray(json, "ingredients")) val output = getStack(JsonHelper.getObject(json, "result")) return DungeonTableShapelessRecipe(id, group, ingredients, output) } override fun read(id: Identifier, buf: PacketByteBuf): DungeonTableShapelessRecipe { val group = buf.readString() val ingredients = DefaultedList.ofSize(buf.readInt(), Ingredient.EMPTY) for (i in ingredients.indices) ingredients[i] = Ingredient.fromPacket(buf) val output = buf.readItemStack() return DungeonTableShapelessRecipe(id, group, ingredients, output) } override fun write(buf: PacketByteBuf, recipe: DungeonTableShapelessRecipe) { buf.writeString(recipe._group) buf.writeInt(recipe.ingredients.size) recipe.ingredients.forEach { it.write(buf) } buf.writeItemStack(recipe._output) } } }
0
Kotlin
0
0
a836162eaf64a75ca97daffa02c1f9e66bdde1b4
2,857
loosely-connected-concepts
Creative Commons Zero v1.0 Universal
app/src/main/java/com/stratagile/qlink/ui/activity/my/EpidemicWebViewActivity.kt
qlcchain
115,608,966
false
null
package com.stratagile.qlink.ui.activity.my import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.webkit.WebSettings import butterknife.ButterKnife import com.pawegio.kandroid.runDelayedOnUiThread import com.socks.library.KLog import com.stratagile.qlink.R import com.stratagile.qlink.application.AppConfig import com.stratagile.qlink.base.BaseActivity import com.stratagile.qlink.constant.ConstantValue import com.stratagile.qlink.ui.activity.my.component.DaggerEpidemicWebViewComponent import com.stratagile.qlink.ui.activity.my.contract.EpidemicWebViewContract import com.stratagile.qlink.ui.activity.my.module.EpidemicWebViewModule import com.stratagile.qlink.ui.activity.my.presenter.EpidemicWebViewPresenter import com.stratagile.qlink.utils.AccountUtil import com.stratagile.qlink.utils.XWebViewClient import com.today.step.lib.ISportStepInterface import com.today.step.lib.TodayStepService import kotlinx.android.synthetic.main.activity_web_view.* import org.greenrobot.eventbus.EventBus import javax.inject.Inject; /** * @author hzp * @Package com.stratagile.qlink.ui.activity.my * @Description: $description * @date 2020/04/16 17:48:35 */ class EpidemicWebViewActivity : BaseActivity(), EpidemicWebViewContract.View { @Inject internal lateinit var mPresenter: EpidemicWebViewPresenter private var iSportStepInterface: ISportStepInterface? = null lateinit var serviceConnection : ServiceConnection override fun onCreate(savedInstanceState: Bundle?) { mainColor = R.color.white super.onCreate(savedInstanceState) } override fun initView() { setContentView(R.layout.activity_web_view) } override fun initData() { setTitle(intent.getStringExtra("title")) webView.getSettings().setBuiltInZoomControls(true) webView.getSettings().setDefaultFontSize(16) webView.getSettings().setDisplayZoomControls(false) webView.getSettings().setSupportZoom(true) webView.getSettings().setLoadWithOverviewMode(true) webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true) webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT) webView.getSettings().setDefaultTextEncodingName("UTF-8") webView.getSettings().setJavaScriptEnabled(true) webView.getSettings().setDomStorageEnabled(true) webView.getSettings().setAllowContentAccess(true) webView.getSettings().setAppCacheEnabled(false) webView.getSettings().setUseWideViewPort(true) webView.getSettings().setLoadWithOverviewMode(true) webView.loadUrl(intent.getStringExtra("url")) // webView.loadUrl("https://www.baidu.com"); KLog.i(intent.getStringExtra("url")) webView.setWebViewClient(XWebViewClient()) //开启计步Service,同时绑定Activity进行aidl通信 val intent = Intent(this, TodayStepService::class.java) startService(intent) serviceConnection = object : ServiceConnection { override fun onServiceConnected(name: ComponentName, service: IBinder) { //Activity和Service通过aidl进行通信 runDelayedOnUiThread(300) { iSportStepInterface = ISportStepInterface.Stub.asInterface(service) focusEpidemic() } } override fun onServiceDisconnected(name: ComponentName) { } } bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE) } override fun onDestroy() { unbindService(serviceConnection) super.onDestroy() } /** * 关注疫情,关注之后才能领取 */ fun focusEpidemic() { if (ConstantValue.currentUser != null) { iSportStepInterface!!.focusEpidemic(ConstantValue.currentUser.account, AccountUtil.getUserToken()) } } override fun setupActivityComponent() { DaggerEpidemicWebViewComponent .builder() .appComponent((application as AppConfig).applicationComponent) .epidemicWebViewModule(EpidemicWebViewModule(this)) .build() .inject(this) } override fun setPresenter(presenter: EpidemicWebViewContract.EpidemicWebViewContractPresenter) { mPresenter = presenter as EpidemicWebViewPresenter } override fun showProgressDialog() { progressDialog.show() } override fun closeProgressDialog() { progressDialog.hide() } }
1
null
18
46
1c8066e4ebbb53c7401751ea3887a6315ccbe5eb
4,621
QWallet-Android
MIT License
app/src/main/java/org/ballistic/dreamjournalai/onboarding/presentation/viewmodel/SplashViewModel.kt
ErickSorto
546,852,272
false
null
package org.ballistic.dreamjournalai.onboarding.presentation.viewmodel import androidx.compose.runtime.MutableState import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.graphics.BlendMode.Companion.Screen import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import org.ballistic.dreamjournalai.feature_dream.navigation.Screens import org.ballistic.dreamjournalai.onboarding.data.DataStoreRepository import javax.inject.Inject @HiltViewModel class SplashViewModel @Inject constructor( private val repository: DataStoreRepository ) : ViewModel() { val state_ = mutableStateOf(SplashState()) val state: State<SplashState> = state_ //if completed startDestination = DreamListScreen.route else Welcome.route init { viewModelScope.launch { repository.readOnBoardingState().collectLatest { completed -> if (completed) { state_.value = state.value.copy(startDestination = Screens.DreamListScreen.route) } else { state_.value = state.value.copy(startDestination = Screens.Welcome.route) } state_.value = state.value.copy(isLoading = false) } } } data class SplashState( val isLoading: Boolean = true, val startDestination: String = Screens.DreamListScreen.route ) }
0
Kotlin
0
1
30509c2f3001a14add310a7b2c73bc9099a701f0
1,568
Dream-Journal-AI
MIT License
src/test/kotlin/utils/BinaryTest.kt
Arch-vile
433,381,878
false
{"Kotlin": 57129}
package utils import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test internal class BinaryTest { @Test fun from_long() { assertEquals(123L, Binary.from(123L,2).asLong()) assertEquals(0L, Binary.from(0L,10).asLong()) assertThrows(Error::class.java) { Binary.from(-1L,10) } } @Test fun from_binary_string() { assertEquals( 38234, Binary.from("1001010101011010").asLong() ) } @Test fun fromList() { assertEquals(38234, Binary.from(listOf(1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0)).asLong()) } @Test fun asBits() { assertEquals( listOf(1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0), Binary.from(38234,16).bits() ) assertEquals( listOf(0, 0, 0, 0, 0, 0, 0, 1), Binary.from(1,8).bits() ) } @Test fun asString() { assertEquals("1101110", Binary.from(110,7).asString()) assertEquals("01101110", Binary.from(110,8).asString()) } @Test fun bit() { val binary = Binary.from("010101") assertEquals(1, binary.bit(5)) assertEquals(0, binary.bit(4)) assertEquals(1, binary.bit(3)) assertThrows(IndexOutOfBoundsException::class.java) { binary.bit(6) } } @Test fun invert() { assertEquals( Binary.from("111000").bits(), Binary.from("000111").invert().bits() ) assertEquals( Binary.from("000").bits(), Binary.from("111").invert().bits() ) } @Test fun shift() { } }
0
Kotlin
0
0
4cdafaa524a863e28067beb668a3f3e06edcef96
1,788
adventOfCode2021
Apache License 2.0
app/src/main/java/com/plutoisnotaplanet/currencyconverterapp/application/utils/CurrencyConversion.kt
plutoisnotaplanet
565,361,264
false
{"Kotlin": 119300}
package com.plutoisnotaplanet.currencyconverterapp.application.utils import java.math.BigDecimal import java.math.MathContext import java.math.RoundingMode object CurrencyConversion { fun convertCurrency(fromRate: BigDecimal, toRate: BigDecimal): BigDecimal { val rateForOneDollar = convertAnyCurrencyToDollar(fromRate) return convertDollarToAnyCurrency(rateForOneDollar, toRate) } private fun convertAnyCurrencyToDollar(fromRate: BigDecimal): BigDecimal { return BigDecimal.ONE.multiply(fromRate, MathContext.DECIMAL128) } private fun convertDollarToAnyCurrency(dollarValue: BigDecimal, toRate: BigDecimal): BigDecimal { return if (dollarValue < BigDecimal.ONE) { dollarValue.divide(toRate, 20, RoundingMode.HALF_UP) } else { toRate.divide(dollarValue, 20, RoundingMode.HALF_UP) } } }
0
Kotlin
0
1
796f2d092f9642fbf2be2c26cc74591feda25d31
886
CurrencyConverterApp
Apache License 2.0
app/src/test/java/uk/ryanwong/catnews/newslist/data/local/entity/NewsItemEntityMapperTest.kt
ryanw-mobile
531,291,511
false
{"Kotlin": 277898}
/* * Copyright (c) 2024. <NAME> (<EMAIL>) */ package uk.ryanwong.catnews.newslist.data.local.entity import io.kotest.matchers.collections.shouldContainInOrder import io.kotest.matchers.shouldBe import org.junit.Before import org.junit.Test import uk.ryanwong.catnews.app.util.nicedateformatter.FakeNiceDateFormatter import uk.ryanwong.catnews.data.datasource.local.entity.NewsItemEntity import uk.ryanwong.catnews.data.datasource.local.mappers.asDomainModel import uk.ryanwong.catnews.domain.model.newslist.NewsItem class NewsItemEntityMapperTest { private lateinit var fakeNiceDateFormatter: FakeNiceDateFormatter @Before fun setupNiceDateFormatter() { fakeNiceDateFormatter = FakeNiceDateFormatter() } @Test fun `asDomainModel should return an empty list if newsItemEntities is empty`() { fakeNiceDateFormatter.getNiceDateResponse = "2 days ago" val newsItemEntities = listOf<NewsItemEntity>() val newsItem = newsItemEntities.asDomainModel(niceDateFormatter = fakeNiceDateFormatter) newsItem shouldBe emptyList() } @Test fun `asDomainModel should convert and keep only known types from multiple newsItemEntities`() { fakeNiceDateFormatter.getNiceDateResponse = "2 days ago" val newsItemEntities = listOf( NewsItemEntityMapperTestData.newsItemEntity1, NewsItemEntityMapperTestData.newsItemEntity2, NewsItemEntityMapperTestData.newsItemEntity3, ) val newsItem = newsItemEntities.asDomainModel(niceDateFormatter = fakeNiceDateFormatter) newsItem shouldContainInOrder listOf( NewsItemEntityMapperTestData.newsItemStory, NewsItemEntityMapperTestData.newsItemWebLink, ) } @Test fun `asDomainModel should fill headline with empty string if it comes as null`() { fakeNiceDateFormatter.getNiceDateResponse = "2 days ago" val newsItemEntities = listOf(NewsItemEntityMapperTestData.newsItemEntity1.copy(headline = null)) val newsItem = newsItemEntities.asDomainModel(niceDateFormatter = fakeNiceDateFormatter) newsItem shouldBe listOf( NewsItem.Story( newsId = 1, headline = "", teaserText = "some-teaser-text", modifiedDate = "2022-05-21T00:00:00Z", niceDate = "2 days ago", teaserImageUrl = "https://some.teaser.image/href", teaserImageAccessibilityText = "some-teaser-image-accessibility-text", ), ) } @Test fun `asDomainModel should fill teaserText with empty string if it comes as null`() { fakeNiceDateFormatter.getNiceDateResponse = "2 days ago" val newsItemEntities = listOf(NewsItemEntityMapperTestData.newsItemEntity1.copy(teaserText = null)) val newsItem = newsItemEntities.asDomainModel(niceDateFormatter = fakeNiceDateFormatter) newsItem shouldBe listOf( NewsItem.Story( newsId = 1, headline = "some-headline", teaserText = "", modifiedDate = "2022-05-21T00:00:00Z", niceDate = "2 days ago", teaserImageUrl = "https://some.teaser.image/href", teaserImageAccessibilityText = "some-teaser-image-accessibility-text", ), ) } @Test fun `asDomainModel should fill teaserImageUrl with empty string if teaserImageHref comes as null`() { fakeNiceDateFormatter.getNiceDateResponse = "2 days ago" val newsItemEntities = listOf( NewsItemEntityMapperTestData.newsItemEntity1.copy(teaserImageHref = null), ) val newsItem = newsItemEntities.asDomainModel(niceDateFormatter = fakeNiceDateFormatter) newsItem shouldBe listOf( NewsItem.Story( newsId = 1, headline = "some-headline", teaserText = "some-teaser-text", modifiedDate = "2022-05-21T00:00:00Z", niceDate = "2 days ago", teaserImageUrl = "", teaserImageAccessibilityText = "some-teaser-image-accessibility-text", ), ) } @Test fun `asDomainModel should keep url as null if it comes as null`() { fakeNiceDateFormatter.getNiceDateResponse = "2 days ago" val newsItemEntities = listOf(NewsItemEntityMapperTestData.newsItemEntity1.copy(advertUrl = null)) val newsItem = newsItemEntities.asDomainModel(niceDateFormatter = fakeNiceDateFormatter) newsItem shouldBe listOf( NewsItem.Story( newsId = 1, headline = "some-headline", teaserText = "some-teaser-text", modifiedDate = "2022-05-21T00:00:00Z", niceDate = "2 days ago", teaserImageUrl = "https://some.teaser.image/href", teaserImageAccessibilityText = "some-teaser-image-accessibility-text", ), ) } }
4
Kotlin
0
1
55365007972eaa864ceb3dc6978d84f132a645b7
5,111
cat-news
Apache License 2.0
app/src/main/java/com/hunabsys/gamezone/models/daos/EvidenceDao.kt
HiperSoft
324,049,960
false
null
package com.hunabsys.gamezone.models.daos import android.util.Log import com.hunabsys.gamezone.models.datamodels.Evidence import com.rollbar.android.Rollbar import io.realm.Realm import io.realm.RealmResults import io.realm.Sort class EvidenceDao { private val tag = EvidenceDao::class.java.simpleName private val realm = Realm.getDefaultInstance() fun create(evidence: Evidence) { try { realm.executeTransaction { val evidenceObject = realm.createObject(Evidence::class.java, getId()) evidenceObject.userId = evidence.userId evidenceObject.evidenceId = evidence.evidenceId evidenceObject.evidenceableId = evidence.evidenceableId evidenceObject.evidenceableType = evidence.evidenceableType evidenceObject.file = evidence.file evidenceObject.filename = evidence.filename evidenceObject.originalFilename = evidence.originalFilename evidenceObject.isSynchronized = evidence.isSynchronized } } catch (ex: IllegalArgumentException) { Log.e(tag, "Attempting to create an Evidence", ex) Rollbar.instance().critical(ex, tag) } } fun update(evidence: Evidence) { try { realm.executeTransaction { val evidenceObject = findById(evidence.id) evidenceObject.userId = evidence.userId evidenceObject.evidenceId = evidence.evidenceId evidenceObject.evidenceableId = evidence.evidenceableId evidenceObject.evidenceableType = evidence.evidenceableType evidenceObject.file = evidence.file evidenceObject.filename = evidence.filename evidenceObject.originalFilename = evidence.originalFilename evidenceObject.isSynchronized = evidence.isSynchronized } } catch (ex: IllegalArgumentException) { Log.e(tag, " Attempting to update an Evidence") Rollbar.instance().critical(ex, tag) } } private fun findById(id: Long): Evidence { return realm.where(Evidence::class.java) .equalTo("id", id) .findFirst()!! } fun findCopyById(id: Long): Evidence { val evidence = realm.where(Evidence::class.java) .equalTo("id", id) .findFirst()!! return realm.copyFromRealm(evidence) } fun findAllByType(type: String, userId: Long): RealmResults<Evidence> { return realm.where(Evidence::class.java) .equalTo("userId", userId) .equalTo("evidenceableType", type) .findAll() .sort("id", Sort.DESCENDING) } private fun findAll(): RealmResults<Evidence> { return realm.where(Evidence::class.java) .findAll() .sort("id", Sort.DESCENDING) } fun deleteAll(userId: Long) { try { realm.executeTransaction { realm.where(Evidence::class.java) .equalTo("userId", userId) .findAll() .deleteAllFromRealm() } } catch (ex: Exception) { Log.e(tag, "Attempting to delete all Evidences", ex) Rollbar.instance().critical(ex, tag) } } fun deleteAllOtherUsers(userId: Long) { try { realm.executeTransaction { realm.where(Evidence::class.java) .notEqualTo("userId", userId) .findAll() .deleteAllFromRealm() } } catch (ex: Exception) { Log.e(tag, "Attempting to delete all Evidences", ex) Rollbar.instance().critical(ex, tag) } } fun getId(): Long { return if (findAll().size != 0) { val lastId = findAll().first()!!.id lastId + 1 } else { 1 } } fun saveEvidence(evidence: Evidence): Evidence? { var savedEvidence: Evidence? = null create(evidence) try { savedEvidence = findById(evidence.id) Log.d(tag, "Evidence is saved: " + savedEvidence.toString()) } catch (ex: KotlinNullPointerException) { Log.e(tag, "Null Evidence", ex) Rollbar.instance().critical(ex, tag) } return savedEvidence } }
0
Kotlin
0
0
fab0ef038d84595df86cf480ed581c84b4272073
4,537
AppGameZone
MIT License
src/main/java/com/github/shur/drip/api/trade/TradeRegistry.kt
SigureRuri
386,152,122
false
null
package com.github.shur.drip.api.trade interface TradeRegistry { fun get(id: TradeId): Trade? fun getAll(): List<Trade> fun has(id: TradeId): Boolean fun register(trade: Trade) fun unregister(id: TradeId) fun load() fun save() }
0
Kotlin
0
0
e0db1d5c412d780a6ee5054b7ff0544002904e9d
265
Drip
MIT License
app/src/main/java/com/demo/app/navigation/NavigateFromAuthToDashboardImpl.kt
creati8e
158,413,358
false
{"Gradle": 12, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 13, "Batchfile": 1, "Proguard": 10, "XML": 41, "Kotlin": 71, "INI": 1, "Java": 5}
package com.demo.app.navigation import androidx.navigation.NavController import com.demo.app.R import com.demo.core.navigation.actions.NavigateFromAuthToDashboard /** * @author Sergey Chuprin */ class NavigateFromAuthToDashboardImpl : NavigateFromAuthToDashboard { override fun navigate(navController: NavController) { navController.navigate(R.id.action_auth_to_dashboard) } }
0
Kotlin
0
0
8a757f810a50d468474e5614acde4432021e59f7
398
Modularization
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/objs/underwall/underwall_tunnel.plugin.kts
pitchblac23
201,185,078
true
{"Kotlin": 3718848, "Dockerfile": 1354}
package gg.rsmod.plugins.content.objs.underwall on_obj_option(16529, "climb-into") { player.climbIntoUnderwallwest() } on_obj_option(16530, "climb-into") { player.climbIntoUnderwalleast() } fun Player.climbIntoUnderwallwest() { queue { lock() animate(2589) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3138, z = 3516, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.EAST.angle)) wait(1) animate(2590) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3139, z = 3515, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.EAST.angle)) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3140, z = 3514, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.EAST.angle)) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3141, z = 3513, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.EAST.angle)) animate(2591) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3142, z = 3513, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.EAST.angle)) animate(-1) player.unlock() } } fun Player.climbIntoUnderwalleast() { queue { lock() animate(2589) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3141, z = 3513, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.WEST.angle)) wait(1) animate(2590) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3140, z = 3514, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.WEST.angle)) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3139, z = 3515, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.WEST.angle)) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3138, z = 3516, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.WEST.angle)) animate(2591) forceMove(this, ForcedMovement.of(player.tile, Tile(x = 3137, z = 3516, height = 0), clientDuration1 = 33, clientDuration2 = 60, directionAngle = Direction.WEST.angle)) animate(-1) player.unlock() } }
1
Kotlin
2
1
ade69da919ba62ec3ac37fccab9068f2820c774d
2,371
rsmod
Apache License 2.0
tests/src/main/java/sergio/sastre/composable/preview/scanner/multiplepreviewswithpreviewparameters/Composables.kt
sergio-sastre
812,732,732
false
{"Kotlin": 79277}
package sergio.sastre.composable.preview.scanner.multiplepreviewswithpreviewparameters import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.PreviewLightDark import androidx.compose.ui.tooling.preview.PreviewParameter import sergio.sastre.composable.preview.scanner.StringProvider import sergio.sastre.composable.preview.scanner.previewparameters.Example @PreviewLightDark @Composable fun ExampleMultiplePreviewWithParams( @PreviewParameter(provider = StringProvider::class) name: String ){ Example(name) }
4
Kotlin
1
58
2ef53b077b603df84bdf12b4299926d6212d5a9c
548
ComposablePreviewScanner
MIT License
src/test/kotlin/com/forgerock/uk/openbanking/tests/functional/payment/domestic/payments/consents/junit/v3_1_10/GetDomesticPaymentsConsentFundsConfirmationTest.kt
SecureApiGateway
330,627,234
false
null
package com.forgerock.uk.openbanking.tests.functional.payment.domestic.payments.consents.junit.v3_1_10 import com.forgerock.securebanking.framework.extensions.junit.CreateTppCallback import com.forgerock.securebanking.framework.extensions.junit.EnabledIfVersion import com.forgerock.securebanking.openbanking.uk.common.api.meta.obie.OBVersion import com.forgerock.uk.openbanking.tests.functional.payment.domestic.payments.consents.api.v3_1_8.GetDomesticPaymentsConsentFundsConfirmation import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test class GetDomesticPaymentsConsentFundsConfirmationTest(val tppResource: CreateTppCallback.TppResource) { lateinit var getDomesticPaymentsConsentFundsConfirmationApi: GetDomesticPaymentsConsentFundsConfirmation @BeforeEach fun setUp() { getDomesticPaymentsConsentFundsConfirmationApi = GetDomesticPaymentsConsentFundsConfirmation(OBVersion.v3_1_10, tppResource) } @EnabledIfVersion( type = "payments", apiVersion = "v3.1.10", operations = ["CreateDomesticPaymentConsent", "GetDomesticPaymentConsentsConsentIdFundsConfirmation"], apis = ["domestic-payment-consents"] ) @Test fun shouldGetDomesticPaymentConsentsFundsConfirmation_false_v3_1_10() { getDomesticPaymentsConsentFundsConfirmationApi.shouldGetDomesticPaymentConsentsFundsConfirmation_false() } @EnabledIfVersion( type = "payments", apiVersion = "v3.1.10", operations = ["CreateDomesticPaymentConsent", "GetDomesticPaymentConsentsConsentIdFundsConfirmation"], apis = ["domestic-payment-consents"] ) @Test fun shouldGetDomesticPaymentConsentsFundsConfirmation_throwsWrongGrantType_v3_1_10() { getDomesticPaymentsConsentFundsConfirmationApi.shouldGetDomesticPaymentConsentsFundsConfirmation_throwsWrongGrantType() } @EnabledIfVersion( type = "payments", apiVersion = "v3.1.10", operations = ["CreateDomesticPaymentConsent", "GetDomesticPaymentConsentsConsentIdFundsConfirmation"], apis = ["domestic-payment-consents"] ) @Test fun shouldGetDomesticPaymentConsentsFundsConfirmation_true_v3_1_10() { getDomesticPaymentsConsentFundsConfirmationApi.shouldGetDomesticPaymentConsentsFundsConfirmation_true() } @EnabledIfVersion( type = "payments", apiVersion = "v3.1.10", operations = ["CreateDomesticPaymentConsent", "GetDomesticPaymentConsentsConsentIdFundsConfirmation"], apis = ["domestic-payment-consents"] ) @Test fun shouldGetDomesticPaymentConsentsFundsConfirmation_throwsInvalidConsentStatus_v3_1_10() { getDomesticPaymentsConsentFundsConfirmationApi.shouldGetDomesticPaymentConsentsFundsConfirmation_throwsInvalidConsentStatus_Test() } }
2
Kotlin
0
4
339d5db69dd11cc10a93116d9bbc9d187969fc46
2,877
securebanking-openbanking-uk-functional-tests
Apache License 2.0
src/main/java/com/heinrichreimer/gradle/plugin/github/release/api/GitHubApiService.kt
heinrichreimer
175,037,998
true
{"Kotlin": 75583}
package com.heinrichreimer.gradle.plugin.github.release.api import com.heinrichreimer.gradle.plugin.github.release.api.converter.HttpUrlJsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import okhttp3.MediaType import okhttp3.OkHttpClient import org.gradle.api.provider.Provider import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory class GitHubApiService( retrofit: Retrofit ) : GitHubService by retrofit.create(GitHubService::class.java) { constructor( authorization: Provider<String>, baseUrl: String = DEFAULT_BASE_URL ) : this( Retrofit.Builder() .client( OkHttpClient.Builder() .addInterceptor { chain -> chain.proceed( chain.request() .newBuilder() .addHeader("Authorization", "token ${authorization.get()}") .addHeader("User-Agent", "GitHub Release Gradle Plugin") .addHeader("Accept", "application/vnd.github.v3+json") .addHeader("Content-Type", JSON.toString()) .build() ) } .build() ) .baseUrl(baseUrl) .addConverterFactory( MoshiConverterFactory.create( Moshi.Builder() .add(HttpUrlJsonAdapter) .add(KotlinJsonAdapterFactory()) .build() ) ) .build() ) companion object { private val JSON: MediaType = MediaType.parse("application/json; charset=utf-8")!! private const val DEFAULT_BASE_URL = "https://api.github.com/" } }
0
Kotlin
0
1
ac1e8674f81630749269a85089dad02c44d984e2
2,348
gradle-github-release
MIT License
paraglider-vbaa-mp-common-cor/src/commonMain/kotlin/core/AbstractCorDsl.kt
otuskotlin
378,049,879
false
null
package core abstract class AbstractCorDsl<T>( override var title: String = "", override var description: String = "", private val workers: MutableList<ICorExecDsl<T>> = mutableListOf(), open var blockOn: suspend T.() -> Boolean = { true }, open var blockExcept: suspend T.(e: Throwable) -> Unit = { e: Throwable -> throw e } ) : ICorChainDsl<T> { override fun on(function: suspend T.() -> Boolean) { blockOn = function } override fun except(function: suspend T.(e: Throwable) -> Unit) { blockExcept = function } override fun add(worker: ICorExecDsl<T>) { workers.add(worker) } abstract override fun build(): ICorExec<T> }
0
Kotlin
0
0
59ab19ce0bdad96adfad0ef3b3d6e60f52789cb8
699
ok-202105-paraglider-vbaa
MIT License
app/src/main/java/com/tieuvy/android/base_mvvm_android_1/utils/extension/ContextExtension.kt
vyvanhungbg
643,543,135
false
{"Kotlin": 39511}
package com.tieuvy.android.base_mvvm_android_1.utils.extension import android.app.AlertDialog import android.app.TimePickerDialog import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.widget.Toast import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.core.content.ContextCompat import java.util.Calendar import java.util.Locale fun Context.showToast(message: String?) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun Context.showToast(resource: Int) { Toast.makeText(this, resource, Toast.LENGTH_SHORT).show() } fun Context.color(@ColorRes color: Int): Int { return ContextCompat.getColor(this, color) } fun Context.drawable(@DrawableRes drawable: Int): Drawable? { return ContextCompat.getDrawable(this, drawable) } fun Context.pickDateTime(action: (hour: Int, minute: Int) -> Unit) { Locale.setDefault(Locale("vi")) val currentDateTime = Calendar.getInstance() val startHour = currentDateTime.get(Calendar.HOUR_OF_DAY) val startMinute = currentDateTime.get(Calendar.MINUTE) TimePickerDialog( this, AlertDialog.THEME_HOLO_LIGHT, TimePickerDialog.OnTimeSetListener { _, hour, minute -> action( hour, minute ) }, startHour, startMinute, true ).apply { window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) show() } }
0
Kotlin
0
2
85c13e09216465a019df9f1e96260240d68ae154
1,569
Base-MVVM-Android-1
Apache License 2.0
app/src/main/java/com/breezefieldsalesayshfacade/features/location/api/LocationRepo.kt
DebashisINT
849,339,890
false
{"Kotlin": 15796449, "Java": 1028706}
package com.breezefieldsalesayshfacade.features.location.api import com.breezefieldsalesayshfacade.app.Pref import com.breezefieldsalesayshfacade.base.BaseResponse import com.breezefieldsalesayshfacade.features.location.model.AppInfoInputModel import com.breezefieldsalesayshfacade.features.location.model.AppInfoResponseModel import com.breezefieldsalesayshfacade.features.location.model.GpsNetInputModel import com.breezefieldsalesayshfacade.features.location.model.ShopDurationRequest import com.breezefieldsalesayshfacade.features.location.shopdurationapi.ShopDurationApi import io.reactivex.Observable /** * Created by Saikat on 17-Aug-20. */ class LocationRepo(val apiService: LocationApi) { fun appInfo(appInfo: AppInfoInputModel?): Observable<BaseResponse> { return apiService.submitAppInfo(appInfo) } fun getAppInfo(): Observable<AppInfoResponseModel> { return apiService.getAppInfo(Pref.session_token!!, Pref.user_id!!) } fun gpsNetInfo(appInfo: GpsNetInputModel?): Observable<BaseResponse> { return apiService.submitGpsNetInfo(appInfo) } }
0
Kotlin
0
0
1a7295943ae51c2feff787bed4219be9c8399217
1,104
AyshFacade
Apache License 2.0
app/src/main/java/edu/skku/cs/giftizone/addGifticon/AddGifticonActivity.kt
AnJeongMin
630,875,410
false
null
package edu.skku.cs.giftizone.addGifticon import android.app.DatePickerDialog import android.content.Intent import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.os.Bundle import android.os.Environment import android.view.View import android.widget.* import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.bumptech.glide.Glide import edu.skku.cs.giftizone.R import edu.skku.cs.giftizone.common.Gifticon import edu.skku.cs.giftizone.common.toast import java.io.File import java.io.FileOutputStream import java.io.IOException import java.time.LocalDate import java.util.* class AddGifticonActivity : AppCompatActivity() { private lateinit var tagList: ArrayList<String> private var localImageUrl: Uri? = null private var selectedTag: String? = null private var expiredDate: LocalDate? = null private val pickImageResultLauncher = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? -> val gifticonImage = findViewById<ImageView>(R.id.addGifticonImage) if (uri != null) { Glide.with(this) .load(uri) // or Uri or File .into(gifticonImage) localImageUrl = uri } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_gifticon) setupSelectImageBtn() setupSelectExpireDate() setupTagSelectDropdown() setupSaveGifticonBtn() } private fun pickImageFromGallery() { pickImageResultLauncher.launch("image/*") } private fun setupSelectImageBtn() { val gifticonImage = findViewById<ImageView>(R.id.addGifticonImage) gifticonImage.setImageResource(R.drawable.baseline_image_search_24) gifticonImage.setOnClickListener { pickImageFromGallery() } } private fun setupSelectExpireDate() { val selectExpireDateBtn = findViewById<ImageView>(R.id.calenderButton) val expireDateText = findViewById<TextView>(R.id.addExpireText) selectExpireDateBtn.setOnClickListener { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) val datePickerDialog = DatePickerDialog(this, { _, selectedYear, selectedMonth, selectedDay -> expireDateText.text = "$selectedYear/${selectedMonth+1}/$selectedDay" expiredDate = LocalDate.of(selectedYear, selectedMonth+1, selectedDay) }, year, month, day) datePickerDialog.show() } } private fun setupTagSelectDropdown() { tagList = intent.getStringArrayListExtra("tagList")!! val addTagDropdown: Spinner = findViewById(R.id.addTagDropdown) addTagDropdown.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View?, position: Int, id: Long) { selectedTag = parent.getItemAtPosition(position).toString() } override fun onNothingSelected(parent: AdapterView<*>) { selectedTag = parent.getItemAtPosition(0).toString() } } ArrayAdapter(this, android.R.layout.simple_spinner_item, tagList) .also { adapter -> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) addTagDropdown.adapter = adapter } } private fun setupSaveGifticonBtn() { val saveGifticonBtn = findViewById<Button>(R.id.addGifticonConfirmButton) saveGifticonBtn.setOnClickListener { if (!isValidGifticon()) return@setOnClickListener val barcode = findViewById<EditText>(R.id.barcodeEdit).text.toString() val gifticonProvider = findViewById<EditText>(R.id.providerEdit).text.toString() val gifticonContent = findViewById<EditText>(R.id.contentEdit).text.toString() val imagePath = if (localImageUrl == null) "" else saveBitmapImage(uri2bitmap(localImageUrl!!)!!)!! val gifticon = Gifticon(imagePath, barcode, selectedTag!!, gifticonProvider, gifticonContent, expiredDate!!) val intent = Intent() intent.putExtra("gifticon", gifticon) setResult(RESULT_OK, intent) finish() } } private fun uri2bitmap(uri: Uri): Bitmap? { return try { val pfd = contentResolver.openFileDescriptor(uri, "r") val fd = pfd?.fileDescriptor val image = BitmapFactory.decodeFileDescriptor(fd) pfd?.close() return image } catch (e: IOException) { e.printStackTrace() toast(this, "이미지를 불러오는데 실패했습니다.") return null } } private fun saveBitmapImage(bitmap: Bitmap): String? { val filename = "${System.currentTimeMillis()}.jpg" val dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES) val file = File(dir, filename) try { val out = FileOutputStream(file) bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out) out.flush() out.close() } catch (e: Exception) { e.printStackTrace() toast(this, "이미지를 저장하는데 실패했습니다.") return null } return file.absolutePath } private fun isValidGifticon(): Boolean { val gifticonProvider = findViewById<EditText>(R.id.providerEdit).text.toString() if (gifticonProvider.isEmpty()) { toast(this, "사용처를 입력해주세요.") return false } val gifticonContent = findViewById<EditText>(R.id.contentEdit).text.toString() if (gifticonContent.isEmpty()) { toast(this, "상품명을 입력해주세요.") return false } val barcode = findViewById<EditText>(R.id.barcodeEdit).text.toString() if (barcode.isEmpty()) { toast(this, "바코드를 입력해주세요.") return false } if (expiredDate == null) { toast(this, "유효기간을 선택해주세요.") return false } if (selectedTag == null) { toast(this, "태그를 선택해주세요.") return false } return true } }
0
Kotlin
0
0
ad0e742d69bc1b4e051397a5ea13daf82a7d2999
6,562
skku-swe3047-GiftiZone
Apache License 2.0
library/src/main/java/com/zerogdev/library/OverlapRecyclerView.kt
zerogdev
183,883,921
false
null
package com.zerogdev.library import android.content.Context import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.util.AttributeSet class OverlapRecyclerView : RecyclerView { var selectedPosition = 0 set(value) { field = value adapter?.notifyDataSetChanged() } constructor(context: Context) : super(context) { init() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) { init() } fun init() { isChildrenDrawingOrderEnabled = true } override fun getChildDrawingOrder(childCount: Int, i: Int): Int { if (layoutManager is LinearLayoutManager) { var selectedPosition = this.selectedPosition - (layoutManager as LinearLayoutManager).findFirstVisibleItemPosition() if (selectedPosition < 0 || i < selectedPosition) { return i } else { if (i == childCount - 1) { return selectedPosition } else if (i >= selectedPosition) { return i + 1 } else { return i } } } return i } }
0
Kotlin
0
2
fb600abb1b536807a459e39b5cb6242ddd73c530
1,387
OverlapRecyclerView-kotlin
Apache License 2.0
tmp/arrays/kotlinAndJava/429.kt
mandelshtamd
249,374,670
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
//File D.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class D { @Nullable private final Integer a; @Nullable public final Integer getA() { return this.a; } public D(@Nullable Integer a) { this.a = a; } @Nullable public final Integer component1() { return this.a; } @NotNull public final D copy(@Nullable Integer a) { return new D(a); } // $FF: synthetic method public static D copy$default(D var0, Integer var1, int var2, Object var3) { if ((var2 & 1) != 0) { var1 = var0.a; } return var0.copy(var1); } @NotNull public String toString() { return "D(a=" + this.a + ")"; } public int hashCode() { Integer var10000 = this.a; return var10000 != null ? var10000.hashCode() : 0; } public boolean equals(@Nullable Object var1) { if (this != var1) { if (var1 instanceof D) { D var2 = (D)var1; if (Intrinsics.areEqual(this.a, var2.a)) { return true; } } return false; } else { return true; } } } //File A.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class A { @Nullable private final Object a; private int x; @Nullable public final Object getA() { return this.a; } public final int getX() { return this.x; } public final void setX(int var1) { this.x = var1; } public A(@Nullable Object a, int x) { this.a = a; this.x = x; } @Nullable public final Object component1() { return this.a; } public final int component2() { return this.x; } @NotNull public final A copy(@Nullable Object a, int x) { return new A(a, x); } // $FF: synthetic method public static A copy$default(A var0, Object var1, int var2, int var3, Object var4) { if ((var3 & 1) != 0) { var1 = var0.a; } if ((var3 & 2) != 0) { var2 = var0.x; } return var0.copy(var1, var2); } @NotNull public String toString() { return "A(a=" + this.a + ", x=" + this.x + ")"; } public int hashCode() { Object var10000 = this.a; return (var10000 != null ? var10000.hashCode() : 0) * 31 + Integer.hashCode(this.x); } public boolean equals(@Nullable Object var1) { if (this != var1) { if (var1 instanceof A) { A var2 = (A)var1; if (Intrinsics.areEqual(this.a, var2.a) && this.x == var2.x) { return true; } } return false; } else { return true; } } } //File B.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class B { @Nullable private final Object a; @Nullable public final Object getA() { return this.a; } public B(@Nullable Object a) { this.a = a; } @Nullable public final Object component1() { return this.a; } @NotNull public final B copy(@Nullable Object a) { return new B(a); } // $FF: synthetic method public static B copy$default(B var0, Object var1, int var2, Object var3) { if ((var2 & 1) != 0) { var1 = var0.a; } return var0.copy(var1); } @NotNull public String toString() { return "B(a=" + this.a + ")"; } public int hashCode() { Object var10000 = this.a; return var10000 != null ? var10000.hashCode() : 0; } public boolean equals(@Nullable Object var1) { if (this != var1) { if (var1 instanceof B) { B var2 = (B)var1; if (Intrinsics.areEqual(this.a, var2.a)) { return true; } } return false; } else { return true; } } } //File Main.kt fun box() : String { if( A(null,19).hashCode() != 19) "fail" if( A(239,19).hashCode() != (239*31+19)) "fail" if( B(null).hashCode() != 0) "fail" if( B(239).hashCode() != 239) "fail" if( C(239,19).hashCode() != (239*31+19)) "fail" if( C(239,null).hashCode() != 239*31) "fail" if( D(239).hashCode() != (239)) "fail" if( D(null).hashCode() != 0) "fail" return "OK" } //File C.java import kotlin.Metadata; import kotlin.jvm.internal.Intrinsics; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public final class C { private final int a; @Nullable private Integer x; public final int getA() { return this.a; } @Nullable public final Integer getX() { return this.x; } public final void setX(@Nullable Integer var1) { this.x = var1; } public C(int a, @Nullable Integer x) { this.a = a; this.x = x; } public final int component1() { return this.a; } @Nullable public final Integer component2() { return this.x; } @NotNull public final C copy(int a, @Nullable Integer x) { return new C(a, x); } // $FF: synthetic method public static C copy$default(C var0, int var1, Integer var2, int var3, Object var4) { if ((var3 & 1) != 0) { var1 = var0.a; } if ((var3 & 2) != 0) { var2 = var0.x; } return var0.copy(var1, var2); } @NotNull public String toString() { return "C(a=" + this.a + ", x=" + this.x + ")"; } public int hashCode() { int var10000 = Integer.hashCode(this.a) * 31; Integer var10001 = this.x; return var10000 + (var10001 != null ? var10001.hashCode() : 0); } public boolean equals(@Nullable Object var1) { if (this != var1) { if (var1 instanceof C) { C var2 = (C)var1; if (this.a == var2.a && Intrinsics.areEqual(this.x, var2.x)) { return true; } } return false; } else { return true; } } }
1
null
1
1
da010bdc91c159492ae74456ad14d93bdb5fdd0a
6,268
bbfgradle
Apache License 2.0
aoc-2017/src/test/kotlin/com/capital7software/aoc/aoc2017aoc/days/Day24Test.kt
vjpalodichuk
732,520,514
false
{"Gradle Kotlin DSL": 11, "Markdown": 8, "Java Properties": 1, "Shell": 1, "Text": 256, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "INI": 1, "YAML": 2, "Java": 225, "Kotlin": 184, "JSON": 5, "XML": 1}
package com.capital7software.aoc.aoc2017aoc.days import com.capital7software.aoc.lib.AdventOfCodeTestBase import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.slf4j.Logger import org.slf4j.LoggerFactory class Day24Test : AdventOfCodeTestBase() { companion object { val log: Logger = LoggerFactory.getLogger(Day24Test::class.java) } override fun getLogger(): Logger { return log } @BeforeEach fun setup() { val instance = Day24() setupFromFile(instance.defaultInputFilename) } @Test fun testGetStrongestBridge() { val instance = Day24() val expected = 31 val actual = instance.getStrongestBridge(lines).sumOf { it.strength } Assertions.assertEquals( expected, actual, "$actual for the strongest bridge strength " + "is not what was expected: $expected" ) } @Test fun testGetLongestThenStrongestBridge() { val instance = Day24() val expected = 19 val actual = instance.getLongestThenStrongestBridge(lines).sumOf { it.strength } Assertions.assertEquals( expected, actual, "$actual for the longest then strongest bridge strength " + "is not what was expected: $expected" ) } }
0
Java
0
0
da28d59b406f2e7e18cb32ade0d828a590d896c2
1,267
advent-of-code
Apache License 2.0
ui/integration-tests/benchmark/src/androidTest/java/androidx/ui/benchmark/test/view/AndroidNestedScrollViewBenchmark.kt
syntaxxxxx
286,529,729
true
{"Java Properties": 20, "Shell": 44, "Markdown": 43, "Java": 4516, "HTML": 17, "Kotlin": 3557, "Python": 28, "Proguard": 37, "Batchfile": 6, "JavaScript": 1, "CSS": 1, "TypeScript": 6, "Gradle Kotlin DSL": 2, "INI": 1, "CMake": 1, "C++": 2}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.ui.benchmark.test.view import androidx.test.filters.LargeTest import androidx.ui.benchmark.AndroidBenchmarkRule import androidx.ui.benchmark.benchmarkDrawPerf import androidx.ui.benchmark.benchmarkFirstDraw import androidx.ui.benchmark.benchmarkFirstLayout import androidx.ui.benchmark.benchmarkFirstMeasure import androidx.ui.benchmark.benchmarkFirstSetContent import androidx.ui.benchmark.benchmarkLayoutPerf import androidx.ui.benchmark.toggleStateBenchmarkDraw import androidx.ui.benchmark.toggleStateBenchmarkLayout import androidx.ui.benchmark.toggleStateBenchmarkMeasure import androidx.ui.integration.test.view.AndroidNestedScrollViewTestCase import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 /** * Benchmark that runs [AndroidNestedScrollViewTestCase]. */ @LargeTest @RunWith(JUnit4::class) class AndroidNestedScrollViewBenchmark { @get:Rule val benchmarkRule = AndroidBenchmarkRule() private val nestedScrollCaseFactory = { AndroidNestedScrollViewTestCase() } @Test fun first_setContent() { benchmarkRule.benchmarkFirstSetContent(nestedScrollCaseFactory) } @Test fun first_measure() { benchmarkRule.benchmarkFirstMeasure(nestedScrollCaseFactory) } @Test fun first_layout() { benchmarkRule.benchmarkFirstLayout(nestedScrollCaseFactory) } @Test fun first_draw() { benchmarkRule.benchmarkFirstDraw(nestedScrollCaseFactory) } @Test fun changeScroll_measure() { benchmarkRule.toggleStateBenchmarkMeasure(nestedScrollCaseFactory) } @Test fun changeScroll_layout() { benchmarkRule.toggleStateBenchmarkLayout(nestedScrollCaseFactory) } @Test fun changeScroll_draw() { benchmarkRule.toggleStateBenchmarkDraw(nestedScrollCaseFactory) } @Test fun layout() { benchmarkRule.benchmarkLayoutPerf(nestedScrollCaseFactory) } @Test fun draw() { benchmarkRule.benchmarkDrawPerf(nestedScrollCaseFactory) } }
0
null
0
1
e4ce477393fc1026f45fe67b73d8400f19e83975
2,696
androidx
Apache License 2.0
kamp-streamer/src/main/kotlin/ch/leadrian/samp/kamp/streamer/api/callback/OnPlayerEnterStreamableCheckpoint.kt
Double-O-Seven
142,487,686
false
{"Kotlin": 3854710, "C": 23964, "C++": 23699, "Java": 4753, "Dockerfile": 769, "Objective-C": 328, "Batchfile": 189}
package ch.leadrian.samp.kamp.streamer.api.callback import ch.leadrian.samp.kamp.annotations.CallbackListener import ch.leadrian.samp.kamp.annotations.InlineCallback import ch.leadrian.samp.kamp.annotations.Receiver import ch.leadrian.samp.kamp.core.api.entity.Player import ch.leadrian.samp.kamp.streamer.api.entity.StreamableCheckpoint @CallbackListener("ch.leadrian.samp.kamp.streamer.runtime.callback") interface OnPlayerEnterStreamableCheckpoint { @InlineCallback("onEnter") fun onPlayerEnterStreamableCheckpoint(player: Player, @Receiver streamableCheckpoint: StreamableCheckpoint) }
1
Kotlin
1
7
af07b6048210ed6990e8b430b3a091dc6f64c6d9
601
kamp
Apache License 2.0
app/src/main/java/io/github/gmathi/novellibrary/fragment/BaseFragment.kt
TechnoJo4
249,806,029
true
{"Kotlin": 649350, "Java": 33921}
package io.github.gmathi.novellibrary.fragment import androidx.fragment.app.Fragment open class BaseFragment : Fragment()
1
Kotlin
1
1
4a9e1b66c508430b6024319658bb50eb5a313e64
125
NovelLibrary
Apache License 2.0
app/src/main/java/cat/pantsu/nyaapantsu/model/RecentlyPlayed.kt
NyaaPantsu
95,310,436
false
null
package cat.pantsu.nyaapantsu.model import com.chibatching.kotpref.KotprefModel /** * Created by akuma06 on 04/07/2017. */ object RecentlyPlayed : KotprefModel() { var torrents by stringPref("") }
7
null
9
45
53ad9a80df926ae93037f14a51fc4d7b6bc66e83
205
NyaaPantsu-android-app
MIT License
src/main/kotlin/juuxel/adorn/gui/widget/WTabbedPanel.kt
Virtuoel
283,969,118
true
{"Gradle Kotlin DSL": 3, "Gradle": 1, "fish": 1, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 1, "Markdown": 3, "JSON": 1682, "INI": 1, "Kotlin": 176, "Java": 10, "JSON5": 4}
package juuxel.adorn.gui.widget import io.github.cottonmc.cotton.gui.widget.WPanel import io.github.cottonmc.cotton.gui.widget.WPlainPanel import io.github.cottonmc.cotton.gui.widget.WWidget import net.minecraft.text.Text /** * A panel that shows one widget at a time like [a card panel][WCardPanel], * but allows the user to change the tabs with buttons. */ class WTabbedPanel : WPanel() { private val buttonBar: WPlainPanel = WPlainPanel() private val cardPanel = WCardPanel() private val buttonGroup = WToggleableButton.Group() private var nextButtonX = 0 init { val panel = WPlainPanel() panel.add(buttonBar, 0, 0, 9 * 18, 18) panel.add(cardPanel, 0, 30) children.add(panel) panel.setLocation(0, 0) panel.setParent(this) expandToFit(panel) } fun addTab(label: Text, tab: WWidget, buttonWidth: Int = 3 * 18 + 9) { cardPanel.addCard(tab) val button = WToggleableButton(label) button.setOnClick { select(tab) } button.setGroup(buttonGroup) buttonBar.add(button, nextButtonX, 0, buttonWidth, 18) nextButtonX += buttonWidth + 5 } fun select(tab: WWidget) = cardPanel.select(tab) fun select(tab: Int) = cardPanel.select(tab) }
0
null
0
0
8a27dbd22e718ace72aef36f4bdd4ce81b41c753
1,316
Adorn
MIT License
app/src/main/java/com/studenthealth/android/ui/health/BodyWeightActivity.kt
wm-develop
318,527,648
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "JSON": 1, "Kotlin": 74, "XML": 71, "Java": 3}
package com.studenthealth.android.ui.health import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MenuItem import com.studenthealth.android.R import kotlinx.android.synthetic.main.activity_body_weight.* class BodyWeightActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_body_weight) setSupportActionBar(bodyWeightToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() } return true } }
0
Kotlin
0
0
5f4c89244f8d61360b4e25aabbab3a6dc410baa4
733
StudentHealth
Apache License 2.0
app/src/main/java/com/dpashko/transitionapp/di/AppModule.kt
Dmytro-Pashko
222,957,438
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 1, "XML": 10, "Kotlin": 15, "Java": 1}
package com.dpashko.transitionapp.di import com.dpashko.transitionapp.api.CountriesApi import dagger.Module import dagger.Provides import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import javax.inject.Singleton @Module class AppModule { @Provides @Singleton fun provideApi(): CountriesApi = Retrofit.Builder() .baseUrl(CountriesApi.BASE_API_URL) .addConverterFactory(GsonConverterFactory.create()) .build() .create(CountriesApi::class.java) }
0
Kotlin
0
0
1bef10e23274f4083842a09cae6a692b34d23e16
518
TransitionApp
Apache License 2.0
idea/testData/multiModuleQuickFix/accessibilityChecker/topLevelProperty/jvm/Utils.kt
walltz556
207,476,848
true
{"Kotlin": 39975052, "Java": 7599429, "JavaScript": 160572, "HTML": 75060, "Lex": 23159, "TypeScript": 21255, "IDL": 11582, "ANTLR": 9803, "CSS": 8084, "Shell": 7727, "Groovy": 6940, "Batchfile": 5362, "Swift": 2253, "Ruby": 668, "Objective-C": 293, "Scala": 80}
// "Create expected property in common module testModule_Common" "true" // SHOULD_FAIL_WITH: You cannot create the expect declaration from:,actual val foo: Some = TODO() // DISABLE-ERRORS interface Some actual val foo<caret>: Some = TODO()
0
null
0
1
89d49479abab76ea1d4ffe5e45826f3b076c6f68
241
kotlin
Apache License 2.0
app/src/main/java/com/warlock/tmdb/data/db/AppDatabase.kt
rahulgothwal5
366,426,179
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "INI": 2, "Kotlin": 91, "XML": 116, "Java": 2, "PureBasic": 1}
package com.warlock.tmdb.data.db import android.content.Context import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import com.warlock.tmdb.data.db.dao.* import com.warlock.tmdb.data.db.entity.* @Database( entities = [MovieResult::class, GenreX::class, MovieCreditsData::class, MovieVideosDataResponse::class, MovieDetailDataResponse::class], version = 1, exportSchema = false ) @TypeConverters( IDConverter::class, MovieGenreConverter::class, MovieVideoConverter::class, MovieCreditCrewConverter::class, BelongsToCollectionConverter::class, MovieCreditCastConverter::class ) abstract class AppDatabase : RoomDatabase() { abstract fun movieDao(): MovieListDao abstract fun genreDao(): GenreListDao abstract fun movieCreditsDao(): MovieCreditDao abstract fun movieDetailDao(): MovieDetailDao abstract fun movieVideosDao(): MovieVideoDao companion object { private const val DATABASE_NAME = "tmdb.db" // For Singleton instantiation @Volatile private var instance: AppDatabase? = null /** * methos used to get instance of AppDatabase * @param context to build database instance * @return AppDatabase */ fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } /** * Create and pre-populate the database. * @param context to build database instance * @return AppDatabase */ private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) .addCallback(object : RoomDatabase.Callback() { }) .build() } } }
0
Kotlin
0
0
3264a8cb808f0184ffee394548b670efe7cdd33c
1,995
TMDB-App
MIT License
georocket-cli/src/main/kotlin/io/georocket/commands/SearchCommand.kt
georocket
58,203,049
false
null
package io.georocket.commands import de.undercouch.underline.InputReader import de.undercouch.underline.Option.ArgumentType import de.undercouch.underline.OptionDesc import de.undercouch.underline.UnknownAttributes import io.georocket.client.SearchParams import io.vertx.core.impl.NoStackTraceThrowable import io.vertx.core.logging.LoggerFactory import java.io.PrintWriter /** * Searches the GeoRocket data store and outputs the retrieved files */ class SearchCommand : AbstractQueryCommand() { companion object { private val log = LoggerFactory.getLogger(SearchCommand::class.java) } private var query: String? = null override val usageName = "search" override val usageDescription = "Search the GeoRocket data store" @set:OptionDesc(longName = "layer", shortName = "l", description = "absolute path to the layer to search", argumentName = "PATH", argumentType = ArgumentType.STRING) var layer: String? = null /** * Enable optimistic merging */ @set:OptionDesc(longName = "optimistic-merging", description = "enable optimistic merging") var optimisticMerging: Boolean = false /** * Set the query parts */ @UnknownAttributes("QUERY") @Suppress("UNUSED") fun setQueryParts(queryParts: List<String>) { // put quotes around query parts containing a space val quotedQueryParts = queryParts .map { if (it.contains(' ')) "\"$it\"" else it } .toList() // join all query parts using the space character this.query = quotedQueryParts.joinToString(" ") } override fun checkArguments(): Boolean { if (query == null || query!!.isEmpty()) { error("no search query given") return false } return super.checkArguments() } override suspend fun doRun(remainingArgs: Array<String>, i: InputReader, o: PrintWriter): Int { val params = SearchParams() .setQuery(query) .setLayer(layer) .setOptimisticMerging(optimisticMerging) return try { query(params, o) 0 } catch (t: Throwable) { error(t.message) if (t !is NoSuchElementException && t !is NoStackTraceThrowable) { log.error("Could not query store", t) } 1 } } }
0
null
25
57
7a3c82ee7a04a84907f7d5ec59742337be985bbd
2,234
georocket
Apache License 2.0
Network/src/main/java/com/nankung/network/model/response/result/CombinedCastResult.kt
anunkwp
245,392,754
false
null
package com.nankung.network.model.response.result import androidx.room.Entity import com.google.gson.annotations.SerializedName /** * Created by 「 <NAME> 」 on 17/3/2563. ^^ */ @Entity(tableName = "combined_cast", primaryKeys = ["id"]) data class CombinedCastResult( @SerializedName("id") val id: Int = 0, @SerializedName("character") val character: String? = "", @SerializedName("original_title") val original_title: String? = "", @SerializedName("overview") val overview: String? = "", @SerializedName("vote_count") val vote_count: Int? = 0, @SerializedName("media_type") val media_type: String? = "", @SerializedName("poster_path") val poster_path: String? = "", @SerializedName("backdrop_path") val backdrop_path: String? = "", @SerializedName("popularity") val popularity: Double? = 0.0, @SerializedName("title") val title: String? = "", @SerializedName("vote_average") val vote_average: Double? = 0.0, @SerializedName("release_date") val release_date: String? = "", @SerializedName("credit_id") val credit_id: String? = "" ) { override fun toString(): String { return "\n id='$id'," + "\n character='$character'\n"+ "\n original_title='$original_title'\n"+ "\n overview='$overview'\n"+ "\n vote_count='$vote_count'\n"+ "\n media_type='$media_type'\n"+ "\n poster_path='$poster_path'\n"+ "\n backdrop_path='$backdrop_path'\n"+ "\n popularity='$popularity'\n"+ "\n title='$title'\n"+ "\n vote_average='$vote_average'\n"+ "\n release_date='$release_date'\n"+ "\n credit_id='$credit_id'\n" } }
1
null
1
1
852c96bbd9b9d41d42f5c27248cbe3f219dc9fda
1,824
KotlinMvvmStructure
Apache License 2.0
app/src/main/java/lt/vilnius/tvarkau/dagger/component/ActivityComponent.kt
codefluencer
153,193,645
true
{"Kotlin": 284507, "Java": 72012}
package lt.vilnius.tvarkau.dagger.component import android.support.v7.app.AppCompatActivity import dagger.Subcomponent import lt.vilnius.tvarkau.BaseActivity import lt.vilnius.tvarkau.activity.LoginActivity import lt.vilnius.tvarkau.dagger.module.ActivityModule import lt.vilnius.tvarkau.dagger.module.MainActivityModule import lt.vilnius.tvarkau.fragments.AllReportsListFragment import lt.vilnius.tvarkau.fragments.BaseFragment import lt.vilnius.tvarkau.fragments.BaseMapFragment import lt.vilnius.tvarkau.fragments.MultipleProblemsMapFragment import lt.vilnius.tvarkau.fragments.MyReportsListFragment import lt.vilnius.tvarkau.fragments.NewReportFragment import lt.vilnius.tvarkau.fragments.PhotoInstructionsFragment import lt.vilnius.tvarkau.fragments.ReportDetailsFragment import lt.vilnius.tvarkau.fragments.ReportFilterFragment import lt.vilnius.tvarkau.fragments.ReportImportDialogFragment import lt.vilnius.tvarkau.fragments.ReportTypeListFragment import lt.vilnius.tvarkau.fragments.SettingsFragment @Subcomponent( modules = [ ActivityModule::class ] ) interface ActivityComponent { fun mainActivityComponent(mainActivityModule: MainActivityModule): MainActivityComponent fun inject(loginActivity: LoginActivity) fun inject(allReportsListFragment: AllReportsListFragment) fun inject(myReportsListFragment: MyReportsListFragment) fun inject(baseMapFragment: BaseMapFragment) fun inject(fragment: MultipleProblemsMapFragment) fun inject(settingsFragment: SettingsFragment) fun inject(activity: BaseActivity) fun inject(fragment: BaseFragment) fun inject(fragment: ReportImportDialogFragment) fun inject(fragment: NewReportFragment) fun inject(fragment: PhotoInstructionsFragment) fun inject(fragment: ReportTypeListFragment) fun inject(fragment: ReportFilterFragment) fun inject(fragment: ReportDetailsFragment) companion object { fun init( applicationComponent: ApplicationComponent, activity: AppCompatActivity ): ActivityComponent { return applicationComponent.activityComponent(ActivityModule(activity)) } } }
0
Kotlin
0
0
7ea3ff5970bacd976d06b0c0b2afa1569552272b
2,185
tvarkau-vilniu
MIT License
composeApp/src/commonMain/kotlin/screen/NavigationStack.kt
mjaremczuk
732,345,154
false
{"Kotlin": 28092, "HTML": 304}
package screen import androidx.compose.runtime.mutableStateListOf class NavigationStack<T>(val initial: T) { private val stack = mutableStateListOf(initial) fun push(t: T) { stack.add(t) } fun back() { if (stack.size > 1) { stack.removeLast() } } fun lastWithIndex() = stack.withIndex().last() fun clear() { stack.clear() stack.add(initial) // stack = mutableStateListOf(initial) } }
0
Kotlin
0
0
efa8fce42e4963b7e26c49b93789496edb40e039
478
ProjectsHelper
Apache License 2.0
app/src/main/java/com/example/fetchassesment/view/BaseViewHolder.kt
NirvanaDogra
706,349,308
false
{"Kotlin": 23697}
package com.example.fetchassesment.view import android.view.View import androidx.recyclerview.widget.RecyclerView import com.example.fetchassesment.model.BaseHiringListDataModel abstract class BaseViewHolder(view: View) : RecyclerView.ViewHolder(view) { abstract fun bind(baseListDataModel: BaseHiringListDataModel) }
0
Kotlin
0
0
5f7d7fac4de35d7916b33bde6eaed7ab248464ac
323
FetchAndroid
Apache License 2.0
app/src/main/java/com/example/totalhealth/FoodItemsAdapter.kt
GreyActOwl1
782,594,323
false
{"Kotlin": 27946}
package com.example.totalhealth import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class FoodItemsAdapter(private val foodItems: MutableList<FoodItemEntity>) : RecyclerView.Adapter<FoodItemsAdapter.ViewHolder>(){ inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val foodItemNameTextView: TextView = itemView.findViewById(R.id.food_item_name_text_view) val foodItemCaloriesTextView: TextView = itemView.findViewById(R.id.food_item_calories_text_view) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.food_item, parent, false)) } override fun getItemCount(): Int { return foodItems.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val foodEntry = foodItems[position] holder.foodItemNameTextView.text = foodEntry.name holder.foodItemCaloriesTextView.text = foodEntry.calories.toString() } }
0
Kotlin
0
0
f3f26ba57acb8028c58568588f39320f8f90a06d
1,160
TotalHealth2
Apache License 2.0
app/src/main/java/ua/polodarb/gmsflags/ui/screens/suggestions/SuggestedFlag.kt
polodarb
624,518,043
false
{"Kotlin": 400464, "AIDL": 1483}
package ua.polodarb.gmsflags.ui.screens.suggestions import ua.polodarb.gmsflags.data.remote.flags.dto.SuggestedFlagInfo data class SuggestedFlag( val flag: SuggestedFlagInfo, val enabled: Boolean )
0
Kotlin
2
76
1155aa24caeb7372f88bbbaa5ccfbb3763b89d2b
208
GMS-Flags
MIT License
app/src/main/java/com/yz/books/ui/main/MainModel.kt
zhangkari
303,389,564
false
null
package com.yz.books.ui.main import androidx.lifecycle.MutableLiveData import com.yz.books.base.model.BaseModel import com.yz.books.base.viewmodel.ErrorState import com.yz.books.base.viewmodel.LoadedState import com.yz.books.base.viewmodel.LoadingState import com.yz.books.base.viewmodel.State import com.yz.books.common.Constant import com.yz.books.db.DaoHelper import com.yz.books.ui.main.bean.* import com.yz.books.ui.manager.IManager /** * @author lilin * @time on 2020-01-14 20:48 */ class MainModel : BaseModel(), IMain, IManager { override fun bindLiveData(state: MutableLiveData<State>) { mBaseState = state } class MachineCodeState(val machineInfoBean: MachineInfoBean?): State() class MainResourcesState(val mainResourcesBean: MainResourcesBean?): State() class UpdateDBState(val updateDBBean: UpdateDBBean?): State() class AppUpdateState(val appUpdateBean: AppUpdateBean?): State() class DownloadResourceState(val downloadResourceList: MutableList<CheckDownloadResourceBean>?): State() override fun checkMachineCode(machineCode: String) { requestData<MachineInfoBean>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = MachineCodeState(data) } request { mApiService.checkMachineCode(machineCode) } } } override fun updateBD(machineCode: String) { requestData<UpdateDBBean>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = UpdateDBState(data) } request { mApiService.updateDB(machineCode) } } } override fun getMainResources() { //LogUtils.e("getMainResources==") if (!Constant.ONLINE_VERSION) { val data = DaoHelper.getMainResources() mBaseState.value = MainResourcesState(data) return } requestData<MainResourcesBean>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = MainResourcesState(data) } request { mApiService.getMainResources() } } } override fun checkAppUpdate() { requestData<AppUpdateBean>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = AppUpdateState(data) } request { val directionType = if (!Constant.SCREEN_ORIENTATION_LANDSCAPE) { 2 } else { 1 } mApiService.checkAppUpdate(directionType) } } } override fun checkDownloadResource() { requestData<MutableList<CheckDownloadResourceBean>>().apply { loading { mBaseState.value = LoadingState() } loaded { mBaseState.value = LoadedState() } fail { code, message -> mBaseState.value = ErrorState(message, code) } success { data, _ -> mBaseState.value = DownloadResourceState(data) } request { mApiService.checkDownloadResource() } } } }
0
null
2
1
90784936a9ec75e702120941fbfac6f1b40b93d5
4,391
yzlauncher
Apache License 2.0
story/src/commonMain/kotlin/kr/progress/story/format/save/IntVariable.kt
progress-studio
828,407,319
false
{"Kotlin": 69159}
package kr.progress.story.format.save import kr.progress.story.parser.XMLBody import kr.progress.story.parser.XMLDecodable import kr.progress.story.parser.XMLNode data class IntVariable( override val id: String, val value: Int, override val extraAttributes: Map<String, String> = emptyMap() ) : Variable() { companion object : XMLDecodable<IntVariable> { override operator fun invoke(node: XMLNode): IntVariable { val attributes = node.attributes.toMutableMap() return IntVariable( id = attributes.remove("id")!!, value = (node.body as XMLBody.Value).body.toInt(), extraAttributes = attributes ) } fun new( from: kr.progress.story.format.project.IntVariable ) = IntVariable( id = from.id, value = from.default ?: 0 ) } override fun toXMLNode() = XMLNode( tag = "int", attributes = mapOf("id" to id) + extraAttributes, body = XMLBody.Value(value.toString()) ) }
0
Kotlin
0
4
c2c3c78ba31c4d6c013840e8eb8db164843a6345
1,076
Story
MIT License
app/src/main/java/com/benrostudios/enchante/data/models/response/events/CoordinatesX.kt
EnchanteHQ
380,800,255
false
null
package com.benrostudios.enchante.data.models.response.events data class CoordinatesX( val lat: String? = "", val lon: String? = "" )
0
Kotlin
0
0
67cf14e4929105fcc7b2d1c8ad35136ea2c5f154
142
enchante
MIT License
src/main/kotlin/xyz/prpht/toolbox/containers/trees/BTNodeToDownStrs.kt
ilyawaisman
204,491,894
false
null
package xyz.prpht.toolbox.containers.trees import xyz.prpht.toolbox.strings.alignCenter import xyz.prpht.toolbox.strings.prePost /** * Creates pretty binary tree (see [BTNode]) strings representation. * Could be composed with [xyz.prpht.toolbox.strings.printlns] for example. */ fun <T> BTNode<T>?.toDownStrs(toStr: (T) -> String = { it.toString() }): List<String> { if (this == null) return emptyList() val btInfo = toInfo(toStr) val result = arrayListOf(btInfo.header(' ', ' ')) var layer = listOf<LineChunk>(NodeChunk(btInfo)) while (layer.any { it.hasChildren() }) { result.add(layer.joinToString("") { it.childrenStr() }) layer = layer.flatMap { it.subChunks() } } return result } private data class NodeInfo(val str: String, val width: Int) private fun BTNode<NodeInfo>?.width() = this?.value?.width ?: 0 private fun <T> BTNode<T>.toInfo(toStr: (T) -> String): BTNode<NodeInfo> { val leftInfo = left?.toInfo(toStr) val rightInfo = right?.toInfo(toStr) val str = toStr(value) val info = NodeInfo(str, leftInfo.width() + str.length + rightInfo.width()) return BTNode(info, leftInfo, rightInfo) } private fun BTNode<NodeInfo>?.header(leftChar: Char, rightChar: Char) = this?.run { value.str.prePost(left.width(), leftChar, right.width(), rightChar) } ?: "" private fun BTNode<*>?.armFiller() = if (this == null) ' ' else '-' private interface LineChunk { fun subChunks(): List<LineChunk> fun hasChildren(): Boolean fun childrenStr(): String } private class SimpleChunk(private val len: Int) : LineChunk { override fun subChunks() = listOf(this) override fun hasChildren() = false override fun childrenStr() = " ".repeat(len) } private class NodeChunk(private val node: BTNode<NodeInfo>) : LineChunk { override fun subChunks() = listOfNotNull(node.left?.let(::NodeChunk), SimpleChunk(node.value.str.length), node.right?.let(::NodeChunk)) override fun hasChildren() = node.left != null || node.right != null override fun childrenStr(): String { val downArm = if (hasChildren()) "'" else " " val downPart = downArm.alignCenter(node.value.str.length, node.left.armFiller(), node.right.armFiller()) return node.left.header(' ', '-') + downPart + node.right.header('-', ' ') } }
0
Kotlin
0
0
99e3e9bd90579dc1e3c3c0ac7ca283d7b83cd319
2,327
toolbox
MIT License
app/src/main/java/com/example/socialk/home/HomeFragment.kt
adampalkowski
585,752,372
false
null
package com.example.socialk.home import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.compose.ui.platform.ComposeView import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import com.example.socialk.Chats import com.example.socialk.Create import com.example.socialk.Home import com.example.socialk.Main.Screen import com.example.socialk.Main.navigate import com.example.socialk.Profile import com.example.socialk.di.ActiveUsersViewModel import com.example.socialk.di.ActivityViewModel import com.example.socialk.di.ChatViewModel import com.example.socialk.model.UserData import com.example.socialk.signinsignup.AuthViewModel import com.example.socialk.ui.theme.SocialTheme import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class HomeFragment : Fragment() { private val viewModel by activityViewModels<HomeViewModel>() private val authViewModel by viewModels<AuthViewModel>() private val chatViewModel by viewModels<ChatViewModel>() private val activityViewModel by activityViewModels<ActivityViewModel>() private val activeUsersViewModel by viewModels<ActiveUsersViewModel>() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModel.navigateTo.observe(viewLifecycleOwner) { navigateToEvent -> navigateToEvent.getContentIfNotHandled()?.let { navigateTo -> if (navigateTo == Screen.Chat) { val bundle = Bundle() bundle.putSerializable("activity", viewModel.clicked_chat_activity.value) navigate(navigateTo, Screen.Home, bundle) } else if (navigateTo == Screen.Map) { val bundle = Bundle() bundle.putSerializable("latlng", viewModel.clicked_location_activity.value) navigate(navigateTo, Screen.Home, bundle) } else if (navigateTo == Screen.UserProfile) { val bundle = Bundle() bundle.putSerializable("user_id",viewModel.clicked_profile.value) navigate(navigateTo, Screen.Home, bundle) }else{ navigate(navigateTo, Screen.Home) } } } activityViewModel?.getActivitiesForUser(authViewModel?.currentUser?.uid) activeUsersViewModel?.getActiveUsersForUser(authViewModel?.currentUser?.uid) viewModel.activity_link.value.let { if (it != null) { Log.d("HomeFragment", it.toString()) activityViewModel.getActivity(it) viewModel.resetLink() } } return ComposeView(requireContext()).apply { setContent { SocialTheme { HomeScreen(activeUsersViewModel, activityViewModel, chatViewModel = chatViewModel, authViewModel, homeViewModel = viewModel, onEvent = { event -> when (event) { is HomeEvent.GoToProfile -> viewModel.handleGoToProfile() is HomeEvent.LogOut -> viewModel.handleLogOut() is HomeEvent.GoToSettings -> viewModel.handleGoToSettings() is HomeEvent.GoToMemories -> viewModel.handleGoToMemories() is HomeEvent.GoToMap -> { viewModel.handleGoToMapActivity(event.latlng) } is HomeEvent.GoToProfileWithID -> { viewModel.handleGoToUserProfile(event.user_id) } is HomeEvent.GoToChat -> { viewModel.handleGoToChat(event.activity) } is HomeEvent.ActivityLiked -> { activityViewModel.likeActivity( event.activity.id, UserData.user!! ) } is HomeEvent.ActivityUnLiked -> { activityViewModel.unlikeActivity( event.activity.id, UserData.user!! ) } } }, bottomNavEvent = { screen -> when (screen) { is Home -> viewModel.handleGoToHome() is com.example.socialk.Map -> viewModel.handleGoToMap() is Chats -> viewModel.handleGoToChats() is Profile -> viewModel.handleGoToProfile() is Create -> viewModel.handleGoToCreate() } } ) } } } } }
0
Kotlin
0
0
05ce66b93e61f19dd80bfe36adf9dbc4f8387976
5,755
SocialK
MIT License
app/src/main/java/com/brins/pet/BaseApplication.kt
BrinsLee
319,191,513
false
null
package com.brins.pet import android.app.Activity import android.app.Application import android.content.Context import android.os.Bundle import com.alibaba.android.arouter.launcher.ARouter import com.brins.lib_appbase.config.MAIN_PROCESS_NAME import com.brins.lib_appbase.manager.ActivityManager import com.brins.lib_appbase.utils.AppUtils import com.brins.lib_appbase.utils.UIUtils import com.brins.lib_appbase.utils.getCurrProcessName import com.brins.lib_bridge.BridgeInterface import com.brins.lib_bridge.factory.Factory import com.brins.lib_bridge.provider.BridgeProviders import com.brins.pet.bridge.AppBridge import dagger.hilt.android.HiltAndroidApp import javax.inject.Inject /** * Created by lipeilin * on 2020/12/8 */ @HiltAndroidApp class BaseApplication : Application() { @Inject lateinit var mBridge: BridgeProviders companion object { @JvmStatic var sInstance: BaseApplication? = null fun getInstance(): BaseApplication { if (sInstance == null) { throw NullPointerException("please inherit com.brins.pet.BaseApplication or call setApplication.") } return sInstance!! } } override fun onCreate() { super.onCreate() setApplication(this) if (isMainProcess(this)) { UIUtils.init(this) AppUtils.init(this) initARouter() registerBridge() } } /** * 注册组件Bridge * */ @Suppress("UNCHECKED_CAST") private fun registerBridge() { mBridge.register(AppBridge::class.java, object : Factory { override fun <T : BridgeInterface> create(bridgeClazz: Class<T>): T { return AppBridge() as T } }) } /** * 注册Activity生命周期 * * @param application */ private fun setApplication(application: BaseApplication) { sInstance = application application.registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks { override fun onActivityPaused(activity: Activity?) { } override fun onActivityResumed(activity: Activity?) { } override fun onActivityStarted(activity: Activity?) { } override fun onActivityDestroyed(activity: Activity?) { ActivityManager.getInstance().removeActivity(activity) } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { ActivityManager.getInstance().addActivity(activity) } }) } /** * 判断是否在主进程 * * @param context * @return */ private fun isMainProcess(context: Context): Boolean { return MAIN_PROCESS_NAME == getCurrProcessName(context) } /** * 初始化ARouter * */ private fun initARouter() { if (BuildConfig.DEBUG) { ARouter.openLog() ARouter.openDebug() } ARouter.init(this) } }
1
null
1
1
8e8995383ae447a5cdadbd478a7e5d2c3f3bc7e5
3,239
pet
Apache License 2.0
app/src/main/java/io/traxa/ui/startup/StartupActivity.kt
chrisinvb
517,052,842
false
{"Kotlin": 213490, "Java": 18186}
package io.traxa.ui.startup import android.app.Activity import android.content.Intent import android.os.Bundle import dispatch.core.ioDispatcher import io.traxa.persistence.AppDatabase import io.traxa.services.Prefs import io.traxa.ui.main.MainActivity import io.traxa.ui.onboard.OnboardActivity import io.traxa.ui.upload.UploadActivity import io.traxa.utils.Constants import io.traxa.utils.MeanColorClassifier import kotlinx.coroutines.* import org.koin.android.ext.android.inject import kotlin.math.pow class StartupActivity : Activity() { private val prefs: Prefs by inject() private val db: AppDatabase by inject() private val containerDao = db.containerDao() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val isFirstTimeOpened = prefs.isFirstTimeOpened() var waitingTime = Constants.waitingTime CoroutineScope(Dispatchers.Main).launch { val count = withContext(ioDispatcher) { containerDao.getContainerCount() } val rewardNumber = 5 * (count/5) if(rewardNumber != 0) { val timeReward = Constants.timeRewards[rewardNumber] ?: Constants.maxTimeReward println("Time reward: $timeReward") waitingTime -= (timeReward / 60f) } MeanColorClassifier.init() delay(1000) if(isFirstTimeOpened) { startActivity(Intent(this@StartupActivity, OnboardActivity::class.java)) finish() }else { val currentTime = System.currentTimeMillis() / 1000 val elapsed = currentTime - prefs.getUploadStartTime() var defaultIntent = Intent(this@StartupActivity, MainActivity::class.java) if (elapsed < 60 * waitingTime) defaultIntent = Intent(this@StartupActivity, UploadActivity::class.java) else prefs.clearUploadStartTime() startActivity(defaultIntent) finish() } } } }
0
Kotlin
0
0
a21ba2aa3dfa3056083b0f72c644c913c3df45b8
2,099
traxaio_android_polygon_filecoin
MIT License
app/src/main/java/com/marcdonald/hibi/uicomponents/views/SearchBar.kt
MarcDonald
163,665,694
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marcdonald.hibi.uicomponents.views import android.content.Context import android.util.AttributeSet import android.view.KeyEvent import android.view.LayoutInflater import android.view.View import android.view.View.OnClickListener import android.view.View.OnKeyListener import android.widget.EditText import android.widget.ImageView import androidx.constraintlayout.widget.ConstraintLayout import com.marcdonald.hibi.R class SearchBar(context: Context, attributeSet: AttributeSet?, defStyle: Int) : ConstraintLayout(context, attributeSet, defStyle) { private var editText: EditText private var searchButton: ImageView init { val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater val view = inflater.inflate(R.layout.view_search_bar, this, true) editText = view.findViewById(R.id.edt_search_bar) searchButton = view.findViewById(R.id.img_search_button) if(attributeSet != null) { val attributes = context.obtainStyledAttributes(attributeSet, R.styleable.SearchBar, defStyle, 0) val hint = attributes.getString(R.styleable.SearchBar_sbHint) editText.hint = hint attributes.recycle() } } constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) fun setHint(hint: String) { editText.hint = hint } fun setSearchAction(searchAction: (searchTerm: String) -> Unit) { val buttonClickListener = OnClickListener { search(searchAction) } searchButton.setOnClickListener(buttonClickListener) val searchOnEnterListener = OnKeyListener { _: View, keyCode: Int, keyEvent: KeyEvent -> if((keyEvent.action == KeyEvent.ACTION_DOWN) && keyCode == KeyEvent.KEYCODE_ENTER) { search(searchAction) } false } editText.setOnKeyListener(searchOnEnterListener) } fun search(searchAction: (searchTerm: String) -> Unit) { val input = editText.text.toString() if(input.isNotBlank()) { searchAction(input) editText.setText("") } else { editText.error = resources.getString(R.string.no_search_term_warning) } } }
2
Kotlin
4
38
eabf13cc335381d66a128b3baad174a96fdfad64
2,683
Hibi
Apache License 2.0
subprojects/gradle/instrumentation-tests/src/main/kotlin/com/avito/instrumentation/reservation/devices/provider/DevicesProviderFactory.kt
ussernamenikita
311,762,440
true
{"Kotlin": 2404460, "HTML": 121161, "Shell": 16845, "Python": 14168, "Dockerfile": 7119, "Makefile": 3035}
package com.avito.instrumentation.reservation.devices.provider import com.avito.instrumentation.configuration.InstrumentationConfiguration import com.avito.instrumentation.configuration.InstrumentationConfiguration.Data.DevicesType.CLOUD import com.avito.instrumentation.configuration.InstrumentationConfiguration.Data.DevicesType.LOCAL import com.avito.instrumentation.configuration.InstrumentationConfiguration.Data.DevicesType.MOCK import com.avito.instrumentation.executing.ExecutionParameters import com.avito.instrumentation.reservation.adb.AndroidDebugBridge import com.avito.instrumentation.reservation.adb.EmulatorsLogsReporter import com.avito.instrumentation.reservation.client.kubernetes.KubernetesReservationClient import com.avito.instrumentation.reservation.client.kubernetes.ReservationDeploymentFactory import com.avito.runner.service.worker.device.adb.Adb import com.avito.runner.service.worker.device.adb.AdbDevicesManager import com.avito.utils.gradle.KubernetesCredentials import com.avito.utils.gradle.createKubernetesClient import com.avito.utils.logging.CILogger import com.avito.utils.logging.commonLogger import java.io.File interface DevicesProviderFactory { fun create( configuration: InstrumentationConfiguration.Data, executionParameters: ExecutionParameters ): DevicesProvider class Impl( private val kubernetesCredentials: KubernetesCredentials, private val buildId: String, private val buildType: String, private val projectName: String, private val registry: String, private val output: File, private val logcatDir: File, private val logger: CILogger ) : DevicesProviderFactory { override fun create( configuration: InstrumentationConfiguration.Data, executionParameters: ExecutionParameters ): DevicesProvider { val adb = Adb() val androidDebugBridge = AndroidDebugBridge( adb = adb, logger = { logger.info(it) } ) val emulatorsLogsReporter = EmulatorsLogsReporter( outputFolder = output, logcatTags = executionParameters.logcatTags, logcatDir = logcatDir ) val devicesManager = AdbDevicesManager(adb = adb, logger = commonLogger(logger)) return when (configuration.requestedDeviceType) { MOCK -> { MockDevicesProvider(logger) } LOCAL -> { LocalDevicesProvider( androidDebugBridge = androidDebugBridge, devicesManager = devicesManager, emulatorsLogsReporter = emulatorsLogsReporter, adb = adb, logger = logger ) } CLOUD -> { KubernetesDevicesProvider( client = KubernetesReservationClient( androidDebugBridge = androidDebugBridge, kubernetesClient = createKubernetesClient( kubernetesCredentials = kubernetesCredentials, namespace = executionParameters.namespace ), reservationDeploymentFactory = ReservationDeploymentFactory( configurationName = configuration.name, projectName = projectName, buildId = buildId, buildType = buildType, registry = registry, logger = logger ), logger = logger, emulatorsLogsReporter = emulatorsLogsReporter ), adbDevicesManager = devicesManager, adb = adb, logger = logger ) } } } } }
0
Kotlin
0
0
45b414cad6ecf101635ba73c9b7b8ed23881b386
4,167
avito-android
MIT License
app/src/main/java/com/debanshu777/compose_github/ui/feature_trending/TrendingScreen.kt
Debanshu777
467,621,052
false
{"Kotlin": 390827}
package com.debanshu777.compose_github.ui.feature_trending import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.ExperimentalUnitApi import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.TextUnitType import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.debanshu777.compose_github.R import com.debanshu777.compose_github.network.dataSource.GitHubViewModel import com.debanshu777.compose_github.ui.base.components.DropDownMenu import com.debanshu777.compose_github.ui.base.components.tabHandler.TabHandler import com.debanshu777.compose_github.utils.Loader import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.rememberPagerState @OptIn(ExperimentalPagerApi::class, ExperimentalUnitApi::class) @Composable fun TrendingScreen( viewModel: GitHubViewModel, navController: NavController, onShowSnackbar: (String) -> Unit ) { val trendingRepositoryDataState by viewModel.trendingRepositoryDataState.collectAsState() val trendingDeveloperDataState by viewModel.trendingDeveloperDataState.collectAsState() val durationTypeFilterVisibility by viewModel.durationTypeFilterVisibility.observeAsState() val durationType by viewModel.durationType.observeAsState() val pagerState = rememberPagerState(0) val pageCount = 2 val tabList = listOf("Repositories", "Developers") val actionList = listOf({ s: String -> viewModel.getUserData(s) }, { s: String -> viewModel.getUserData(s) }) val dataList = listOf(trendingRepositoryDataState.data, trendingDeveloperDataState.data) Column(modifier = Modifier.padding(top = if (durationTypeFilterVisibility == true) 56.dp else 15.dp)) { DropDownMenu( durationType, durationTypeFilterVisibility ?: false ) { viewModel.updateDurationType(it) } if (trendingDeveloperDataState.isLoading && trendingRepositoryDataState.isLoading) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Loader(R.raw.github_loading_anim) } } else if ((!trendingDeveloperDataState.isLoading && !trendingRepositoryDataState.isLoading) && (trendingDeveloperDataState.error != null || trendingRepositoryDataState.error != null)) { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Loader(R.raw.error_page, Modifier.height(250.dp)) Text( modifier = Modifier.padding(vertical = 10.dp), text = "Some Issue From Our Side", fontWeight = FontWeight.W300, fontSize = TextUnit(value = 14F, type = TextUnitType.Sp), ) } } } else { TabHandler( pagerState, pageCount, tabList, actionList, listOf(), dataList, navController, onShowSnackbar ) } } }
1
Kotlin
2
57
422904eb5e71737e7f527932bfe84253740ed35c
3,789
Github-Compose
MIT License
BaseLibrary/src/main/java/com/ccp/base/widgets/ProgressLoading.kt
matrixccp
141,006,860
false
null
package com.ccp.base.widgets import android.app.Dialog import android.content.Context import android.graphics.drawable.AnimationDrawable import android.view.Gravity import android.widget.ImageView import com.ccp.base.R import org.jetbrains.anko.find /** * <p>desc:<p> * <p>author:CP<p> * <p>create time:2018/7/14<p> * <p>change time:2018/7/14<p> * <p>version:1<p> * */ class ProgressLoading private constructor(context: Context,theme:Int):Dialog(context,theme){ companion object { private lateinit var mDialog: ProgressLoading private var animDrawable:AnimationDrawable? = null fun create(context: Context):ProgressLoading{ mDialog = ProgressLoading(context, R.style.LightProgressDialog) mDialog.setContentView(R.layout.progress_dialog) mDialog.setCancelable(true) mDialog.setCanceledOnTouchOutside(false) mDialog.window.attributes.gravity = Gravity.CENTER val lp = mDialog.window.attributes lp.dimAmount = 0.2f mDialog.window.attributes = lp val loadingView = mDialog.find<ImageView>(R.id.iv_loading) animDrawable = loadingView.background as AnimationDrawable return mDialog } } fun showLoading(){ super.show() animDrawable?.start() } fun hideLoading(){ super.dismiss() animDrawable?.stop() } }
1
null
1
1
0305bfc743fb73a7972f7354069f8b2a26d20bce
1,430
YiMall
Apache License 2.0
idea/testData/inspections/unusedSymbol/function/membersOfLocalClass.kt
erokhins
44,854,854
true
{"Markdown": 33, "XML": 665, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 20967, "Java": 4534, "Protocol Buffer": 7, "Text": 4663, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 152, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1}
fun main(args: Array<String>) { class LocalClass { fun f() { } val p = 5 } LocalClass().f() LocalClass().p }
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
151
kotlin
Apache License 2.0
idea/testData/inspections/unusedSymbol/function/membersOfLocalClass.kt
erokhins
44,854,854
true
{"Markdown": 33, "XML": 665, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 20967, "Java": 4534, "Protocol Buffer": 7, "Text": 4663, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 152, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1}
fun main(args: Array<String>) { class LocalClass { fun f() { } val p = 5 } LocalClass().f() LocalClass().p }
0
Java
0
1
ff00bde607d605c4eba2d98fbc9e99af932accb6
151
kotlin
Apache License 2.0
data_structure/src/main/java/graph/dfs_traversal.kt
NileshJarad
625,893,880
false
null
package graph fun main() { val dfsTraversal = DfsTraversal() dfsTraversal.createGraph() dfsTraversal.printGraph() dfsTraversal.depthFirstSearch() } class DfsTraversal { companion object { const val GRAPH_VERTEX = 7 } private val graph = Array<ArrayList<Edge>>(GRAPH_VERTEX) { // Creating an empty list, to avoid having null checks within edges ArrayList<Edge>() } data class Edge( val src : Int, val dest: Int ) fun depthFirstSearch() { val visited = Array(graph.size) { false } printDFS(0, visited) } private fun printDFS(currentV: Int, visited: Array<Boolean>) { print("$currentV ") visited[currentV] = true val edges = graph[currentV] edges.forEach { if (!visited[it.dest]) { printDFS(it.dest, visited) } } } fun createGraph() { /*** * 1 ------- 3 * / | \ * 0 | 5 --- 6 * \ | / * 2 ------- 4 */ graph[0].add(Edge(0,1)) graph[0].add(Edge(0,2)) graph[1].add(Edge(1,3)) graph[2].add(Edge(2,4)) graph[3].add(Edge(3,4)) graph[3].add(Edge(3,5)) graph[4].add(Edge(4,3)) graph[4].add(Edge(4,5)) graph[5].add(Edge(5,6)) } fun printGraph() { for (i: Int in graph.indices) { if (graph[i].size > 0) { print("$i --> ") for (j: Int in 0 until graph[i].size) { val edge = graph[i][j] print("(${edge.src}, ${edge.dest})") } println() } else { println("$i --> empty") } } } }
1
Kotlin
1
0
e71d93b2f9aa9a5181efbd4a474088bff34aaa7f
1,842
android-knowledge-mesh
Apache License 2.0
src/main/kotlin/com/chronoscoper/ftpupload/Main.kt
vaginessa
115,529,668
false
null
/* * Copyright 2017 KoFuk * * 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.chronoscoper.ftpupload import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.apache.commons.net.ftp.FTPReply import java.io.BufferedInputStream import java.io.File import java.io.FileInputStream fun main(args: Array<String>) { if (args.size < 5) { println("host user password localFile remoteFile") return } val host = args[0] val username = args[1] val password = args[2] val local = args[3] val remote = args[4] val client = FTPClient() client.controlEncoding = "UTF-8" client.connect(host) if (!FTPReply.isPositiveCompletion(client.replyCode)) { throw RuntimeException("Failed to connect to host") } client.login(username, password) if (!FTPReply.isPositiveCompletion(client.replyCode)) { throw RuntimeException("Failed to login") } client.setFileType(FTP.BINARY_FILE_TYPE) BufferedInputStream(FileInputStream(File(local))).use { fileStream -> client.storeFile(remote, fileStream) } client.logout() client.disconnect() }
0
Kotlin
0
0
3e9c9877cbe5605a8fcb0bf3d0232bafb74461de
1,626
ftp-upload
Apache License 1.1
app/src/main/java/com/example/topper/presentation/components/DeleteDialogue.kt
IAMISHWOR
818,511,313
false
{"Kotlin": 158810}
package com.example.topper.presentation.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.AlertDialog import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import com.example.topper.domain.model.Subject @Composable fun DeleteDialogue( isOpen : Boolean, title:String, onDismissRequest:()->Unit, onConfirmRequest:()->Unit, bodyText:String ) { if (isOpen) { AlertDialog( onDismissRequest = onDismissRequest, title = { Text(text = title) }, text = { Text(text = bodyText) }, dismissButton = { TextButton(onClick = { onDismissRequest() }) { Text(text = "Cancel") } }, confirmButton = { TextButton(onClick = { onConfirmRequest() }){ Text(text = "Delete") } }, ) } }
0
Kotlin
0
1
80e2a7e430fc12341fd7aa727fd4ddeaeeddd0ce
2,213
Topper
Apache License 2.0
app/src/main/java/cz/ikem/dci/zscanner/screen_message/CreateMessagePagesFragment.kt
ikem-cz
183,602,578
false
null
package cz.ikem.dci.zscanner.screen_message import android.content.Context import android.content.res.ColorStateList import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProviders import com.google.android.material.snackbar.Snackbar import com.stepstone.stepper.Step import com.stepstone.stepper.VerificationError import cz.ikem.dci.zscanner.OnCreateMessageViewsInteractionListener import cz.ikem.dci.zscanner.R import kotlinx.android.synthetic.main.fragment_message_pages.view.* class CreateMessagePagesFragment : androidx.fragment.app.Fragment(), Step { private var mListener: OnCreateMessageViewsInteractionListener? = null private lateinit var mViewModel: CreateMessageViewModel private lateinit var mRecyclerView: androidx.recyclerview.widget.RecyclerView private var mSnackbar: Snackbar? = null //region Step callbacks override fun onSelected() { mViewModel.currentStep = ModeDispatcher(mViewModel.mode).stepNumberFor(this) /*if (Utils.tutorialNextStep(4, activity)) { Handler().postDelayed({ Utils.makeTooltip("Teď přidáme nějaké obrázky !", pages_recyclerview, Gravity.BOTTOM, activity, showArrow = false, modal = true) { Utils.makeTooltip("Obrázky lze buď načíst z galerie Vašeho fotoaparátu pomocí tohoto tlačítka ...", gallery_fab, Gravity.TOP, activity, showArrow = true, modal = true) { Utils.makeTooltip("... anebo přímo vyfotit", photo_fab, Gravity.START, activity, showArrow = true, modal = true) { Utils.makeTooltip("Nyní vyfoťte nějakou fotografii.", pages_recyclerview, Gravity.BOTTOM, activity, showArrow = false, modal = true) { Utils.tutorialAdvance(activity) } } } } }, 500) }*/ return } override fun verifyStep(): VerificationError? { if (!mViewModel.containsAtLeastOnePage()) { return VerificationError(getString(R.string.err_no_photo)) } return null } override fun onError(error: VerificationError) {} //endregion override fun onCreate(savedInstanceState: Bundle?) { mViewModel = ViewModelProviders.of(activity!!).get(CreateMessageViewModel::class.java) super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment val view = inflater.inflate(R.layout.fragment_message_pages, container, false) view.fab_next_send.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.invalid)); view.fab_next_send.setOnClickListener { mListener?.onProceedButtonPress() } // initialize recycler view mRecyclerView = (view.pages_recyclerview).apply { layoutManager = androidx.recyclerview.widget.GridLayoutManager(activity, 2) setEmptyView(view.pages_empty_view) } val pagesTouchCallback = PagesTouchCallback(mViewModel) val itemTouchHelper = PagesItemTouchHelper(pagesTouchCallback) itemTouchHelper.attachToRecyclerView(mRecyclerView) val adapter = PagesAdapter(mViewModel.pageActions.value!!.clone(), context!!) mRecyclerView.adapter = adapter mViewModel.pageActions.observe(this, Observer<PageActionsQueue> { adapter.syncActionsQueue(mViewModel) if (mViewModel.containsAtLeastOnePage()) { view.fab_next_send.backgroundTintList = ColorStateList.valueOf(getResources().getColor(R.color.colorPrimary)); } else { view.fab_next_send.backgroundTintList = ColorStateList.valueOf(getResources().getColor(R.color.invalid)); } }) mViewModel.undoAction.observe(this, Observer<PageActionsQueue.PageAction> { if (mViewModel.undoAction.value != null) { mSnackbar = Snackbar.make(view.popup_layout_buttons, "Smazáno.", Snackbar.LENGTH_INDEFINITE) .setAction("Zpět") { mViewModel.addPage(mViewModel.undoAction.value!!.page.path, mViewModel.undoAction.value!!.target) } mSnackbar!!.show() } else { if (mSnackbar != null) { mSnackbar!!.dismiss() mSnackbar = null } } }) // add make photo button listener view.photo_layout.setOnClickListener { mListener?.onCapturePagePhotoButtonPress() } view.photo_fab.setOnClickListener { mListener?.onCapturePagePhotoButtonPress() } view.gallery_layout.setOnClickListener { mListener?.onAttachButtonPress() } view.gallery_fab.setOnClickListener { mListener?.onAttachButtonPress() } return view } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnCreateMessageViewsInteractionListener) { mListener = context } else { throw RuntimeException("$context must implement OnCreateMessageViewsInteractionListener") } } override fun onDetach() { super.onDetach() mListener = null } }
1
Kotlin
0
2
c1a5d7a449f3fed3da429bda154428ecdb4a8d42
5,630
zscanner-android
MIT License
src/main/kotlin/daf/demotdd/delivery/CurrencyController.kt
DanielFCubides
211,957,769
false
null
package daf.demotdd.delivery import daf.demotdd.usecase.CurrencyUseCaseImpl import org.springframework.beans.factory.annotation.Autowired import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class CurrencyController() { @Autowired lateinit var currencyUseCase: CurrencyUseCaseImpl @GetMapping("/currency") fun getAllCurrencies(): List<String> = currencyUseCase.getAllCurrencies() }
0
Kotlin
1
1
cef0895441a0ced40d9ebfa9451abffbe53fe3f2
500
currencies-converter
Apache License 2.0
arrow-libs/core/arrow-core-test/src/commonMain/kotlin/arrow/core/test/laws/Law.kt
lukaszkalnik
427,116,886
true
{"Kotlin": 1928099, "SCSS": 99659, "JavaScript": 83153, "HTML": 25306, "Java": 7691, "Ruby": 917, "Shell": 98}
package arrow.core.test.laws import arrow.core.test.concurrency.deprecateArrowTestModules import io.kotest.assertions.fail import io.kotest.core.test.TestContext @Deprecated(deprecateArrowTestModules) public data class Law(val name: String, val test: suspend TestContext.() -> Unit) @Deprecated(deprecateArrowTestModules) public fun <A> A.equalUnderTheLaw(b: A, f: (A, A) -> Boolean = { a, b -> a == b }): Boolean = if (f(this, b)) true else fail("Found $this but expected: $b")
0
Kotlin
0
1
73fa3847df1f04e634a02bba527917389b59d7df
484
arrow
Apache License 2.0
kotlin/sealed_stack.kts
rtoal
27,696,937
false
{"JavaScript": 41570, "Rust": 34194, "Haskell": 31660, "Shell": 27624, "Java": 23019, "C": 21474, "Swift": 19501, "Go": 18302, "Kotlin": 18186, "Elm": 16016, "Julia": 15051, "Python": 14638, "Ruby": 13534, "Clojure": 13509, "Lua": 12367, "TypeScript": 11717, "C++": 10702, "Erlang": 9439, "Dart": 6732, "Perl": 6539, "CoffeeScript": 6467, "C#": 2774, "Zig": 2151, "Standard ML": 1976, "Gleam": 1675, "F#": 1313, "Odin": 1282, "Scala": 1225, "OCaml": 1219, "Assembly": 1100, "HTML": 1059, "Ada": 1026, "V": 835, "Fortran": 819, "Crystal": 794, "D": 777, "Vala": 764, "COBOL": 749, "Chapel": 746, "Common Lisp": 713, "Smalltalk": 681, "Nim": 502, "Forth": 445, "LOLCODE": 409, "Io": 398, "Modula-2": 392, "Prolog": 388, "Awk": 358, "R": 277, "Scheme": 222, "Elixir": 204, "Raku": 198, "Brainfuck": 145, "Idris": 56, "Lean": 48, "APL": 32, "Befunge": 29, "Mojo": 22}
sealed class IntStack { abstract fun push(value: Int): IntStack abstract fun pop(): IntStack abstract fun peek(): Int? abstract fun size(): Int object Empty : IntStack() { override fun push(value: Int): IntStack = NonEmpty(value, this) override fun pop(): IntStack = this override fun peek(): Int? = null override fun size(): Int = 0 } data class NonEmpty(val top: Int, val rest: IntStack) : IntStack() { override fun push(value: Int): IntStack = NonEmpty(value, this) override fun pop(): IntStack = rest override fun peek(): Int? = top override fun size(): Int = 1 + rest.size() } } val stack: IntStack = IntStack.Empty val stack1 = stack.push(10) val stack2 = stack1.push(20) val stack3 = stack2.push(30) println("Peek: ${stack3.peek()}") // Output: Peek: 30 println("Size: ${stack3.size()}") // Output: Size: 3 val stack4 = stack3.pop() println("Peek after pop: ${stack4.peek()}") // Output: Peek after pop: 20 println("Size after pop: ${stack4.size()}") // Output: Size after pop: 2
5
JavaScript
35
90
0f2a387d77294c14059f4bb9417812a0f46f0aa4
1,088
ple
MIT License
app/src/main/java/com/finance/hodl/view/navigation/HodlNavHost.kt
smohantty
748,648,513
false
{"Kotlin": 79649}
package com.finance.hodl.view.navigation import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.runtime.Composable import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navigation import com.finance.hodl.view.HodlAppState import com.finance.hodl.view.screens.HodlBotsNewScreen import com.finance.hodl.view.screens.HodlHomeBithumbScreen import com.finance.hodl.view.screens.HodlSettingsMainScreen @Composable fun HodlNavHost( appState: HodlAppState, startDestination: String = HodlNavGraph.Home.route, ) { val navController = appState.navController NavHost( navController = navController, startDestination = startDestination, enterTransition = { EnterTransition.None }, exitTransition = { ExitTransition.None } ) { navigation( startDestination = HodlHome.Bithumb.route, route = HodlNavGraph.Home.route ) { composable(HodlHome.Bithumb.route) { HodlHomeBithumbScreen(navController = navController) } } navigation( startDestination = HodlBots.New.route, route = HodlNavGraph.Bots.route ) { composable(HodlBots.New.route) { HodlBotsNewScreen(navController = navController) } } navigation( startDestination = HodlSettings.Main.route, route = HodlNavGraph.Settings.route ) { composable(HodlSettings.Main.route) { HodlSettingsMainScreen(navController = navController) } } } }
0
Kotlin
0
0
c54021e9377044f05ac92cc686ed19c6d4df149f
1,767
Hodl
MIT License
Client/app/src/main/java/com/t3ddyss/clother/ui/offer_category/OfferCategoryFragment.kt
t3ddyss
337,083,750
false
null
package com.t3ddyss.clother.ui.offer_category import android.os.Bundle import android.view.View import androidx.core.content.ContextCompat import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.navigation.fragment.navArgs import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import com.t3ddyss.clother.R import com.t3ddyss.clother.databinding.FragmentOfferCategoryBinding import com.t3ddyss.clother.ui.adapters.CategoriesAdapter import com.t3ddyss.core.presentation.BaseFragment import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class OfferCategoryFragment : BaseFragment<FragmentOfferCategoryBinding> (FragmentOfferCategoryBinding::inflate) { private val viewModel by viewModels<OfferCategoryViewModel>() private val args by navArgs<OfferCategoryFragmentArgs>() private lateinit var adapter: CategoriesAdapter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { adapter = CategoriesAdapter { if (!it.isLastLevel) { val action = OfferCategoryFragmentDirections .openSubcategoriesAction(it.id) findNavController().navigate(action) } else { val action = OfferCategoryFragmentDirections .offerCategoryToOfferEditorGraph(it) findNavController().navigate(action) } } val layoutManager = LinearLayoutManager(context) binding.listCategories.layoutManager = layoutManager binding.listCategories.adapter = adapter val verticalDecorator = DividerItemDecoration(activity, DividerItemDecoration.VERTICAL) ContextCompat.getDrawable(requireContext(), R.drawable.divider_small)?.apply { verticalDecorator.setDrawable(this) binding.listCategories.addItemDecoration(verticalDecorator) } subscribeUi() } private fun subscribeUi() { viewModel.categories.observe(viewLifecycleOwner) { adapter.submitList(it) } } }
0
Kotlin
0
22
ca7bfd2a830cb36cf7ba62782498636e58f9ea17
2,149
Clother
MIT License
app/src/main/java/com/example/todoscompose/MainActivity.kt
behrends
705,599,200
false
{"Kotlin": 7752}
package com.example.todoscompose import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.Button import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.todoscompose.ui.theme.TodosComposeTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { TodosComposeTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { TodosApp() } } } } } @Preview(showBackground = true) @Composable fun TodosApp() { Todos() } @Composable fun Todos() { var todos by remember { mutableStateOf(listOf(Todo("Sport"), Todo("Einkaufen"), Todo("Kotlin lernen"))) } Column { TodoInput(onSave = {todos = todos + Todo(it)}) LazyColumn(modifier = Modifier.padding(16.dp).fillMaxSize()) { items(todos) { TodoItem(it) } } } } @Composable fun TodoInput(onSave: (String) -> Unit) { // by ist ein Delegate auf die Eigenschaft value // var todo = remember { mutableStateOf("") } var todo by remember { mutableStateOf("") } Row { TextField( value = todo, // ohne by: value = todo.value onValueChange = { todo = it }, label = { Text(stringResource(R.string.enter_todo)) }, ) Spacer(modifier = Modifier.width(16.dp)) Button(onClick = {onSave(todo)}) { Text(stringResource(R.string.save)) } } } @Composable fun TodoItem(todo: Todo) { var done by remember { mutableStateOf(false) } val style = TextStyle(textDecoration = if (done) TextDecoration.LineThrough else TextDecoration.None) Text(text = todo.text, modifier = Modifier.clickable(onClick = {done = !done}).padding(8.dp).fillMaxSize(), style = style) }
0
Kotlin
0
0
d2c0c736452c932ad3dc103f5ee24045ff4d4e25
3,183
TodosCompose
MIT License
client_support/common/src/commonMain/kotlin/org/thechance/common/presentation/chat/ChatUIEffect.kt
TheChance101
671,967,732
false
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
package org.thechance.common.presentation.chat interface ChatUIEffect { object NavigateToLogin : ChatUIEffect }
4
Kotlin
55
572
1d2e72ba7def605529213ac771cd85cbab832241
117
beep-beep
Apache License 2.0
idea/testData/intentions/simplifyBooleanWithConstants/nullableComplex2.kt
JakeWharton
99,388,807
true
null
data class Test(val notnull: Boolean, val nullable: Boolean?) fun test(a: Test, b: Test?) { <caret>a.notnull == true || a.nullable == true || b?.notnull == true || b?.nullable == true }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
190
kotlin
Apache License 2.0
feature/home/src/main/java/com/tapptitude/template/home/presentation/HomeScreen.kt
tapptitude
462,275,098
false
null
package com.tapptitude.template.home.presentation import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Button import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil.compose.AsyncImage import com.tapptitude.template.config.BuildConfig import com.tapptitude.template.core.model.Image import com.tapptitude.template.feature.home.R import com.tapptitude.template.session.model.LoggedIn import com.tapptitude.template.session.model.LoggedOut import com.tapptitude.template.session.model.LoginState import org.koin.androidx.compose.koinViewModel @Composable internal fun HomeRoute( modifier: Modifier = Modifier, viewModel: HomeViewModel = koinViewModel(), ) { val state by viewModel.state.collectAsStateWithLifecycle() HomeScreen( isLoading = state.isLoading, image = state.image, loginState = state.loginState, onButtonClick = viewModel::toggleLoginMode, modifier = modifier, ) } @Composable internal fun HomeScreen( isLoading: Boolean, image: Image?, loginState: LoginState, onButtonClick: () -> Unit, modifier: Modifier = Modifier, ) { if (!isLoading) { Column( modifier = modifier .fillMaxWidth() .padding(24.dp), ) { Text( text = stringResource(R.string.title_including_flavor_format, BuildConfig.FLAVOR), modifier = Modifier.align(Alignment.CenterHorizontally), ) Spacer(modifier = Modifier.size(16.dp)) AsyncImage( model = image?.imageUrl, contentScale = ContentScale.Crop, contentDescription = null, ) Spacer(modifier = Modifier.size(16.dp)) Button( onClick = onButtonClick, modifier = Modifier.align(Alignment.CenterHorizontally), ) { val btnStringId = when (loginState) { is LoggedIn -> R.string.action_logout is LoggedOut -> R.string.action_login } Text(text = stringResource(btnStringId)) } Spacer(modifier = Modifier.size(16.dp)) val loginStatus = when (loginState) { is LoggedIn -> stringResource(R.string.status_logged_in_x, loginState.userId) is LoggedOut -> stringResource(R.string.status_logged_out) } Text( text = loginStatus, modifier = Modifier.align(Alignment.CenterHorizontally), ) } } AnimatedVisibility( visible = isLoading, enter = slideInVertically( initialOffsetY = { fullHeight -> -fullHeight }, ) + fadeIn(), exit = slideOutVertically( targetOffsetY = { fullHeight -> -fullHeight }, ) + fadeOut(), ) { Box( modifier = Modifier.fillMaxSize(), ) { CircularProgressIndicator( modifier = Modifier.align(Alignment.Center), ) } } }
4
null
0
5
b5d29a8cf4d07775c6039072a852e7f38f53eea2
4,070
AndroidKotlinMVVMTemplate
MIT License
plugin/src/main/kotlin/tanvd/grazi/ide/notification/GraziNotificationComponent.kt
TanVD
177,469,390
false
null
package tanvd.grazi.ide.notification import com.intellij.openapi.project.DumbAware import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity import tanvd.grazi.GraziConfig import tanvd.grazi.GraziPlugin open class GraziNotificationComponent : StartupActivity, DumbAware { override fun runActivity(project: Project) { GraziConfig.update { when { it.lastSeenVersion == null -> Notification.showInstallationMessage(project) GraziPlugin.version != it.lastSeenVersion -> Notification.showUpdateMessage(project) } if (it.hasMissedLanguages()) Notification.showLanguagesMessage(project) it.update(lastSeenVersion = GraziPlugin.version) } } }
2
Kotlin
1
37
d12150715d19aaafcb9b7a474ea911bf1713701f
781
Grazi
Apache License 2.0
src/main/kotlin/view/common/AddVertexDialog.kt
spbu-coding-2023
791,480,179
false
{"Kotlin": 147316}
package view.common import androidx.compose.foundation.border import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Checkbox import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.TextFieldDefaults import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.dp import androidx.compose.ui.window.DialogWindow import androidx.compose.ui.window.rememberDialogState import localisation.getLocalisation import localisation.localisation import viewmodel.graph.AbstractGraphViewModel @Composable fun AddVertexDialog( _visible: Boolean, onClose: () -> Unit, graphVM: AbstractGraphViewModel<String>, ) { var visible by mutableStateOf(_visible) var centerCoordinates by remember { mutableStateOf(true) } DialogWindow( visible = visible, title = "New Vertices", onCloseRequest = onClose, state = rememberDialogState(height = 340.dp, width = 560.dp) ) { var verticesNumber by remember { mutableStateOf("1") } val language = getLocalisation() Column(modifier = Modifier.padding(30.dp, 24.dp)) { Row(modifier = Modifier.fillMaxWidth()) { Text( text = localisation("number"), style = defaultStyle, modifier = Modifier.align(Alignment.CenterVertically).width(180.dp), ) TextField( modifier = Modifier .fillMaxWidth() .border(4.dp, color = Color.Black, shape = RoundedCornerShape(25.dp)), colors = TextFieldDefaults.textFieldColors( focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, ), shape = RoundedCornerShape(25.dp), textStyle = defaultStyle, value = verticesNumber, onValueChange = { newValue -> if (newValue.length < 6) { verticesNumber = newValue.filter { it.isDigit() } } }, ) } Spacer(modifier = Modifier.height(30.dp)) Row { Checkbox( modifier = Modifier.align(Alignment.CenterVertically), checked = centerCoordinates, onCheckedChange = { centerCoordinates = it } ) Text( text = localisation("center_coordinates"), style = defaultStyle, modifier = Modifier.align(Alignment.CenterVertically) ) } Spacer(modifier = Modifier.height(30.dp)) Row { val onClick = { if (verticesNumber == "") verticesNumber = "1" repeat(verticesNumber.toInt()) { graphVM.addVertex(graphVM.size.toString(), centerCoordinates) } graphVM.updateView() visible = false } DefaultButton(onClick, "add", defaultStyle) Spacer(modifier = Modifier.width(30.dp)) DefaultButton(onClose, "back", defaultStyle, Color.Red) } } } }
2
Kotlin
0
4
b25b5a432b6af0c71f401d27770938d49f88ecf9
3,624
graphs-graphs-8
The Unlicense