path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/io/lavamc/bedrokt/api/PluginManager.kt
ConsoleLogLuke
268,694,871
false
null
@file:Suppress("MemberVisibilityCanBePrivate") package io.lavamc.bedrokt.api import io.lavamc.bedrokt.proxyLogger import java.io.File import java.net.URLClassLoader import java.util.* import java.util.jar.JarFile import kotlin.system.measureTimeMillis class PluginManager { companion object { val pluginsDir = File("plugins") val plugins = mutableListOf<Plugin>() private fun runArbitraryPluginCode(message: String, code: () -> Unit): Boolean { return try { code() true } catch (e: Throwable) { e.printStackTrace() proxyLogger.error(message) proxyLogger.error("The error above was likely caused by a plugin and not Bedrokt.") false } } private fun loadJarPlugin(jarFile: File): Plugin { val jar = JarFile(jarFile) val inputStream = jar.getInputStream(jar.getJarEntry("bedrokt.txt")) val mainClass = Scanner(inputStream).useDelimiter("\\A").next().trim() val classLoader = URLClassLoader(arrayOf(jarFile.toURI().toURL()), {}.javaClass.classLoader) val pluginClass = Class.forName(mainClass, true, classLoader) val plugin = pluginClass.asSubclass(Plugin::class.java) val constructor = plugin.getConstructor() val instance = constructor.newInstance() val configEntry = jar.getJarEntry("config.yml") val configFile = File(instance.dataDir, "config.yml") if (!configFile.exists() && configEntry != null) { val defaultConfig = Scanner(jar.getInputStream(configEntry)) .useDelimiter("\\A") .next() .trim() configFile.writeText(defaultConfig) } return instance } fun loadPlugin(file: File): Boolean { val plugin = when (file.extension) { "jar" -> loadJarPlugin(file) else -> loadJarPlugin(file) } val success = runArbitraryPluginCode( "${plugin.name}: An error occurred in onLoad. This plugin will not be loaded." ) { plugin.onLoad() } if (success) { plugins.add(plugin) proxyLogger.info("Loaded ${plugin.name} v${plugin.version}!") } return success } fun unloadPlugin(plugin: Plugin) { runArbitraryPluginCode("${plugin.name}: An error occurred in onUnload.") { plugin.onUnload() } plugins.remove(plugin) proxyLogger.info("Unloaded ${plugin.name} v${plugin.version}!") } fun reloadPlugins() { if (!pluginsDir.exists()) pluginsDir.mkdirs() proxyLogger.info("Reloading plugins...") var unloadCount = 0 var loadCount = 0 val reloadTime = measureTimeMillis { plugins.forEach { unloadPlugin(it) unloadCount++ } for (file in pluginsDir.listFiles()!!) { if (file.isDirectory || file.extension !in listOf("jar")) continue if (loadPlugin(file)) loadCount++ } } / 1000f val unloadWord = if (unloadCount == 1) "plugin" else "plugins" val loadWord = if (loadCount == 1) "plugin" else "plugins" proxyLogger.info( "Unloaded $unloadCount $unloadWord and loaded $loadCount $loadWord in ${reloadTime}s!" ) } fun callEvent(eventType: EventType, code: (Plugin) -> Unit) { plugins.forEach { runArbitraryPluginCode("${it.name}: An error occurred in ${eventType.methodName}.") { code(it) } } } } }
0
Kotlin
0
0
c6bee18894de85de7e42ea46a078aea9cb621dce
3,951
Bedrokt
MIT License
app/src/main/java/pl/charmas/android/tagview/TagView.kt
wakim
52,843,851
false
{"Git Config": 1, "Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 1, "XML": 63, "JSON": 1, "Kotlin": 84}
/** * Copyright 2013 <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 pl.charmas.android.tagview import android.content.Context import android.graphics.* import android.graphics.drawable.Drawable import android.support.annotation.ColorInt import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.ImageSpan import android.util.AttributeSet import android.widget.TextView import br.com.wakim.eslpodclient.R import br.com.wakim.eslpodclient.util.extensions.dp class TagView : TextView { companion object { private const val DEFAULT_PADDING = 8 private const val DEFAULT_CORNER_RADIUS = 6F private val DEFAULT_COLOR = Color.parseColor("#DDDDDD") private const val DEFAULT_UPPERCASE = true private const val DEFAULT_SEPARATOR = " " } private var tagPadding: Int? = DEFAULT_PADDING private var tagCornerRadius: Float? = DEFAULT_CORNER_RADIUS private var tagColor: Int? = DEFAULT_COLOR private var tagSeparator: String? = DEFAULT_SEPARATOR private var isUppercaseTags = DEFAULT_UPPERCASE private var prefix = "" constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context, attrs, defStyleAttr) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context, attrs, defStyleAttr) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context, attrs, R.attr.tagViewStyle) } constructor(context: Context?) : super(context) private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) { if (attrs != null) { context.theme.obtainStyledAttributes(attrs, R.styleable.TagView, defStyleAttr, R.style.Widget_TagView).apply { tagPadding = getDimensionPixelSize(R.styleable.TagView_tagPadding, context.dp(DEFAULT_PADDING)) tagCornerRadius = getDimensionPixelSize(R.styleable.TagView_tagCornerRadius, context.dp(DEFAULT_CORNER_RADIUS).toInt()).toFloat() tagColor = getColor(R.styleable.TagView_tagColor, DEFAULT_COLOR) tagSeparator = getString(R.styleable.TagView_tagSeparator) isUppercaseTags = getBoolean(R.styleable.TagView_tagUppercase, DEFAULT_UPPERCASE) if (hasValue(R.styleable.TagView_tagPrefix)) { prefix = getString(R.styleable.TagView_tagPrefix) } }.recycle() } else { tagPadding = context.dp(DEFAULT_PADDING) tagCornerRadius = context.dp(DEFAULT_CORNER_RADIUS) } } override fun setText(text: CharSequence?, type: TextView.BufferType) { if (text == null) { super.setText(null, type) } else { if (!isInEditMode) setTags(text.toString().split(tagSeparator ?: DEFAULT_SEPARATOR)) } } fun setTags(tags: List<String>) { val separator = tagSeparator ?: DEFAULT_SEPARATOR setTags(tags, tagColor ?: DEFAULT_COLOR, separator) } fun setTags(tags: List<String>, @ColorInt color: Int, separator: String, type: TextView.BufferType = TextView.BufferType.NORMAL) { if (tags.size == 0) { super.setText(null, type) return } val sb = SpannableStringBuilder() var i = 0 val size = tags.size while (i < size) { if (tags[i].isBlank()) { ++i continue } val tag = prefix + tags[i].trim() val tagContent = if (isUppercaseTags) tag.toUpperCase() else tag sb.append(tagContent).setSpan( createSpan(tagContent, color), sb.length - tagContent.length, sb.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE) if (i + 1 < size) { sb.append(separator) } ++i } super.setText(sb, type) } private fun createSpan(text: String, color: Int): TagSpan { return TagSpan( text, tagPadding ?: DEFAULT_PADDING, textSize, typeface === Typeface.DEFAULT_BOLD, currentTextColor, color, tagCornerRadius?.toFloat() ?: DEFAULT_CORNER_RADIUS) } class TagSpan(val text: String, tagPadding: Int, textSize: Float, bold: Boolean, textColor: Int, tagColor: Int, roundCornersFactor: Float) : ImageSpan(TagDrawable(text, tagPadding, textSize, bold, textColor, tagColor, roundCornersFactor)) class TagDrawable (private val text: String, tagPadding: Int, textSize: Float, bold: Boolean, textColor: Int, tagColor: Int, private val roundCornersFactor: Float) : Drawable() { private val textContentPaint: Paint private val backgroundPaint: Paint private val fBounds: RectF private val backgroundPadding: Rect init { this.backgroundPadding = Rect(tagPadding, tagPadding, tagPadding, tagPadding) this.textContentPaint = Paint() textContentPaint.color = textColor textContentPaint.textSize = textSize textContentPaint.isAntiAlias = true textContentPaint.isFakeBoldText = bold textContentPaint.style = Paint.Style.FILL textContentPaint.textAlign = Paint.Align.LEFT this.backgroundPaint = Paint() backgroundPaint.color = tagColor backgroundPaint.style = Paint.Style.FILL backgroundPaint.isAntiAlias = true setBounds(0, 0, textContentPaint.measureText(text).toInt() + backgroundPadding.left + backgroundPadding.right, (textContentPaint.textSize + backgroundPadding.top.toFloat() + backgroundPadding.bottom.toFloat()).toInt()) fBounds = RectF(bounds) fBounds.top += (tagPadding / 2).toFloat() } override fun draw(canvas: Canvas) { canvas.drawRoundRect(fBounds, roundCornersFactor, roundCornersFactor, backgroundPaint) canvas.drawText(text, (backgroundPadding.left + MAGIC_PADDING_LEFT).toFloat(), textContentPaint.textSize + backgroundPadding.top, textContentPaint) } override fun setAlpha(alpha: Int) { textContentPaint.alpha = alpha backgroundPaint.alpha = alpha } override fun setColorFilter(cf: ColorFilter?) { textContentPaint.colorFilter = cf } override fun getOpacity(): Int { return PixelFormat.TRANSLUCENT } companion object { private const val MAGIC_PADDING_LEFT = 0 } } }
0
Kotlin
1
6
a92dad2832f087f97fcbf9b2b7973a31efde551c
7,424
esl-pod-client
Apache License 2.0
app/src/main/java/arche/phodal/com/arche/fragment/ArcheWebViewFragment.kt
phodal
116,018,537
false
{"Git Config": 1, "Gradle": 6, "Java Properties": 3, "Shell": 2, "Text": 1, "Ignore List": 4, "Batchfile": 2, "Markdown": 3, "YAML": 2, "JSON with Comments": 3, "JSON": 9, "EditorConfig": 1, "JavaScript": 8, "HTML": 4, "SCSS": 4, "Proguard": 2, "Kotlin": 9, "XML": 23, "INI": 2, "Starlark": 2, "Java": 2, "OpenStep Property List": 4, "Objective-C": 4}
package arche.phodal.com.arche.fragment import android.annotation.SuppressLint import android.graphics.Bitmap import android.os.Bundle import android.support.annotation.Nullable import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebView import android.webkit.WebViewClient import arche.phodal.com.arche.R import com.wang.avi.AVLoadingIndicatorView class ArcheWebViewFragment : Fragment() { private var mWebView: WebView? = null private var avi: AVLoadingIndicatorView? = null @SuppressLint("SetJavaScriptEnabled") @Nullable override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater?.inflate(R.layout.fragment_webview, container, false) avi = view?.findViewById(R.id.avi) mWebView = view?.findViewById(R.id.webview) mWebView!!.loadUrl("file:///android_asset/www/index.html") val webSettings = mWebView!!.settings webSettings.javaScriptEnabled = true mWebView!!.webViewClient = WebViewClient() setLoadingProgress() return view } private fun setLoadingProgress() { mWebView!!.webViewClient = object : WebViewClient() { override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) { avi!!.show() super.onPageStarted(view, url, favicon) } override fun onPageFinished(view: WebView?, url: String?) { avi!!.hide() super.onPageFinished(view, url) } } } }
0
Kotlin
6
15
1e7b5c1b3cdd837c051cd0e28f60f72746a388b8
1,677
arche
MIT License
wordpress-comments/src/main/java/org/wordpress/aztec/plugins/wpcomments/toolbar/MoreToolbarButton.kt
johnMinelli
206,531,286
false
{"Gradle": 7, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Text": 1, "Markdown": 1, "Proguard": 5, "Ignore List": 5, "Kotlin": 92, "XML": 133, "JSON": 2, "Java": 3}
package org.wordpress.aztec.plugins.wpcomments.toolbar import androidx.core.content.ContextCompat import android.text.SpannableStringBuilder import android.text.Spanned import android.view.KeyEvent import android.view.LayoutInflater import android.view.ViewGroup import android.widget.ToggleButton import org.wordpress.android.util.DeviceUtils import org.wordpress.aztec.AztecText import org.wordpress.aztec.Constants import org.wordpress.aztec.plugins.IToolbarButton import org.wordpress.aztec.plugins.wpcomments.R import org.wordpress.aztec.plugins.wpcomments.spans.WordPressCommentSpan import org.wordpress.aztec.spans.IAztecNestable import org.wordpress.aztec.toolbar.AztecToolbar import org.wordpress.aztec.toolbar.IToolbarAction class MoreToolbarButton(val visualEditor: AztecText) : IToolbarButton { override val action: IToolbarAction = CommentsToolbarAction.MORE override val context = visualEditor.context!! override fun toggle() { visualEditor.removeInlineStylesFromRange(visualEditor.selectionStart, visualEditor.selectionEnd) visualEditor.removeBlockStylesFromRange(visualEditor.selectionStart, visualEditor.selectionEnd, true) val nestingLevel = IAztecNestable.getNestingLevelAt(visualEditor.editableText, visualEditor.selectionStart) val span = WordPressCommentSpan( WordPressCommentSpan.Comment.MORE.html, visualEditor.context, ContextCompat.getDrawable(visualEditor.context, R.drawable.img_more)!!, nestingLevel, visualEditor ) val ssb = SpannableStringBuilder(Constants.MAGIC_STRING) ssb.setSpan(span, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) val start = visualEditor.selectionStart visualEditor.editableText.replace(start, visualEditor.selectionEnd, ssb) val newSelectionPosition = visualEditor.editableText.indexOf(Constants.MAGIC_CHAR, start) + 1 visualEditor.setSelection(newSelectionPosition) } override fun matchesKeyShortcut(keyCode: Int, event: KeyEvent): Boolean { if (DeviceUtils.getInstance().isChromebook(context)) { return false // This opens the terminal in Chromebooks } return keyCode == KeyEvent.KEYCODE_T && event.isAltPressed && event.isCtrlPressed // Read More = Alt + Ctrl + T } override fun inflateButton(parent: ViewGroup) { LayoutInflater.from(context).inflate(R.layout.more_button, parent) } override fun toolbarStateAboutToChange(toolbar: AztecToolbar, enable: Boolean) { toolbar.findViewById<ToggleButton>(R.id.format_bar_button_more).isEnabled = enable } }
1
null
1
1
83efaaca4f489a94bacbb45a425b61421c6be78e
2,674
EduTube
Apache License 2.0
app/src/main/java/com/spaceapp/presentation/explore_detail/ExploreDetailScreen.kt
AhmetOcak
552,274,999
false
{"Kotlin": 385521}
package com.spaceapp.presentation.explore_detail import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import com.spaceapp.core.designsystem.components.DefaultTextButton import com.spaceapp.presentation.utils.* @Composable fun ExploreDetailScreen( modifier: Modifier = Modifier, viewModel: ExploreDetailViewModel = hiltViewModel() ) { val uiState by viewModel.uiState.collectAsState() ExploreDetailScreenContent( modifier = modifier, viewModel = viewModel, categoryState = uiState.categoryState, objectName = viewModel.name, objectInfo1 = viewModel.info1, objectInfo2 = viewModel.info2, objectDescription = viewModel.description ) } @Composable private fun ExploreDetailScreenContent( modifier: Modifier, viewModel: ExploreDetailViewModel, categoryState: CategoryState, objectName: String?, objectInfo1: String?, objectInfo2: String?, objectDescription: String? ) { Column( modifier = modifier .fillMaxSize() .statusBarsPadding() .navigationBarsPadding() .padding(start = 16.dp, end = 16.dp, top = 16.dp, bottom = 32.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceBetween ) { CategoriesSection(modifier = modifier.fillMaxWidth(), viewModel = viewModel) when (categoryState) { is CategoryState.Overview -> { OverViewSection( objectName = objectName, objectInfo1 = objectInfo1, objectInfo2 = objectInfo2 ) } is CategoryState.Information -> { InformationSection(objectName = objectName, objectDescription = objectDescription) } } } } @Composable private fun CategoriesSection(modifier: Modifier, viewModel: ExploreDetailViewModel) { var selected by rememberSaveable { mutableIntStateOf(0) } LazyRow( modifier = modifier, horizontalArrangement = Arrangement.SpaceEvenly ) { itemsIndexed(categories) { index, item -> DefaultTextButton( category = item, index = index, onClick = { selected = index viewModel.categoryOnClick(categoryName = item) }, selected = selected ) } } } @Composable private fun InformationSection(objectName: String?, objectDescription: String?) { Image( modifier = Modifier .fillMaxWidth() .height(320.dp) .clip(RoundedCornerShape(15)), painter = painterResource(id = SpaceObjectImageType.setSpaceObjectImageType(objectName!!)), contentDescription = null, contentScale = ContentScale.Fit ) Text( modifier = Modifier.padding(vertical = 16.dp), text = objectName, style = MaterialTheme.typography.headlineLarge ) Text( modifier = Modifier.verticalScroll(rememberScrollState()), text = objectDescription ?: "", style = MaterialTheme.typography.bodyMedium, textAlign = TextAlign.Center ) } @Composable fun OverViewSection( objectName: String?, objectInfo1: String?, objectInfo2: String? ) { objectName?.let { SpaceObjectImageType.setSpaceObjectImageType(it) }?.let { OverView( title1 = "radius", info1 = if (objectInfo1 == NoData.noData) NoData.noData else "r = ${objectInfo1}km", title2 = if (isMeteor(objectName)) "velocity" else "distance from sun", info2 = if (isMeteor(objectName)) "${objectInfo2}km/s" else "${objectInfo2}km", objectName = objectName, objectImage = it ) } } @Composable private fun OverView( title1: String, info1: String, title2: String, info2: String, objectName: String, objectImage: Int, contentScale: ContentScale = ContentScale.Fit ) { Image( modifier = Modifier .fillMaxWidth() .height(320.dp) .clip(RoundedCornerShape(15)), painter = painterResource(id = objectImage), contentDescription = null, contentScale = contentScale ) Text( modifier = Modifier.padding(bottom = 32.dp), text = objectName, style = MaterialTheme.typography.headlineLarge.copy(fontSize = 56.sp), textAlign = TextAlign.Center ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly, verticalAlignment = Alignment.CenterVertically ) { Column( horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = title1, style = MaterialTheme.typography.bodySmall ) Text( modifier = Modifier.padding(top = 8.dp), text = info1, style = MaterialTheme.typography.bodyMedium ) } Column( horizontalAlignment = Alignment.CenterHorizontally, ) { Text(text = title2, style = MaterialTheme.typography.bodySmall) Text( modifier = Modifier.padding(top = 8.dp), text = info2, style = MaterialTheme.typography.bodyMedium ) } } } private fun isMeteor(name: String): Boolean { return when (name) { SpaceObjects.lenoids -> { true } SpaceObjects.lyrids -> { true } SpaceObjects.orinoids -> { true } SpaceObjects.perseids -> { true } else -> { false } } } private val categories = listOf( ExploreDetailCategories.overview, ExploreDetailCategories.information )
0
Kotlin
1
2
faac912d41d8decca902f79d725aa560d1e6a7bf
6,737
Explore-Universe
MIT License
core/src/commonMain/kotlin/com/lehaine/rune/engine/node/renderable/entity/Entity.kt
LeHaine
468,806,982
false
{"Kotlin": 88511}
package com.lehaine.rune.engine.node.renderable.entity import com.lehaine.littlekt.graph.node.Node import com.lehaine.littlekt.graph.node.addTo import com.lehaine.littlekt.graph.node.annotation.SceneGraphDslMarker import com.lehaine.littlekt.graph.node.node2d.Node2D import com.lehaine.littlekt.graphics.* import com.lehaine.littlekt.math.MutableVec2f import com.lehaine.littlekt.math.Vec2f import com.lehaine.littlekt.math.distSqr import com.lehaine.littlekt.math.geom.Angle import com.lehaine.littlekt.math.geom.cosine import com.lehaine.littlekt.math.geom.radians import com.lehaine.littlekt.math.geom.sine import com.lehaine.littlekt.math.interpolate import com.lehaine.littlekt.util.seconds import com.lehaine.rune.engine.Cooldown import com.lehaine.rune.engine.node.PixelSmoothFrameBuffer import com.lehaine.rune.engine.node.renderable.animatedSprite import kotlin.contracts.ExperimentalContracts import kotlin.contracts.InvocationKind import kotlin.contracts.contract import kotlin.math.* import kotlin.time.Duration @OptIn(ExperimentalContracts::class) fun Node.entity(gridCellSize: Float, callback: @SceneGraphDslMarker Entity.() -> Unit = {}): Entity { contract { callsInPlace(callback, InvocationKind.EXACTLY_ONCE) } return Entity(gridCellSize).also(callback).addTo(this) } open class Entity(val gridCellSize: Float) : Node2D() { val sprite = animatedSprite { name = "Skin" } var anchorX: Float get() = sprite.anchorX set(value) { sprite.anchorX = value } var anchorY: Float get() = sprite.anchorY set(value) { sprite.anchorY = value } var cx: Int = 0 var cy: Int = 0 var xr: Float = 0.5f var yr: Float = 1f var gravityX: Float = 0f var gravityY: Float = 0f var gravityMultiplier: Float = 1f var velocityX: Float = 0f var velocityY: Float = 0f var frictionX: Float = 0.82f var frictionY: Float = 0.82f var maxGridMovementPercent: Float = 0.33f var width: Float = gridCellSize var height: Float = gridCellSize val innerRadius get() = min(width, height) * ppuInv * 0.5 val outerRadius get() = max(width, height) * ppuInv * 0.5 var interpolatePixelPosition: Boolean = true var lastPx: Float = 0f var lastPy: Float = 0f private var _stretchX = 1f private var _stretchY = 1f var stretchX: Float get() = _stretchX set(value) { _stretchX = value _stretchY = 2 - value } var stretchY: Float get() = _stretchY set(value) { _stretchX = 2 - value _stretchY = value } /** * The current entity x-scaling. */ var entityScaleX = 1f /** * The current entity y-scaling. */ var entityScaleY = 1f var restoreSpeed: Float = 12f var dir: Int = 1 val px: Float get() { return if (interpolatePixelPosition) { fixedProgressionRatio.interpolate(lastPx, attachX) } else { attachX } } val py: Float get() { return if (interpolatePixelPosition) { fixedProgressionRatio.interpolate(lastPy, attachY) } else { attachY } } open val attachX get() = ((cx + xr) * gridCellSize) * ppuInv open val attachY get() = ((cy + yr) * gridCellSize) * ppuInv val centerX get() = attachX + (0.5f - anchorX) * width val centerY get() = attachY + (0.5f - anchorY) * height val top get() = attachY - anchorY * height * ppuInv val right get() = attachX + (1 - anchorX) * width * ppuInv val bottom get() = attachY + (1 - anchorY) * height * ppuInv val left get() = attachX - anchorX * width * ppuInv private val _topLeft = MutableVec2f() val topLeft: Vec2f get() = _topLeft.set(left, top).calculateVertex(centerX, centerY, globalRotation) private val _bottomLeft = MutableVec2f() val bottomLeft: Vec2f get() = _bottomLeft.set(left, bottom).calculateVertex(centerX, centerY, globalRotation) private val _bottomRight = MutableVec2f() val bottomRight: Vec2f get() = _bottomRight.set(right, bottom).calculateVertex(centerX, centerY, globalRotation) private val _topRight = MutableVec2f() private val topRight: Vec2f get() = _topRight.set(right, top).calculateVertex(centerX, centerY, globalRotation) private val _vertices = MutableList(4) { Vec2f(0f) } private val vertices: List<Vec2f> get() { _vertices[0] = topLeft _vertices[1] = bottomLeft _vertices[2] = bottomRight _vertices[3] = topRight return _vertices } private val _rect = MutableList(8) { 0f } private val rect: List<Float> get() { _rect[0] = vertices[0].x _rect[1] = vertices[0].y _rect[2] = vertices[1].x _rect[3] = vertices[1].y _rect[4] = vertices[2].x _rect[5] = vertices[2].y _rect[6] = vertices[3].x _rect[7] = vertices[3].y return _rect } val cooldown = Cooldown() val mouseX get() = (canvas as? PixelSmoothFrameBuffer)?.mouseX ?: 0f val mouseY get() = (canvas as? PixelSmoothFrameBuffer)?.mouseY ?: 0f val angleToMouse: Angle get() = atan2( mouseY - centerY, mouseX - centerX ).radians val dirToMouse: Int get() = dirTo(mouseX) private var ignorePosChanged = false init { anchorX = 0.5f anchorY = 1f onReady += { updateGridPosition() } } override fun onPositionChanged() { super.onPositionChanged() if (ignorePosChanged) return toPixelPosition(globalX, globalY) } override fun preUpdate(dt: Duration) { cd.update(dt) } override fun fixedUpdate() { updateGridPosition() } override fun postUpdate(dt: Duration) { ignorePosChanged = true globalPosition(px, py) ignorePosChanged = false entityScaleX = scaleX * dir * stretchX entityScaleY = scaleY * stretchY _stretchX += (1 - _stretchX) * min(1f, restoreSpeed * dt.seconds) _stretchY += (1 - _stretchY) * min(1f, restoreSpeed * dt.seconds) sprite.scaleX = entityScaleX sprite.scaleY = entityScaleY } private fun performSAT(poly2: List<Vec2f>): Boolean { val edges = tempVecList2 var i = 0 polyToEdges(vertices).forEach { edges[i].set(it) i++ } polyToEdges(poly2).forEach { edges[i].set(it) i++ } val axes = tempVecList3 repeat(edges.size) { index -> axes[index].set(orthogonal(edges[index])) } for (axis in axes) { val projection1 = tempVec2f2.set(project(vertices, axis)) val projection2 = tempVec2f3.set(project(poly2, axis)) if (!overlap(projection1, projection2)) { return false } } return true } private fun edgeVector(v1: Vec2f, v2: Vec2f): Vec2f = tempVec2f.set(v2).subtract(v1) private fun polyToEdges(poly: List<Vec2f>): List<Vec2f> { repeat(poly.size) { index -> tempVecList[index].set(edgeVector(poly[index], poly[(index + 1) % poly.size])) } return tempVecList } private fun orthogonal(vec2f: Vec2f): Vec2f = tempVec2f.set(vec2f.y, -vec2f.x) private fun project(poly: List<Vec2f>, axis: Vec2f): Vec2f { repeat(poly.size) { index -> tempFloatList[index] = poly[index].dot(axis) } return tempVec2f.set(tempFloatList.min(), tempFloatList.max()) } private fun overlap(projection1: Vec2f, projection2: Vec2f) = projection1.x <= projection2.y && projection2.x <= projection1.y /** * AABB check */ fun isCollidingWith(from: Entity, useSat: Boolean = false): Boolean { if (useSat) { if (globalRotation != 0.radians || from.globalRotation != 0.radians) { if (!isCollidingWithOuterCircle(from)) return false return performSAT(from.vertices) } } // normal rectangle overlap check val lx = left val lx2 = from.left val rx = right val rx2 = from.right if (lx >= rx2 || lx2 >= rx) { return false } val ly = top val ry = bottom val ly2 = from.top val ry2 = from.bottom if (ly >= ry2 || ly2 >= ry) { return false } return true } fun isCollidingWithInnerCircle(from: Entity): Boolean { val dist = innerRadius + from.innerRadius return distSqr(centerX, centerY, from.centerX, from.centerY) <= dist * dist } fun isCollidingWithOuterCircle(from: Entity): Boolean { val dist = outerRadius + from.outerRadius return distSqr(centerX, centerY, from.centerX, from.centerY) <= dist * dist } fun onPositionManuallyChanged() { lastPx = attachX lastPy = attachY } open fun updateGridPosition() { lastPx = attachX lastPy = attachY velocityX += calculateDeltaXGravity() velocityY += calculateDeltaYGravity() /** * Any movement greater than [maxGridMovementPercent] will increase the number of steps here. * The steps will break down the movement into smaller iterators to avoid jumping over grid collisions */ val steps = ceil(abs(velocityX) + abs(velocityY) / maxGridMovementPercent) if (steps > 0) { var i = 0 while (i < steps) { xr += velocityX / steps if (velocityX != 0f) { preXCheck() checkXCollision() } while (xr > 1) { xr-- cx++ } while (xr < 0) { xr++ cx-- } yr += velocityY / steps if (velocityY != 0f) { preYCheck() checkYCollision() } while (yr > 1) { yr-- cy++ } while (yr < 0) { yr++ cy-- } i++ } } velocityX *= frictionX if (abs(velocityX) <= 0.0005f) { velocityX = 0f } velocityY *= frictionY if (abs(velocityY) <= 0.0005f) { velocityY = 0f } } open fun calculateDeltaXGravity(): Float { return 0f } open fun calculateDeltaYGravity(): Float { return 0f } open fun preXCheck() = Unit open fun preYCheck() = Unit open fun checkXCollision() = Unit open fun checkYCollision() = Unit companion object { private val tempVec2f = MutableVec2f() private val tempVec2f2 = MutableVec2f() private val tempVec2f3 = MutableVec2f() private val tempVecList = MutableList(4) { MutableVec2f(0f) } private val tempVecList2 = MutableList(8) { MutableVec2f(0f) } private val tempVecList3 = MutableList(8) { MutableVec2f(0f) } private val tempFloatList = MutableList(4) { 0f } } } private fun MutableVec2f.calculateVertex(cx: Float, cy: Float, angle: Angle): MutableVec2f { val px = x - cx val py = y - cy val sin = angle.sine val cos = angle.cosine val nx = px * cos - py * sin val ny = px * sin + py * cos set(nx + cx, ny + cy) return this }
0
Kotlin
0
0
7934315a1b86b4b84a633761e6a842121e9c174f
11,917
rune-kt
Apache License 2.0
src/main/kotlin/org/kale/mail/EmailAccountConfig.kt
OdysseusLevy
58,777,555
false
null
package org.kale.mail /** * @author Odysseus Levy ([email protected]) */ data class EmailAccountConfig( var nickname: String ="", /** * Set user name. For example a gmail user name would be something like [email protected] * @group Properties */ var user: String = "", /** * Password (assumed to work with both imap and smtp) * @group Properties */ var password: String = "", /** * Server used to receive mail (using the IMAP protocol). For example gmail uses: imap.gmail.com * @group Properties */ var imapHost: String = "", /** * Optional, Advanced property -- usually the default will work * @group Properties */ var imapPort: Int = -1, /** * Server used to send out email. For example gmail uses smtp.gmail.com * @group Properties */ var smtpHost: String = "", var smtpPort: Int = 465);
0
Kotlin
0
0
15cd8558c704cd770b4f54ad3597a09c04dcd3f6
1,037
kale
Apache License 2.0
app/src/main/java/com/pikachu/wordle_2/ui/settings/SharedPreferencesHelper.kt
FrenzyExists
779,458,904
false
{"Kotlin": 33553}
package com.pikachu.wordle_2.ui.settings import android.content.Context import android.content.SharedPreferences import androidx.core.content.edit class SharedPreferencesHelper(context: Context) { private val sharedPreferences: SharedPreferences = context.getSharedPreferences("settings", Context.MODE_PRIVATE) enum class SettingKeys(val displayName: String) { WORD_LENGTH("Word Length"), DIFFICULTY("Difficulty"), SOUND_EFFECTS("Sound Effects"), HINTS("Hints"), TIMER("Timer"), VIBRATION("VibrationEnable"); companion object { fun fromDisplayName(name: String): SettingKeys? { return entries.find { it.displayName == name } } } } private fun settingsToString(key: SettingKeys): String { return key.displayName } fun saveSettings(value: Any, key: SettingKeys) { sharedPreferences.edit { when (value) { is Boolean -> putBoolean(settingsToString(key), value) is String -> putString(settingsToString(key), value) else -> throw IllegalArgumentException("Unsupported setting type") } } } fun getSettings(key: SettingKeys): Any? { return if(key == SettingKeys.SOUND_EFFECTS || key == SettingKeys.HINTS) { sharedPreferences.getBoolean(settingsToString(key), false) } else { sharedPreferences.getString(settingsToString(key), null) } } }
0
Kotlin
0
0
51fbfa5bd87e7fac31c386af1b40d39690d5139c
1,529
funny-app-or-something-idk
Apache License 2.0
app/src/main/java/com/example/a100gram/fragments/NewArticleFragment.kt
ochagovdanil
204,158,038
false
null
package com.example.a100gram.fragments import android.os.Bundle import android.view.* import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.example.a100gram.R import com.example.a100gram.helpers.ProgressBarDialog import com.example.a100gram.models.Article import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.FirebaseDatabase import kotlinx.android.synthetic.main.fragment_new_article.* import kotlinx.android.synthetic.main.partial_toolbar.* import java.text.SimpleDateFormat import java.util.* class NewArticleFragment : Fragment() { private lateinit var mEditTextTitle: EditText private lateinit var mEditTextContent: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) // init the toolbar menu options } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = LayoutInflater.from(context).inflate(R.layout.fragment_new_article, container, false) override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) initApp() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.new_article, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.item_new_article_fragment_publish -> { checkForm() true } else -> false } private fun initApp() { initToolbar() mEditTextTitle = et_new_article_fragment_title mEditTextContent = et_new_article_fragment_content } private fun initToolbar() { (activity as AppCompatActivity).setSupportActionBar(toolbar_custom.apply { title = getString(R.string.toolbar_new_article_fragment_title) }) } private fun checkForm() { // clear old errors mEditTextTitle.error = null mEditTextContent.error = null // get the fields val title = mEditTextTitle.text.toString() val content = mEditTextContent.text.toString() // check the form if (title.isEmpty()) { mEditTextTitle.error = "You must fill this field out!" return } if (title.length < 10) { mEditTextTitle.error = "The title is short!" return } if (content.isEmpty()) { mEditTextContent.error = "You must fill this field out!" return } if (content.length < 20) { mEditTextContent.error = "The content is short!" return } // everything's okay, let's post an article val user = FirebaseAuth.getInstance().currentUser postArticle( Article( user?.uid, user?.email, title, content, SimpleDateFormat( "dd.MM.yyyy", Locale.getDefault() ).format(Calendar.getInstance().time) ) ) } private fun postArticle(article: Article) { ProgressBarDialog.showDialog(activity as AppCompatActivity) FirebaseDatabase.getInstance().reference.child("articles").push().setValue(article) .addOnCompleteListener { task -> ProgressBarDialog.hideDialog(activity as AppCompatActivity) if (task.isSuccessful) { // everything's okay mEditTextTitle.text.clear() mEditTextContent.text.clear() mEditTextTitle.error = null mEditTextContent.error = null showMessage("Your article was successfully posted!") } else { showMessage("Something went wrong[setValue]") } } } private fun showMessage(message: String) { InformationDialogFragment().apply { arguments = Bundle().apply { putString("message", message) } }.show(activity?.supportFragmentManager!!, "InformationDialogFragment") } }
0
Kotlin
0
0
290201b6b32768f014dab71af1eaaff98a2c5dc5
4,367
100gram
MIT License
app/src/main/java/com/ncs/o2/Domain/Models/state/RegistrationFormState.kt
arpitmx
647,358,015
false
{"Kotlin": 1819184}
package com.ncs.o2.Domain.Models.state /* File : RegistrationFormState.kt -> com.ncs.o2.Domain.Models.state Description : State for registration form Author : <NAME> (VC uname : apple) Link : https://github.com/arpitmx From : Bitpolarity x Noshbae (@Project : O2 Android) Creation : 6:53 pm on 21/06/23 Todo > Tasks CLEAN CODE : Tasks BUG FIXES : Tasks FEATURE MUST HAVE : Tasks FUTURE ADDITION : */ data class RegistrationFormState( val email: String = "", val emailError: String? = null, val password: String = "", val passwordError: String? = null, val repeatedPassword: String = "", val repeatedPasswordError: String? = null, )
1
Kotlin
2
2
a00e406e84ef46c86015adeab4035111697f45c3
671
Oxygen
Apache License 2.0
app/src/main/java/com/iptriana/olly/ui/theme/Theme.kt
Iptriana98
803,436,856
false
{"Kotlin": 40543}
package com.iptriana.olly.ui.theme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.compositeOver import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.em import androidx.compose.ui.unit.sp @Composable fun OllyTheme( content: @Composable () -> Unit ) { MaterialTheme( colorScheme = colorPalette, typography = Typography, content = content ) } /** * A theme overlay used for dialogs. */ @Composable fun RallyDialogThemeOverlay(content: @Composable () -> Unit) { // Rally is always dark themed. val dialogColors = darkColorScheme( primary = Color.White, surface = Color.White.copy(alpha = 0.12f).compositeOver(Color.Black), onSurface = Color.White ) // Copy the current [Typography] and replace some text styles for this theme. val currentTypography = MaterialTheme.typography val dialogTypography = currentTypography.copy( bodyMedium = currentTypography.bodySmall.copy( fontWeight = FontWeight.Normal, fontSize = 20.sp, lineHeight = 28.sp, letterSpacing = 1.sp ), labelLarge = currentTypography.labelLarge.copy( fontWeight = FontWeight.Bold, letterSpacing = 0.2.em ) ) MaterialTheme(colorScheme = dialogColors, typography = dialogTypography, content = content) }
0
Kotlin
0
0
9c0171da9994ce8bb72b782a08e75f085d72e51d
1,560
Olly
Apache License 2.0
app/src/main/java/org/haidy/servify/data/mapper/Service.kt
HaidyAbuGom3a
805,534,454
false
{"Kotlin": 702248}
package org.haidy.servify.data.mapper import org.haidy.servify.data.dto.ServiceDto import org.haidy.servify.domain.model.Service fun ServiceDto.toService(): Service { return Service( id = id.toString(), name = name ?: "", description = description ?: "", imageUrl = image ?: "", status = status?.lowercase() == "true", discount = 0.0 ) }
0
Kotlin
0
2
8c2ba73cea5d29cc2ef7048d832f8ecea13f34ee
395
Servify
Apache License 2.0
src/commonMain/kotlin/matt/math/sigfig/sigfig.kt
mgroth0
532,380,281
false
{"Kotlin": 233084}
package matt.math.sigfig import matt.lang.anno.NeedsTest import matt.lang.anno.SupportedByChatGPT import matt.math.round.floorInt import kotlin.math.absoluteValue import kotlin.math.log10 import kotlin.math.pow import kotlin.math.roundToInt fun Float.roundToDecimalPlace(n: Int): Float { val factor = 10.0f.pow(n) return (factor * this).roundToInt() / factor } fun Double.roundToDecimalPlace(n: Int): Double { val factor = 10.0.pow(n) return (factor * this).roundToInt() / factor } fun Double.toStringRoundedToDecimalWithPaddedZeros(n: Int): String { val doubleWithPrecision = roundToDecimalPlace(n) val baseString = doubleWithPrecision.toString() return baseString.substringBefore('.') + '.' + baseString.substringAfter('.').padEnd(n, '0') } @SupportedByChatGPT fun Float.withPrecision(n: Int): Float { require(n >= 1) if (this == 0f) return this val exponent = log10(absoluteValue).floorInt() val magnitude = 10.0.pow(exponent).toFloat() val scaledValue = absoluteValue / magnitude val scale = 10.0.pow(n - 1).toFloat() val roundedScaledValue = (scaledValue * scale).roundToInt() / scale return roundedScaledValue * magnitude * (if (this < 0) -1 else 1) } fun Double.withPrecision(n: Int): Double { require(n >= 1) if (this == 0.0) return this val exponent = log10(absoluteValue).floorInt() val magnitude = 10.0.pow(exponent) val scaledValue = absoluteValue / magnitude val scale = 10.0.pow(n - 1) val roundedScaledValue = (scaledValue * scale).roundToInt() / scale return roundedScaledValue * magnitude * (if (this < 0) -1 else 1) } private const val G_EXP = 3 private val LOW_CUT_OFF = 10.0.pow(-4) private val HIGH_CUT_OFF = 10.0.pow(G_EXP) @NeedsTest /*tries to replicate the 'G' conversion from https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html*/ fun Double.decimalOrScientificNotation(): String { if (this.isInfinite()) return if (this >= 0) "Infinity" else "-Infinity" if (this.isNaN()) return "NaN" if (this == 0.0) withPrecision(G_EXP).toString() val decimalPrecise = withPrecision(G_EXP) return if (decimalPrecise in LOW_CUT_OFF..HIGH_CUT_OFF) { decimalPrecise.toString() } else { toScientificNotationString() } } @NeedsTest @SupportedByChatGPT fun Double.toScientificNotationString(): String { if (this == 0.0) return "0.0e+0" val positiveNumber = if (this < 0) -this else this var exponent = 0 var normalizedNumber = positiveNumber while (normalizedNumber >= 10) { normalizedNumber /= 10 exponent++ } while (normalizedNumber < 1) { normalizedNumber *= 10 exponent-- } val mantissa = buildMantissaString(normalizedNumber) return mantissa + if (exponent >= 0) "+" else "" + "$exponent" } @NeedsTest @SupportedByChatGPT private fun buildMantissaString(normalizedNumber: Double): String { val mantissaDigits = StringBuilder() var remainingDigits = 6 var currentNumber = normalizedNumber while (remainingDigits > 0) { currentNumber *= 10 val digit = currentNumber.toInt() mantissaDigits.append(digit) currentNumber -= digit remainingDigits-- } return mantissaDigits.toString() }
0
Kotlin
0
0
f2a1a04cee2b5eb0e577b033984a3df25a2e3983
3,303
math
MIT License
feature/feed-impl/src/main/kotlin/org/michaelbel/movies/feed/ui/FeedGridLoading.kt
michaelbel
115,437,864
false
null
package org.michaelbel.movies.feed.ui import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import org.michaelbel.movies.network.model.MovieResponse import org.michaelbel.movies.persistence.database.entity.MovieDb import org.michaelbel.movies.ui.placeholder.PlaceholderHighlight import org.michaelbel.movies.ui.placeholder.material3.fade import org.michaelbel.movies.ui.placeholder.placeholder import org.michaelbel.movies.ui.preview.DevicePreviews import org.michaelbel.movies.ui.theme.MoviesTheme @Composable fun FeedGridLoading( modifier: Modifier = Modifier, paddingValues: PaddingValues = PaddingValues(), ) { LazyVerticalStaggeredGrid( columns = StaggeredGridCells.Fixed(2), modifier = modifier, contentPadding = paddingValues, verticalItemSpacing = 8.dp, horizontalArrangement = Arrangement.spacedBy(8.dp), userScrollEnabled = false ) { items(MovieResponse.DEFAULT_PAGE_SIZE.div(2)) { FeedGridMovieBox( movie = MovieDb.Empty, modifier = Modifier .fillMaxWidth() .placeholder( visible = true, color = MaterialTheme.colorScheme.inversePrimary, shape = MaterialTheme.shapes.small, highlight = PlaceholderHighlight.fade() ) ) } } } @Composable @DevicePreviews private fun FeedGridLoadingPreview() { MoviesTheme { FeedGridLoading( modifier = Modifier .fillMaxSize() .padding(start = 8.dp, top = 8.dp, end = 8.dp) .background(MaterialTheme.colorScheme.background) ) } }
0
null
25
151
02a1c9ff9c9ccd6dcdb3d389323baa2d3300a169
2,329
movies
Apache License 2.0
app/src/main/java/dev/jianastrero/composefireworks/ui/app/App.kt
jianastrero
739,001,715
false
{"Kotlin": 26344}
package dev.jianastrero.composefireworks.ui.app import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.compose.NavHost import androidx.navigation.compose.rememberNavController import dev.jianastrero.composefireworks.enumeration.Screens import dev.jianastrero.composefireworks.ui.nav_graph.mainNavGraph @Composable fun App(modifier: Modifier = Modifier) { val navController = rememberNavController() NavHost( navController = navController, startDestination = Screens.Main.route, modifier = modifier ) { mainNavGraph( onBack = { navController.popBackStack() }, onNavigate = { screen -> navController.navigate(screen.route) }, modifier = Modifier.fillMaxSize() ) } }
0
Kotlin
0
0
ab5e0dd13c48ddb64ab42db84f4494f9099f0054
921
compose-fireworks
MIT License
intellij-plugin/educational-core/testSrc/com/jetbrains/edu/rules/MinPlatformVersion.kt
JetBrains
43,696,115
false
{"Kotlin": 5014435, "Java": 42267, "Python": 19649, "HTML": 14893, "CSS": 10327, "JavaScript": 302, "Shell": 71}
package com.jetbrains.edu.rules /** * Specify minimal platform version necessary for test execution * * @see [ConditionalExecutionRule] */ @Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS) annotation class MinPlatformVersion(val version: String)
7
Kotlin
49
150
9cec6c97d896f4485e76cf9a2a95f8a8dd21c982
300
educational-plugin
Apache License 2.0
simplexml-ksp-processor/src/main/kotlin/ua/vald_zx/simplexml/ksp/processor/generator/SerializeFunctionGenerator.kt
ValdZX
372,240,045
false
{"Kotlin": 236365}
package ua.vald_zx.simplexml.ksp.processor.generator import com.squareup.kotlinpoet.FunSpec import ua.vald_zx.simplexml.ksp.processor.ClassToGenerate import ua.vald_zx.simplexml.ksp.processor.Field internal fun FunSpec.Builder.generateSerialization(classToGenerate: ClassToGenerate): FunSpec.Builder { val serializersMap = generateAndGetSerializers(classToGenerate) beginControlFlow("tagFather.apply") renderChildren(classToGenerate.dom, serializersMap) endControlFlow() return this } internal fun FunSpec.Builder.renderChildren( fields: Iterable<Field>, serializersMap: Map<Field, FieldSerializer> ) { fields.forEach { field -> val fieldSerializer = serializersMap.toMutableMap()[field] field.serializationGenerator.render(this, fieldSerializer, serializersMap) } }
0
Kotlin
0
1
6fe7aad73f82b8719a9aafd9285a354cf79de8ef
822
SimpleXmlKsp
Apache License 2.0
simplexml-ksp-processor/src/main/kotlin/ua/vald_zx/simplexml/ksp/processor/generator/SerializeFunctionGenerator.kt
ValdZX
372,240,045
false
{"Kotlin": 236365}
package ua.vald_zx.simplexml.ksp.processor.generator import com.squareup.kotlinpoet.FunSpec import ua.vald_zx.simplexml.ksp.processor.ClassToGenerate import ua.vald_zx.simplexml.ksp.processor.Field internal fun FunSpec.Builder.generateSerialization(classToGenerate: ClassToGenerate): FunSpec.Builder { val serializersMap = generateAndGetSerializers(classToGenerate) beginControlFlow("tagFather.apply") renderChildren(classToGenerate.dom, serializersMap) endControlFlow() return this } internal fun FunSpec.Builder.renderChildren( fields: Iterable<Field>, serializersMap: Map<Field, FieldSerializer> ) { fields.forEach { field -> val fieldSerializer = serializersMap.toMutableMap()[field] field.serializationGenerator.render(this, fieldSerializer, serializersMap) } }
0
Kotlin
0
1
6fe7aad73f82b8719a9aafd9285a354cf79de8ef
822
SimpleXmlKsp
Apache License 2.0
app/src/androidTest/java/ru/cherryperry/instavideo/renderscript/BitmapComparator.kt
CherryPerry
157,012,355
false
{"Kotlin": 175332, "Java": 11140, "RenderScript": 2719}
package ru.cherryperry.instavideo.renderscript import android.graphics.Bitmap import android.graphics.Color /** * Compares two bitmaps with color loss after YUV <-> RGB conversion. */ object BitmapComparator { /** * Images are very similiar. */ fun areImagesProbablySame(bitmap1: Bitmap, bitmap2: Bitmap): Boolean { if (bitmap1.width != bitmap2.width || bitmap1.height != bitmap2.height || bitmap1.config != bitmap2.config) { return false } for (y in 0 until bitmap1.height) { for (x in 0 until bitmap1.width) { val p1 = bitmap1.getPixel(x, y) val p2 = bitmap2.getPixel(x, y) if (!(p1.r() colorDelta p2.r() && p1.g() colorDelta p2.g() && p1.b() colorDelta p2.b())) { return false } } } return true } /** 20% color delta **/ private infix fun Int.colorDelta(other: Int): Boolean = Math.abs(this - other) < 50 /** Red color component **/ private fun Int.r(): Int = Color.red(this) /** Green color component **/ private fun Int.g(): Int = Color.green(this) /** Blue color component **/ private fun Int.b(): Int = Color.blue(this) }
1
Kotlin
7
47
54886e7b78ee09f8c834dec9d1a50f50ff7fd0c5
1,252
VideoCrop
Do What The F*ck You Want To Public License
src/main/java/com/sayzen/campfiresdk/screens/wiki/SWikiList.kt
ZeonXX
381,986,881
false
{"Kotlin": 2097097}
package com.sayzen.campfiresdk.screens.wiki import android.view.View import com.dzen.campfire.api.API import com.dzen.campfire.api.API_RESOURCES import com.dzen.campfire.api.API_TRANSLATE import com.dzen.campfire.api.models.wiki.WikiTitle import com.dzen.campfire.api.requests.wiki.RWikiItemGet import com.dzen.campfire.api.requests.wiki.RWikiListGet import com.sayzen.campfiresdk.R import com.sayzen.campfiresdk.controllers.ControllerApi import com.sayzen.campfiresdk.controllers.ControllerLinks import com.sayzen.campfiresdk.controllers.api import com.sayzen.campfiresdk.controllers.t import com.sayzen.campfiresdk.models.events.wiki.EventWikiCreated import com.sayzen.campfiresdk.models.events.wiki.EventWikiListChanged import com.sayzen.campfiresdk.support.ApiRequestsSupporter import com.sup.dev.android.libs.screens.navigator.NavigationAction import com.sup.dev.android.libs.screens.navigator.Navigator import com.sup.dev.android.tools.ToolsAndroid import com.sup.dev.android.tools.ToolsToast import com.sup.dev.android.tools.ToolsView import com.sup.dev.android.views.screens.SLoadingRecycler import com.sup.dev.java.libs.eventBus.EventBus class SWikiList( val fandomId: Long, val prefLanguageId: Long, val itemId: Long, val itemName: String, // would be nice if selecting articles was possible as well, but i'm too lazy val onSelectSection: ((WikiTitle) -> Unit)? = null, ) : SLoadingRecycler<CardWikiItem, WikiTitle>() { companion object { fun instanceFandomId(fandomId: Long, action: NavigationAction) { Navigator.action(action, SWikiList(fandomId, 0, 0, "")) } fun instanceItemId(wikiItemId: Long, action: NavigationAction) { ApiRequestsSupporter.executeInterstitial(action, RWikiItemGet(wikiItemId)) { r -> SWikiList(r.wikiTitle.fandomId, 0, r.wikiTitle.itemId, r.wikiTitle.getName(ControllerApi.getLanguageCode())) } } } private val eventBus = EventBus .subscribe(EventWikiCreated::class) { if (it.item.fandomId == fandomId && it.item.parentItemId == itemId) adapter.reloadBottom() } .subscribe(EventWikiListChanged::class) { if (it.item == null || (it.item.fandomId == fandomId && it.item.parentItemId == itemId)) adapter.reloadBottom() } init { disableShadows() disableNavigation() addToolbarIcon(R.drawable.ic_insert_link_white_24dp) { if (itemId > 0) ToolsAndroid.setToClipboard(ControllerLinks.linkToWikiItemId(itemId)) else ToolsAndroid.setToClipboard(ControllerLinks.linkToWikiFandomId(fandomId)) ToolsToast.show(t(API_TRANSLATE.app_copied)) } if (itemName.isEmpty()) setTitle(t(API_TRANSLATE.app_wiki)) else setTitle(itemName) setTextEmpty(t(API_TRANSLATE.wiki_list_empty)) setBackgroundImage(API_RESOURCES.IMAGE_BACKGROUND_29) (vFab as View).visibility = if (ControllerApi.can(fandomId, ControllerApi.getLanguage("en").id, API.LVL_MODERATOR_WIKI_EDIT)) View.VISIBLE else View.GONE if (onSelectSection != null) { vFab.setImageResource(R.drawable.ic_done_white_24dp) vFab.setOnClickListener { Navigator.remove(this) onSelectSection.invoke(WikiTitle().apply { fandomId = [email protected] itemId = [email protected] }) } ToolsView.setFabColorR(vFab, R.color.green_700) } else { vFab.setImageResource(R.drawable.ic_add_white_24dp) vFab.setOnClickListener { Navigator.to(SWikiItemCreate(fandomId, itemId)) } } adapter.setBottomLoader { onLoad, cards -> subscription = RWikiListGet(fandomId, itemId, cards.size.toLong()) .onComplete { r -> onLoad.invoke(r.items) } .onNetworkError { onLoad.invoke(null) } .send(api) } } override fun classOfCard() = CardWikiItem::class override fun map(item: WikiTitle) = CardWikiItem(item, prefLanguageId, onSelectSection.let { if (it != null) { { Navigator.to(SWikiList( item.fandomId, 0, item.itemId, item.getName(ControllerApi.getLanguageCode()) ) { item -> Navigator.remove(this) it(item) }) } } else { null } }, onSelectSection.let { if (it != null) { { item -> Navigator.remove(this) it(item) } } else { null } }) { adapter.directItems().map { (it as CardWikiItem).wikiItem } } }
0
Kotlin
2
0
9930e65c1f213bac9266046be22eb937a03f151e
4,896
CampfireSDK
Apache License 2.0
kotlin-node/src/jsMain/generated/node/fs/symlink.suspend.kt
JetBrains
93,250,841
false
{"Kotlin": 12363456, "JavaScript": 408220}
// Generated by Karakum - do not modify it manually! package node.fs import js.core.Void suspend fun symlink(target: PathLike, path: PathLike, type: String? = undefined.unsafeCast<Nothing>()): Void = symlinkAsync( target, path, type ).await()
39
Kotlin
165
1,330
809b00e4aa9fbaa46d0ebfd82ac2b574b5898dfc
263
kotlin-wrappers
Apache License 2.0
app/src/main/java/com/gdgnairobi/devfest18/ui/MainActivity.kt
etonotieno
149,093,023
false
{"Kotlin": 16213}
package com.gdgnairobi.devfest18.ui import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.LinearLayoutManager import com.gdgnairobi.devfest18.R import com.gdgnairobi.devfest18.databinding.MainActivityBinding import net.danlew.android.joda.JodaTimeAndroid class MainActivity : AppCompatActivity() { private val newsViewModel by lazy { ViewModelProviders.of(this).get(MainViewModel::class.java) } private val mainBinding: MainActivityBinding by lazy { DataBindingUtil.setContentView<MainActivityBinding>(this, R.layout.main_activity) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) JodaTimeAndroid.init(this) mainBinding.viewModel = newsViewModel mainBinding.setLifecycleOwner(this) mainBinding.mainActivityRecyclerView.apply { adapter = NewsAdapter() layoutManager = LinearLayoutManager(this@MainActivity) } } }
1
Kotlin
1
2
e25c228f247bb1f65a06c8f4c7cfc4bb8891dd93
1,117
DevFest18
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/PennantOff.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.BadgeOff: ImageVector get() { if (_badgeOff != null) { return _badgeOff!! } _badgeOff = Builder(name = "BadgeOff", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(7.0f, 7.0f) verticalLineToRelative(10.0f) lineToRelative(5.0f, 3.0f) lineToRelative(5.0f, -3.0f) moveToRelative(0.0f, -4.0f) verticalLineToRelative(-9.0f) lineToRelative(-5.0f, 3.0f) lineToRelative(-2.496f, -1.497f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.0f, 3.0f) lineToRelative(18.0f, 18.0f) } } .build() return _badgeOff!! } private var _badgeOff: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,115
compose-icon-collections
MIT License
src/test/kotlin/thuan/handsome/optimizer/MathFuncTest.kt
duckladydinh
227,356,261
false
{"Fortran": 148795, "Kotlin": 70813, "C": 5608, "Makefile": 1992, "SWIG": 381, "Shell": 257}
package thuan.handsome.optimizer import kotlin.math.pow import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.EnumSource import thuan.handsome.core.optimizer.BayesianOptimizer import thuan.handsome.core.optimizer.Optimizer import thuan.handsome.core.optimizer.RandomOptimizer import thuan.handsome.core.xspace.UniformXSpace import thuan.handsome.gp.kernel.* class MathFuncTest { companion object { fun testNaiveOptimizer(optimizer: Optimizer) { val xSpace = UniformXSpace() xSpace.addParam("x", -100.0, 100.0) xSpace.addParam("y", -100.0, 100.0) xSpace.addParam("z", -100.0, 100.0) xSpace.addParam("w", -100.0, 100.0) val func = fun(params: Map<String, Any>): Double { val x = params["x"] as Double val y = params["y"] as Double val z = params["z"] as Double val w = params["w"] as Double return -((x - 1).pow(2) + (y - 2).pow(2) + (z - 3).pow(2) + (w - 4).pow(2)) } val (x, y) = optimizer.argmax(func, xSpace = xSpace, maxiter = 30) println("At { ${(x.map { "${it.key} : ${it.value}" }.joinToString(" | "))} }") println("y = $y") } } @Test fun naiveFunctionTestWithRBF() { testNaiveOptimizer(BayesianOptimizer(kernel = RBF())) } @ParameterizedTest @EnumSource(MaternType::class) fun naiveFunctionTestWithMatern(maternType: MaternType) { testNaiveOptimizer(BayesianOptimizer(kernel = Matern(nu = maternType))) } @Test fun naiveFunctionTestWithRandom() { testNaiveOptimizer(RandomOptimizer()) } }
0
Fortran
0
0
e3f3777734a08758734ef645ea5b53e03c31e278
1,821
KotlinML
MIT License
app/src/main/java/com/task/data/remote/dto/Multimedia.kt
ChandoraAnkit
241,170,670
true
{"Kotlin": 70361, "HTML": 53}
package com.task.data.remote.dto import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Multimedia( var caption: String = "", var copyright: String = "", var format: String = "", var height: Int = 0, var subtype: String = "", var type: String = "", var url: String = "", var width: Int = 0 ):Parcelable
0
Kotlin
0
0
387c2279903de87c59f03490e652d6d940255735
372
MVVM-Kotlin-Android-Architecture
Apache License 2.0
data/slack-jackson-dto/src/main/kotlin/io/olaph/slack/dto/jackson/common/messaging/Element.kt
nmchau
183,535,942
true
{"Kotlin": 505011}
package io.olaph.slack.dto.jackson.common.messaging import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.annotation.JsonSerialize import io.olaph.slack.dto.jackson.common.messaging.composition.Confirmation import io.olaph.slack.dto.jackson.common.messaging.composition.Option import io.olaph.slack.dto.jackson.common.messaging.composition.OptionGroup import io.olaph.slack.dto.jackson.common.messaging.composition.Text import java.time.LocalDate sealed class Element(@JsonProperty("type") val type: Type) { @JsonSerialize(using = Type.Serializer::class) enum class Type(private val typeString: String) { IMAGE("image"), BUTTON("button"), STATIC_SELECT("static_select"), EXTERNAL_SELECT("external_select"), USERS_SELECT("users_select"), CONVERSATIONS_SELECT("conversations_select"), CHANNELS_SELECT("channels_select"), DATE_PICKER("datepicker"), OVERFLOW("overflow"); class Serializer : JsonSerializer<Type>() { override fun serialize(value: Type, gen: JsonGenerator?, serializers: SerializerProvider?) { gen?.writeString(value.typeString) } } } /** * https://api.slack.com/reference/messaging/block-elements#image */ data class Image constructor(@JsonProperty("image_url") val imageUrl: String, @JsonProperty("alt_text") val altText: String) : Element(Type.IMAGE) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#button */ data class Button constructor(@JsonProperty("text") val text: Text, @JsonProperty("action_id") val actionId: String, @JsonProperty("url") val url: String? = null, @JsonProperty("value") val value: String? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.BUTTON) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#select */ data class StaticSelect constructor(@JsonProperty("placeholder") val placeholderText: Text, @JsonProperty("action_id") val actionId: String, @JsonProperty("options") val options: List<Option>, @JsonProperty("option_groups") val optionGroups: List<OptionGroup>? = null, @JsonProperty("initial_option") val initialOption: Option? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.STATIC_SELECT) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#external-select */ data class ExternalSelect constructor(@JsonProperty("placeholder") val placeholderText: Text, @JsonProperty("action_id") val actionId: String, @JsonProperty("options") val options: List<Option>, @JsonProperty("option_groups") val optionGroups: List<OptionGroup>? = null, @JsonProperty("initial_option") val initialOption: Option? = null, @JsonProperty("min_query_length") val minQueryLength: Int? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.EXTERNAL_SELECT) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#users-select */ data class UsersSelect constructor(@JsonProperty("placeholder") val placeholderText: Text, @JsonProperty("action_id") val actionId: String, @JsonProperty("initial_user") val initialUserId: String? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.USERS_SELECT) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#conversation-select */ data class ConversationsSelect constructor(@JsonProperty("placeholder") val placeholderText: Text, @JsonProperty("action_id") val actionId: String, @JsonProperty("initial_conversation") val initialConversationId: String? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.CONVERSATIONS_SELECT) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#channel-select */ data class ChannelsSelect constructor(@JsonProperty("placeholder") val placeholderText: Text, @JsonProperty("action_id") val actionId: String, @JsonProperty("initial_channels") val initialChannelsId: String? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.CHANNELS_SELECT) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#overflow */ data class Overflow constructor(@JsonProperty("action_id") val actionId: String, @JsonProperty("options") val options: List<Option>, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.OVERFLOW) { companion object } /** * https://api.slack.com/reference/messaging/block-elements#datepicker */ data class DatePicker constructor(@JsonProperty("action_id") val actionId: String, @JsonProperty("placeholder") val placeholderText: Text? = null, @JsonProperty("initial_date") val initialChannelsId: LocalDate? = null, @JsonProperty("confirm") val confirmation: Confirmation? = null) : Element(Type.OVERFLOW) { companion object } }
0
Kotlin
0
0
227983e8f31bf9bc9b0056782328679f4a3409f1
6,602
slack-spring-boot-starter
MIT License
src/main/kotlin/no/nav/arbeidsgiver/sykefravarsstatistikk/api/applikasjon/domenemodeller/Statistikkategori.kt
navikt
201,881,144
false
{"Kotlin": 796531, "Shell": 1600, "Dockerfile": 213}
package no.nav.arbeidsgiver.sykefravarsstatistikk.api.applikasjon.domenemodeller enum class Statistikkategori { LAND, SEKTOR, NÆRING, BRANSJE, OVERORDNET_ENHET, VIRKSOMHET, NÆRINGSKODE }
0
Kotlin
2
0
fd3e4795c206dd0565fb8fc968504f0df5acae09
216
sykefravarsstatistikk-api
MIT License
app/src/main/java/com/friendly_machines/frbpdoctor/watchprotocol/command/WatchProfileSex.kt
daym
744,679,396
false
{"Kotlin": 177161}
package com.friendly_machines.frbpdoctor.watchprotocol.command enum class WatchProfileSex(val code: Byte) { Female(0), Male(1); companion object { fun parse(code: Byte): WatchProfileSex? { return when (code) { 0.toByte() -> Female 1.toByte() -> Male else -> null } } } }
0
Kotlin
1
1
f6c5c0c8320ca29f976b8eb57c397e0db01bc13c
376
frbpdoctor
BSD 2-Clause FreeBSD License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/CloudBackUpAlt.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.CloudBackUpAlt: ImageVector get() { if (_cloudBackUpAlt != null) { return _cloudBackUpAlt!! } _cloudBackUpAlt = Builder(name = "CloudBackUpAlt", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(18.0f, 18.0f) curveToRelative(0.0f, 3.309f, -2.691f, 6.0f, -6.0f, 6.0f) reflectiveCurveToRelative(-6.0f, -2.691f, -6.0f, -6.0f) curveToRelative(0.0f, -0.223f, 0.013f, -0.443f, 0.036f, -0.66f) curveToRelative(0.088f, -0.823f, 0.82f, -1.425f, 1.651f, -1.331f) curveToRelative(0.823f, 0.088f, 1.42f, 0.827f, 1.331f, 1.651f) curveToRelative(-0.012f, 0.111f, -0.019f, 0.225f, -0.019f, 0.34f) curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f) reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f) curveToRelative(0.0f, -1.302f, -0.839f, -2.402f, -2.0f, -2.816f) verticalLineToRelative(1.27f) curveToRelative(0.0f, 0.452f, -0.534f, 0.693f, -0.873f, 0.394f) lineToRelative(-2.71f, -2.389f) curveToRelative(-0.556f, -0.48f, -0.556f, -1.32f, 0.0f, -1.8f) lineToRelative(2.71f, -2.389f) curveToRelative(0.339f, -0.299f, 0.873f, -0.058f, 0.873f, 0.394f) verticalLineToRelative(1.426f) curveToRelative(2.833f, 0.478f, 5.0f, 2.942f, 5.0f, 5.91f) close() moveTo(17.81f, 4.945f) curveToRelative(-0.148f, -0.03f, -0.263f, -0.115f, -0.322f, -0.243f) curveTo(15.9f, 1.358f, 12.226f, -0.507f, 8.559f, 0.163f) curveTo(5.21f, 0.775f, 2.584f, 3.449f, 2.024f, 6.817f) curveToRelative(-0.164f, 0.99f, -0.152f, 1.983f, 0.034f, 2.95f) curveToRelative(0.02f, 0.103f, -0.046f, 0.249f, -0.162f, 0.354f) curveToRelative(-1.188f, 1.081f, -1.896f, 2.727f, -1.896f, 4.402f) curveToRelative(0.0f, 1.341f, 0.488f, 2.633f, 1.375f, 3.638f) curveToRelative(0.297f, 0.336f, 0.71f, 0.508f, 1.126f, 0.508f) curveToRelative(0.353f, 0.0f, 0.706f, -0.124f, 0.991f, -0.375f) curveToRelative(0.621f, -0.548f, 0.681f, -1.496f, 0.133f, -2.117f) curveToRelative(-0.403f, -0.457f, -0.625f, -1.044f, -0.625f, -1.653f) curveToRelative(0.0f, -0.82f, 0.359f, -1.677f, 0.915f, -2.183f) curveToRelative(0.891f, -0.809f, 1.308f, -2.013f, 1.089f, -3.143f) curveToRelative(-0.119f, -0.616f, -0.126f, -1.252f, -0.021f, -1.889f) curveToRelative(0.348f, -2.09f, 2.039f, -3.814f, 4.115f, -4.194f) curveToRelative(2.367f, -0.433f, 4.656f, 0.72f, 5.677f, 2.872f) curveToRelative(0.468f, 0.99f, 1.359f, 1.683f, 2.447f, 1.901f) curveToRelative(2.188f, 0.437f, 3.777f, 2.376f, 3.777f, 4.636f) curveToRelative(0.0f, 0.89f, -0.259f, 1.75f, -0.749f, 2.487f) curveToRelative(-0.459f, 0.69f, -0.271f, 1.621f, 0.418f, 2.08f) reflectiveCurveToRelative(1.621f, 0.271f, 2.08f, -0.418f) curveToRelative(0.818f, -1.231f, 1.251f, -2.666f, 1.251f, -4.172f) curveToRelative(0.0f, -3.662f, -2.604f, -6.84f, -6.19f, -7.555f) close() } } .build() return _cloudBackUpAlt!! } private var _cloudBackUpAlt: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,417
icons
MIT License
combined/src/main/kotlin/com/github/jan222ik/ui/components/inputs/ShortcutDisplay.kt
jan222ik
462,289,211
false
{"Kotlin": 852617, "Java": 17948}
package com.github.jan222ik.ui.components.inputs import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.nativeKeyCode import androidx.compose.ui.unit.dp import java.awt.event.KeyEvent @ExperimentalComposeUiApi @Composable fun ShortcutDisplay(keys: List<Key>, enabled: Boolean = true) { val textColor = Color.Black.copy(alpha = 1f.takeIf { enabled } ?: ContentAlpha.disabled) @Composable fun KeyDisplay(key: Key) { Box( modifier = Modifier .background(color = Color.LightGray.copy(alpha = 1f.takeIf { enabled } ?: ContentAlpha.disabled)) .border( width = 1.dp, color = Color.DarkGray ) .clip(shape = RoundedCornerShape(size = 16.dp)) ) { Surface( modifier = Modifier.padding(horizontal = 3.dp).padding(bottom = 3.dp, top = 1.dp), color = Color.White, elevation = 5.dp ) { Text( text = key.nativeKeyCode.takeIf { key != Key.Escape } ?.let { KeyEvent.getKeyText(it) } ?: "Esc", style = MaterialTheme.typography.caption, color = textColor ) } } } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp) ) { keys.forEachIndexed { index, key -> if (index != 0) { Text( text = "+", style = MaterialTheme.typography.caption, color = textColor ) } KeyDisplay(key) } } }
0
Kotlin
0
0
e67597e41b47ec7676aa0e879062d8356f1b4672
2,387
MSc-Master-Composite
Apache License 2.0
tests/output/kotlin/src/commonTest/kotlin/com/algolia/e2e/SearchTest.kt
algolia
419,291,903
false
{"PHP": 5272264, "Ruby": 4629939, "C#": 4210619, "Python": 4019761, "Java": 3898681, "Swift": 3302311, "Scala": 3002553, "JavaScript": 2461797, "Dart": 2087466, "Kotlin": 1866170, "TypeScript": 1757483, "Mustache": 653134, "CSS": 41876, "Go": 29433, "Shell": 8893, "HTML": 981, "Objective-C": 149}
// Code generated by OpenAPI Generator (https://openapi-generator.tech), manual changes will be lost - read more on https://github.com/algolia/api-clients-automation. DO NOT EDIT. package com.algolia.e2e import com.algolia.client.api.SearchClient import com.algolia.client.configuration.* import com.algolia.client.model.search.* import com.algolia.client.transport.* import com.algolia.utils.* import io.github.cdimascio.dotenv.Dotenv import io.ktor.http.* import kotlinx.coroutines.test.* import kotlinx.serialization.encodeToString import kotlinx.serialization.json.* import org.skyscreamer.jsonassert.JSONAssert import org.skyscreamer.jsonassert.JSONCompareMode import kotlin.test.* class SearchTest { var client: SearchClient init { if (System.getenv("CI") == "true") { this.client = SearchClient(appId = System.getenv("ALGOLIA_APPLICATION_ID"), apiKey = System.getenv("ALGOLIA_ADMIN_KEY")) } else { val dotenv = Dotenv.configure().directory("../../").load() this.client = SearchClient(appId = dotenv["ALGOLIA_APPLICATION_ID"], apiKey = dotenv["ALGOLIA_ADMIN_KEY"]) } } @Test fun `browse with minimal parameters`() = runTest { client.runTest( call = { browse( indexName = "cts_e2e_browse", ) }, response = { JSONAssert.assertEquals("{\"page\":0,\"nbHits\":33191,\"nbPages\":34,\"hitsPerPage\":1000,\"query\":\"\",\"params\":\"\"}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `getRule`() = runTest { client.runTest( call = { getRule( indexName = "cts_e2e_browse", objectID = "qr-1725004648916", ) }, response = { JSONAssert.assertEquals("{\"description\":\"test_rule\",\"enabled\":true,\"objectID\":\"qr-1725004648916\",\"conditions\":[{\"alternatives\":true,\"anchoring\":\"contains\",\"pattern\":\"zorro\"}],\"consequence\":{\"params\":{\"ignorePlurals\":\"true\"},\"filterPromotes\":true,\"promote\":[{\"objectIDs\":[\"Æon Flux\"],\"position\":0}]}}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `getSettings`() = runTest { client.runTest( call = { getSettings( indexName = "cts_e2e_settings", ) }, response = { JSONAssert.assertEquals("{\"minWordSizefor1Typo\":4,\"minWordSizefor2Typos\":8,\"hitsPerPage\":100,\"maxValuesPerFacet\":100,\"paginationLimitedTo\":10,\"exactOnSingleWordQuery\":\"attribute\",\"ranking\":[\"typo\",\"geo\",\"words\",\"filters\",\"proximity\",\"attribute\",\"exact\",\"custom\"],\"separatorsToIndex\":\"\",\"removeWordsIfNoResults\":\"none\",\"queryType\":\"prefixLast\",\"highlightPreTag\":\"<em>\",\"highlightPostTag\":\"</em>\",\"alternativesAsExact\":[\"ignorePlurals\",\"singleWordSynonym\"]}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `search for a single hits request with minimal parameters4`() = runTest { client.runTest( call = { search( searchMethodParams = SearchMethodParams( requests = listOf( SearchForHits( indexName = "cts_e2e_search_empty_index", ), ), ), ) }, response = { JSONAssert.assertEquals("{\"results\":[{\"hits\":[],\"page\":0,\"nbHits\":0,\"nbPages\":0,\"hitsPerPage\":20,\"exhaustiveNbHits\":true,\"exhaustiveTypo\":true,\"exhaustive\":{\"nbHits\":true,\"typo\":true},\"query\":\"\",\"params\":\"\",\"index\":\"cts_e2e_search_empty_index\",\"renderingContent\":{}}]}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `search with highlight and snippet results5`() = runTest { client.runTest( call = { search( searchMethodParams = SearchMethodParams( requests = listOf( SearchForHits( indexName = "cts_e2e_highlight_snippet_results", query = "vim", attributesToSnippet = listOf("*:20"), attributesToHighlight = listOf("*"), attributesToRetrieve = listOf("*"), ), ), ), ) }, response = { JSONAssert.assertEquals("{\"results\":[{\"hits\":[{\"editor\":{\"name\":\"vim\",\"type\":\"beforeneovim\"},\"names\":[\"vim\",\":q\"],\"_snippetResult\":{\"editor\":{\"name\":{\"value\":\"<em>vim</em>\",\"matchLevel\":\"full\"},\"type\":{\"value\":\"beforeneovim\",\"matchLevel\":\"none\"}},\"names\":[{\"value\":\"<em>vim</em>\",\"matchLevel\":\"full\"},{\"value\":\":q\",\"matchLevel\":\"none\"}]},\"_highlightResult\":{\"editor\":{\"name\":{\"value\":\"<em>vim</em>\",\"matchLevel\":\"full\",\"fullyHighlighted\":true,\"matchedWords\":[\"vim\"]},\"type\":{\"value\":\"beforeneovim\",\"matchLevel\":\"none\",\"matchedWords\":[]}},\"names\":[{\"value\":\"<em>vim</em>\",\"matchLevel\":\"full\",\"fullyHighlighted\":true,\"matchedWords\":[\"vim\"]},{\"value\":\":q\",\"matchLevel\":\"none\",\"matchedWords\":[]}]}}],\"nbHits\":1,\"page\":0,\"nbPages\":1,\"hitsPerPage\":20,\"exhaustiveNbHits\":true,\"exhaustiveTypo\":true,\"exhaustive\":{\"nbHits\":true,\"typo\":true},\"query\":\"vim\",\"index\":\"cts_e2e_highlight_snippet_results\",\"renderingContent\":{}}]}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `search for a single facet request with minimal parameters8`() = runTest { client.runTest( call = { search( searchMethodParams = SearchMethodParams( requests = listOf( SearchForFacets( indexName = "cts_e2e_search_facet", type = SearchTypeFacet.entries.first { it.value == "facet" }, facet = "editor", ), ), strategy = SearchStrategy.entries.first { it.value == "stopIfEnoughMatches" }, ), ) }, response = { JSONAssert.assertEquals("{\"results\":[{\"exhaustiveFacetsCount\":true,\"facetHits\":[{\"count\":1,\"highlighted\":\"goland\",\"value\":\"goland\"},{\"count\":1,\"highlighted\":\"neovim\",\"value\":\"neovim\"},{\"count\":1,\"highlighted\":\"visual studio\",\"value\":\"visual studio\"},{\"count\":1,\"highlighted\":\"vscode\",\"value\":\"vscode\"}]}]}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `search filters end to end14`() = runTest { client.runTest( call = { search( searchMethodParams = SearchMethodParams( requests = listOf( SearchForHits( indexName = "cts_e2e_search_facet", filters = "editor:'visual studio' OR editor:neovim", ), SearchForHits( indexName = "cts_e2e_search_facet", facetFilters = FacetFilters.of(listOf(FacetFilters.of("editor:'visual studio'"), FacetFilters.of("editor:neovim"))), ), SearchForHits( indexName = "cts_e2e_search_facet", facetFilters = FacetFilters.of(listOf(FacetFilters.of("editor:'visual studio'"), FacetFilters.of(listOf(FacetFilters.of("editor:neovim"))))), ), SearchForHits( indexName = "cts_e2e_search_facet", facetFilters = FacetFilters.of(listOf(FacetFilters.of("editor:'visual studio'"), FacetFilters.of(listOf(FacetFilters.of("editor:neovim"), FacetFilters.of(listOf(FacetFilters.of("editor:goland"))))))), ), ), ), ) }, response = { JSONAssert.assertEquals("{\"results\":[{\"hitsPerPage\":20,\"index\":\"cts_e2e_search_facet\",\"nbHits\":2,\"nbPages\":1,\"page\":0,\"hits\":[{\"editor\":\"visual studio\",\"_highlightResult\":{\"editor\":{\"value\":\"visual studio\",\"matchLevel\":\"none\"}}},{\"editor\":\"neovim\",\"_highlightResult\":{\"editor\":{\"value\":\"neovim\",\"matchLevel\":\"none\"}}}],\"query\":\"\",\"params\":\"filters=editor%3A%27visual+studio%27+OR+editor%3Aneovim\"},{\"hitsPerPage\":20,\"index\":\"cts_e2e_search_facet\",\"nbHits\":0,\"nbPages\":0,\"page\":0,\"hits\":[],\"query\":\"\",\"params\":\"facetFilters=%5B%22editor%3A%27visual+studio%27%22%2C%22editor%3Aneovim%22%5D\"},{\"hitsPerPage\":20,\"index\":\"cts_e2e_search_facet\",\"nbHits\":0,\"nbPages\":0,\"page\":0,\"hits\":[],\"query\":\"\",\"params\":\"facetFilters=%5B%22editor%3A%27visual+studio%27%22%2C%5B%22editor%3Aneovim%22%5D%5D\"},{\"hitsPerPage\":20,\"index\":\"cts_e2e_search_facet\",\"nbHits\":0,\"nbPages\":0,\"page\":0,\"hits\":[],\"query\":\"\",\"params\":\"facetFilters=%5B%22editor%3A%27visual+studio%27%22%2C%5B%22editor%3Aneovim%22%2C%5B%22editor%3Agoland%22%5D%5D%5D\"}]}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `get searchDictionaryEntries results with minimal parameters`() = runTest { client.runTest( call = { searchDictionaryEntries( dictionaryName = DictionaryType.entries.first { it.value == "stopwords" }, searchDictionaryEntriesParams = SearchDictionaryEntriesParams( query = "about", ), ) }, response = { JSONAssert.assertEquals("{\"hits\":[{\"objectID\":\"86ef58032f47d976ca7130a896086783\",\"language\":\"en\",\"word\":\"about\"}],\"page\":0,\"nbHits\":1,\"nbPages\":1}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `searchRules`() = runTest { client.runTest( call = { searchRules( indexName = "cts_e2e_browse", searchRulesParams = SearchRulesParams( query = "zorro", ), ) }, response = { JSONAssert.assertEquals("{\"hits\":[{\"conditions\":[{\"alternatives\":true,\"anchoring\":\"contains\",\"pattern\":\"zorro\"}],\"consequence\":{\"params\":{\"ignorePlurals\":\"true\"},\"filterPromotes\":true,\"promote\":[{\"objectIDs\":[\"Æon Flux\"],\"position\":0}]},\"description\":\"test_rule\",\"enabled\":true,\"objectID\":\"qr-1725004648916\"}],\"nbHits\":1,\"nbPages\":1,\"page\":0}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `search with special characters in indexName1`() = runTest { client.runTest( call = { searchSingleIndex( indexName = "cts_e2e_space in index", ) }, ) } @Test fun `single search retrieve snippets3`() = runTest { client.runTest( call = { searchSingleIndex( indexName = "cts_e2e_browse", searchParams = SearchParamsObject( query = "batman mask of the phantasm", attributesToRetrieve = listOf("*"), attributesToSnippet = listOf("*:20"), ), ) }, response = { JSONAssert.assertEquals("{\"nbHits\":1,\"hits\":[{\"_snippetResult\":{\"genres\":[{\"value\":\"Animated\",\"matchLevel\":\"none\"},{\"value\":\"Superhero\",\"matchLevel\":\"none\"},{\"value\":\"Romance\",\"matchLevel\":\"none\"}],\"year\":{\"value\":\"1993\",\"matchLevel\":\"none\"}},\"_highlightResult\":{\"genres\":[{\"value\":\"Animated\",\"matchLevel\":\"none\",\"matchedWords\":[]},{\"value\":\"Superhero\",\"matchLevel\":\"none\",\"matchedWords\":[]},{\"value\":\"Romance\",\"matchLevel\":\"none\",\"matchedWords\":[]}],\"year\":{\"value\":\"1993\",\"matchLevel\":\"none\",\"matchedWords\":[]}}}]}", Json.encodeToString(it), JSONCompareMode.LENIENT) }, ) } @Test fun `setSettings with minimal parameters1`() = runTest { client.runTest( call = { setSettings( indexName = "cts_e2e_settings", indexSettings = IndexSettings( paginationLimitedTo = 10, ), forwardToReplicas = true, ) }, ) } }
31
PHP
14
36
ed203c6a76fc7c99bda79783f9ad6475dc60c431
11,885
api-clients-automation
MIT License
src/main/kotlin/io/mverse/kslack/api/methods/response/groups/GroupsArchiveResponse.kt
mverse
161,946,116
true
{"Kotlin": 403852}
package io.mverse.kslack.api.methods.response.groups import io.mverse.kslack.api.methods.SlackApiResponse data class GroupsArchiveResponse ( override val ok: Boolean = false, override val warning: String? = null, override val error: String? = null): SlackApiResponse
0
Kotlin
0
0
9ebf1dc13f6a3d89a03af11a83074a4d636cb071
281
jslack
MIT License
app/src/main/java/uk/nhs/nhsx/covid19/android/app/testordering/SubmitFakeExposureWindows.kt
nhsx-mirror
289,296,773
true
{"Kotlin": 2761696, "Shell": 1098, "Ruby": 847, "Batchfile": 197}
package uk.nhs.nhsx.covid19.android.app.testordering import uk.nhs.nhsx.covid19.android.app.common.SubmitEmptyData import uk.nhs.nhsx.covid19.android.app.remote.data.EmptySubmissionSource import javax.inject.Inject class SubmitFakeExposureWindows @Inject constructor( private val submitEmptyData: SubmitEmptyData, private val getEmptyExposureWindowSubmissionCount: GetEmptyExposureWindowSubmissionCount ) { operator fun invoke(emptySubmissionSource: EmptySubmissionSource, numberOfExposureWindowsSent: Int = 0) { submitEmptyData(emptySubmissionSource, getEmptyExposureWindowSubmissionCount(numberOfExposureWindowsSent)) } }
0
Kotlin
0
0
296c9decde1b5ed904b760ff77b05afc51f24281
650
covid-19-app-android-ag-public
MIT License
app/src/main/java/com/oneparchy/simplecontacts/models/Contact.kt
oneparchy
472,120,650
false
{"Kotlin": 20299}
package com.oneparchy.simplecontacts.models data class Contact( val name: String = "", val phone1: String = "", val phone2: String = "", val email: String = "", val address: String = "", val gender: String = "" )
0
Kotlin
0
0
4082c16cc63e0e2dca2bf8629a7a9a0151d5fffe
238
Simplecontacts
Apache License 2.0
app/src/main/java/com/llcvmlr/weatherappchallenge/network/di/WeatherDispatchers.kt
jsvallon
857,868,407
false
{"Kotlin": 105211}
package com.llcvmlr.weatherappchallenge.network.di import javax.inject.Qualifier /** * A Dagger [Qualifier] annotation used to distinguish between different [CoroutineDispatcher] instances. * * This annotation is used to specify which [CoroutineDispatcher] should be injected when * multiple dispatchers are available. It helps in providing the correct dispatcher instance * based on the context in which it is used. * * @param weatherDispatchers The [WeatherDispatchers] value that identifies the specific dispatcher. */ @Qualifier @Retention(AnnotationRetention.RUNTIME) annotation class Dispatcher(val weatherDispatchers: WeatherDispatchers) /** * Enum class representing different types of [CoroutineDispatcher] used in the application. * * This enum defines various dispatcher types that are used for different kinds of tasks, * such as I/O operations or general-purpose tasks. */ enum class WeatherDispatchers { /** * The default dispatcher used for CPU-bound tasks and general-purpose operations. */ Default, /** * The I/O dispatcher used for I/O-bound tasks such as network and file operations. */ IO, }
0
Kotlin
0
0
0cd2c2c3ba6b1f62d86cbcf08f385f1c3960dd7b
1,166
WeatherApp
MIT License
web/server/src/main/kotlin/support/bymason/kiosk/checkin/utils/Auth.kt
MasonAmerica
221,848,067
false
null
package support.bymason.kiosk.checkin.utils import firebase.firestore.SetOptions import firebase.functions.admin import firebase.functions.functions import google.OAuth2Client import google.google import kotlinx.coroutines.async import kotlinx.coroutines.await import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import superagent.superagent import kotlin.js.Json import kotlin.js.json fun buildGoogleAuthClient(): OAuth2Client = createInstance( google.asDynamic().auth.OAuth2, functions.config().gsuite.client_id, functions.config().gsuite.client_secret, "https://mason-check-in-kiosk.firebaseapp.com/redirect/gsuite/auth" ) suspend fun getAndInitCreds( uid: String, vararg integrations: String ): Map<String, Json> = coroutineScope { val creds = integrations.map { integration -> async { integration to admin.firestore() .collection(uid) .doc("config") .collection("credentials") .doc(integration) .get() .await() } }.awaitAll() creds.associate { (integration, creds) -> integration to creds.data() } } fun installGoogleAuth(creds: Json): GoogleAuthState { val client = buildGoogleAuthClient().apply { credentials = creds.asDynamic() } google.options(json("auth" to client)) return GoogleAuthState(client.credentials.access_token, client) } fun maybeRefreshGsuiteCreds(uid: String, state: GoogleAuthState) { if (state.prevToken == state.client.credentials.access_token) return console.log("Soft refreshing gsuite token") admin.firestore() .collection(uid) .doc("config") .collection("credentials") .doc("gsuite") .set(state.client.credentials.asDynamic(), SetOptions.merge) } suspend fun refreshDocusignCreds(uid: String, creds: Json): Json { console.log("Soft refreshing docusign token") val credsResult = superagent.post("https://account-d.docusign.com/oauth/token") .set(json("Authorization" to "Basic ${functions.config().docusign.client_hash}")) .query(json( "grant_type" to "refresh_token", "refresh_token" to creds["refresh_token"] )).await().body admin.firestore() .collection(uid) .doc("config") .collection("credentials") .doc("docusign") .set(credsResult, SetOptions.merge) return credsResult } data class GoogleAuthState(val prevToken: String?, val client: OAuth2Client)
2
Kotlin
1
0
4397e2f2cdf93f8b4caea95277492a94ad4f4861
2,688
mason-check-in-kiosk
Apache License 2.0
app/src/main/java/com/linecy/copy/ui/widget/VideoPlayerListener.kt
linecyc
112,428,472
false
null
package com.linecy.copy.ui.widget import tv.danmaku.ijk.media.player.IMediaPlayer import tv.danmaku.ijk.media.player.IMediaPlayer.OnTimedTextListener /** * @author by linecy */ abstract class VideoPlayerListener : IMediaPlayer.OnBufferingUpdateListener, IMediaPlayer.OnCompletionListener, IMediaPlayer.OnPreparedListener, IMediaPlayer.OnInfoListener, IMediaPlayer.OnVideoSizeChangedListener, IMediaPlayer.OnErrorListener, IMediaPlayer.OnSeekCompleteListener, OnTimedTextListener
0
Kotlin
2
1
c3fd0e3b14a2502ea619a93b7e96d65f79070c1c
495
Eyepetizer_Kotlin
Apache License 2.0
src/utils/JiraAuthenticationCookieGetter.kt
bucketplace
230,986,355
false
null
package utils import okhttp3.Headers import okhttp3.OkHttpClient import okhttp3.Response import org.koin.core.KoinComponent import secrets.JiraSecrets object JiraAuthenticationCookieGetter { private const val LOGIN_URL = "${JiraSecrets.DOMAIN}/rest/auth/1/session" suspend fun get(): String { return getCookie(getLoginResponseHeaders()) } private suspend fun getLoginResponseHeaders(): Headers { return ApiRequester.request<Response>("POST", LOGIN_URL, jsonBody = JiraSecrets.LOGIN_POST_BODY).headers() } private fun getCookie(headers: Headers): String { return headers.toMultimap().entries .first { it.key.toLowerCase() == "set-cookie" }.value .joinToString("; ") } }
0
Kotlin
0
0
58e2270ed92bf19fe196613b67172aaf12442368
750
error-report-v2
Apache License 2.0
diskordin-base/src/main/kotlin/org/tesserakt/diskordin/impl/gateway/interceptor/HeartbeatACKInterceptor.kt
ITesserakt
218,969,129
false
null
package org.tesserakt.diskordin.impl.gateway.interceptor import kotlinx.datetime.Clock import mu.KotlinLogging import org.tesserakt.diskordin.core.data.event.lifecycle.HeartbeatACKEvent import org.tesserakt.diskordin.gateway.interceptor.EventInterceptor import kotlin.time.ExperimentalTime class HeartbeatACKInterceptor : EventInterceptor() { @ExperimentalTime override suspend fun Context.heartbeatACK(event: HeartbeatACKEvent) { val logger = KotlinLogging.logger("[Shard #${shard.shardData.index}]") shard._heartbeatACKs.value = Clock.System.now() logger.debug("Received heartbeat ACK after ${shard.ping()}") } }
1
Kotlin
1
12
e93964fcb5ecb0e1d03dd0fc7d3dd2637a0e08ae
653
diskordin
Apache License 2.0
app/src/main/java/com/franzliszt/magicmusic/route/searchresult/album/SearchResultAlbumPage.kt
FranzLiszt-1847
753,088,527
false
{"Kotlin": 879960, "Java": 1923}
package com.franzliszt.magicmusic.route.searchresult.album import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.paging.LoadState import androidx.paging.compose.LazyPagingItems import androidx.paging.compose.collectAsLazyPagingItems import androidx.paging.compose.items import androidx.paging.compose.itemsIndexed import com.franzliszt.magicmusic.R import com.franzliszt.magicmusic.bean.recommend.songs.DailySong import com.franzliszt.magicmusic.route.searchresult.SearchResultItem import com.franzliszt.magicmusic.tool.Loading import com.franzliszt.magicmusic.tool.LoadingFailed import com.franzliszt.magicmusic.ui.theme.MagicMusicTheme @Composable fun SearchResultAlbumList( keyword:String, viewModel: SearchResultAlbumViewModel = hiltViewModel(), onAlbum:(Long)->Unit ){ val albums = viewModel.getSearchAlbumResult(keyword).collectAsLazyPagingItems() LazyColumn( modifier = Modifier .fillMaxWidth() .heightIn(max = LocalConfiguration.current.screenHeightDp.dp) .background(MagicMusicTheme.colors.background), verticalArrangement = Arrangement.spacedBy(10.dp) ){ when(albums.loadState.refresh){ is LoadState.Loading-> { item { Loading() } } is LoadState.Error-> { item { LoadingFailed{ albums.retry() } } } else ->{} } items(items = albums){album-> if (album != null) { SearchResultItem( cover = album.blurPicUrl, nickname = album.name, author = album.artist.name, onClick = { onAlbum(album.id) } ) } } when(albums.loadState.append){ is LoadState.Loading-> { item { Loading() } } else ->{} } } }
0
Kotlin
1
1
dcbc4c0cb9c0478e617423812712659df52a3b7d
2,318
MagicPlayer
Apache License 2.0
features/core/language/impl/src/main/java/com/ruslan/hlushan/core/language/impl/dto/LanguageDTO.kt
game-x50
361,364,864
false
null
package com.ruslan.hlushan.core.language.impl.dto import com.ruslan.hlushan.core.language.api.Language import com.ruslan.hlushan.core.language.code.LangFullCode import com.ruslan.hlushan.core.language.code.LangNonFullCode import com.ruslan.hlushan.core.language.code.stringValue import com.ruslan.hlushan.core.manager.api.ResourceManager import kotlinx.serialization.Serializable @Serializable internal data class LanguageDTO( val code: String, val countryCode: String, val defaultName: String, val image: String?, val alphabet: String ) internal fun mapLanguage(baseLangDTO: LanguageDTO, resourceManager: ResourceManager): Language? { val nonFullCode = LangNonFullCode.createFrom(baseLangDTO.code) return if (nonFullCode != null) { val code = LangFullCode(nonFullCode = nonFullCode, countryCode = baseLangDTO.countryCode) val localizedName = resourceManager.getStringResourceByName(code.stringValue) val name = if (localizedName.isBlank()) { localizedName } else { baseLangDTO.defaultName } Language( code = code, name = name, imageUrl = baseLangDTO.image, alphabet = baseLangDTO.alphabet ) } else { null } }
22
Kotlin
0
0
159a035109fab5cf777dd7a60f142a89f441df63
1,323
android_client_app
Apache License 2.0
common/build/generated/sources/schemaCode/kotlin/main/io/portone/sdk/server/schemas/UnauthorizedException.kt
portone-io
809,427,199
false
{"Kotlin": 385115, "Java": 331}
package io.portone.sdk.server.schemas import java.lang.Exception import kotlin.String /** * 인증 정보가 올바르지 않은 경우 */ public class UnauthorizedException( message: String? = null, ) : Exception(message)
0
Kotlin
0
2
f984c4cc31aa64aad5cd0fa0497bdd490a0fe33a
203
server-sdk-jvm
MIT License
backend/src/commonMain/kotlin/dev/drzepka/wikilinks/app/db/infrastructure/DatabaseProvider.kt
drzpk
513,034,741
false
null
package dev.drzepka.wikilinks.app.db.infrastructure import com.squareup.sqldelight.db.SqlCursor import com.squareup.sqldelight.db.SqlDriver import com.squareup.sqldelight.db.use import dev.drzepka.wikilinks.app.utils.Environment import dev.drzepka.wikilinks.app.utils.environment import dev.drzepka.wikilinks.common.config.CommonConfiguration import dev.drzepka.wikilinks.common.model.database.DatabaseFile import dev.drzepka.wikilinks.common.model.database.DatabaseType import dev.drzepka.wikilinks.common.utils.MultiplatformDirectory import dev.drzepka.wikilinks.db.cache.CacheDatabase import dev.drzepka.wikilinks.db.history.HistoryDatabase import dev.drzepka.wikilinks.db.links.LinksDatabase import mu.KotlinLogging @Suppress("MemberVisibilityCanBePrivate") class DatabaseProvider { private val log = KotlinLogging.logger {} fun getOrCreateUnprotectedLinksDatabase(file: DatabaseFile, directory: String): LinksDatabase { file.verifyType(DatabaseType.LINKS) val driver = getDbDriver(file.fileName, true, directory) LinksDatabase.Schema.createOrMigrateIfNecessary(driver, "links", LINKS_DATABASE_VERSION) return LinksDatabase.invoke(driver) } fun getLinksDatabase(file: DatabaseFile): ManagedDatabase<LinksDatabase> { file.verifyType(DatabaseType.LINKS) val driver = getDbDriver(file.fileName, false, null) val database = LinksDatabase.invoke(driver) return ManagedDatabase(database, driver, file) } fun getOrCreateCacheDatabase(file: DatabaseFile): ManagedDatabase<CacheDatabase> { file.verifyType(DatabaseType.CACHE) val driver = getDbDriver(file.fileName, false) CacheDatabase.Schema.createOrMigrateIfNecessary(driver, "cache", CACHE_DATABASE_VERSION) val database = CacheDatabase.invoke(driver) return ManagedDatabase(database, driver, file) } fun getOrCreateHistoryDatabase(file: DatabaseFile): ManagedDatabase<HistoryDatabase> { file.verifyType(DatabaseType.HISTORY) val driver = getDbDriver(file.fileName, false) HistoryDatabase.Schema.createOrMigrateIfNecessary(driver, "history", HISTORY_DATABASE_VERSION) val database = HistoryDatabase.invoke(driver) return ManagedDatabase(database, driver, file) } private fun DatabaseFile.verifyType(expected: DatabaseType) { if (type != expected) throw IllegalStateException("Expected DatabaseFile with type $expected, but got $type instead") } private fun getDbDriver(dbName: String, disableProtection: Boolean, overrideDirectory: String? = null): SqlDriver { val driver = doGetDbDriver(dbName, disableProtection, overrideDirectory) return CloseableDriver(driver) } private fun doGetDbDriver( dbName: String, disableProtection: Boolean, overrideDirectory: String? = null ): SqlDriver { val dir = overrideDirectory ?: CommonConfiguration.databasesDirectory MultiplatformDirectory(dir).mkdirs() val driver = getDriver(dir, dbName) // Optimize insert speed // https://www.sqlite.org/pragma.html val journalMode = if (disableProtection) "OFF" else "DELETE" val synchronous = if (disableProtection) "OFF" else "FULL" driver.exec("PRAGMA journal_mode = $journalMode") driver.exec("PRAGMA synchronous = $synchronous") return driver } private fun SqlDriver.Schema.createOrMigrateIfNecessary(driver: SqlDriver, name: String, currentVersion: Int) { val schemaVersion = driver.getVersion() if (schemaVersion == 0) { log.info { "Creating schema $name" } create(driver) driver.setVersion(0, currentVersion) } else if (schemaVersion < currentVersion) { log.info { "Migrating schema $name from $schemaVersion to $currentVersion" } migrate(driver, schemaVersion, currentVersion) driver.setVersion(schemaVersion, currentVersion) } } private fun SqlDriver.exec(sql: String) { // The SQLite library on Linux doesn't support 'execute' statements. if (environment == Environment.LINUX) executeQuery(null, sql, 0) else execute(null, sql, 0) } private fun SqlDriver.getVersion(): Int { // Sqlite also supports PRAGMA user_version, but for some reason it doesn't work on native driver. val tableExists = executeQuery("SELECT name from sqlite_master WHERE type = 'table' and name = 'Version'") .use { it.next() && it.getString(0) != null } if (!tableExists) return 0 return executeQuery("SELECT version FROM Version").use { it.next(); it.getLong(0) }!!.toInt() } private fun SqlDriver.setVersion(oldVersion: Int, newVersion: Int) { if (oldVersion == 0) { execute(null, "CREATE TABLE Version (version INTEGER NOT NULL);", 0) execute(null, "INSERT INTO Version VALUES ($newVersion);", 0) } else { execute(null, "UPDATE Version SET version = $newVersion;", 0) } } private fun SqlDriver.executeQuery(sql: String): SqlCursor = executeQuery(null, sql, 0) companion object { private const val LINKS_DATABASE_VERSION = 1 private const val CACHE_DATABASE_VERSION = 1 private const val HISTORY_DATABASE_VERSION = 3 } } internal expect fun getDriver(basePath: String?, databaseName: String): SqlDriver
0
Kotlin
0
1
ab55472076b04ff6cca0b8ae4777f074d6f7be73
5,528
wikilinks
Apache License 2.0
zircon.jvm/src/test/kotlin/org/codetome/zircon/internal/graphics/DefaultStyleSetTest.kt
mdr0id
142,499,841
true
{"Kotlin": 772586, "Java": 70338}
package org.codetome.zircon.internal.graphics import org.assertj.core.api.Assertions.assertThat import org.codetome.zircon.api.color.ANSITextColor import org.codetome.zircon.api.color.TextColor import org.codetome.zircon.api.builder.graphics.StyleSetBuilder import org.codetome.zircon.api.interop.Modifiers import org.codetome.zircon.api.modifier.BorderBuilder import org.codetome.zircon.api.modifier.BorderPosition import org.codetome.zircon.api.modifier.SimpleModifiers.* import org.junit.Test class DefaultStyleSetTest { @Test fun shouldBuildProperCacheKey() { val result = StyleSetBuilder.newBuilder() .backgroundColor(ANSITextColor.WHITE) .foregroundColor(TextColor.fromString("#aabbcc")) .modifiers(Modifiers.crossedOut(), BorderBuilder.newBuilder().borderPositions(BorderPosition.TOP).build()) .build().generateCacheKey() assertThat(result).isEqualTo("170187204255WHITEBorderSOLIDTOP-CrossedOut") } @Test fun shouldAddModifiersProperly() { val styleSet = StyleSetBuilder.defaultStyle().withAddedModifiers(Bold) val result = styleSet.withAddedModifiers(Italic) assertThat(StyleSetBuilder.defaultStyle().getModifiers()).isEmpty() assertThat(styleSet.getModifiers()).containsExactlyInAnyOrder(Bold) assertThat(result.getModifiers()).containsExactlyInAnyOrder(Bold, Italic) } @Test fun shouldRemoveModifiersProperly() { val styleSet = StyleSetBuilder.defaultStyle().withAddedModifiers(Bold, Italic) val result = styleSet.withRemovedModifiers(Italic) assertThat(StyleSetBuilder.defaultStyle().getModifiers()).isEmpty() assertThat(styleSet.getModifiers()).containsExactlyInAnyOrder(Bold, Italic) assertThat(result.getModifiers()).containsExactlyInAnyOrder(Bold) } @Test fun shouldSetModifiersProperly() { val styleSet = StyleSetBuilder.defaultStyle().withAddedModifiers(Bold, Italic) val result = styleSet.withModifiers(Italic, CrossedOut) assertThat(StyleSetBuilder.defaultStyle().getModifiers()).isEmpty() assertThat(styleSet.getModifiers()).containsExactlyInAnyOrder(Bold, Italic) assertThat(result.getModifiers()).containsExactlyInAnyOrder(CrossedOut, Italic) } @Test fun shouldNotHaveModifiersByDefault() { assertThat(StyleSetBuilder.defaultStyle().getModifiers()).isEmpty() } @Test fun shouldGenerateEqualDefaults() { assertThat(StyleSetBuilder.defaultStyle()).isEqualTo(StyleSetBuilder.defaultStyle()) } }
0
Kotlin
0
0
58cade5b8ecb2663d6880d3220db70f6e7bb6f91
2,617
zircon
MIT License
webui/src/main/kotlin/world/phantasmal/webui/TimeExtensions.kt
DaanVandenBosch
189,066,992
false
null
package world.phantasmal.webui import kotlin.time.Duration fun Duration.formatAsHoursAndMinutes(): String = toComponents { hours, minutes, _, _ -> "${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}" }
1
Kotlin
5
20
423c3e252b2be6de63a03108915861fced90aaa6
245
phantasmal-world
MIT License
philarios-core/src/main/kotlin/io/philarios/core/Context.kt
taxpon
180,252,847
true
{"Kotlin": 666395, "Ruby": 7769, "Shell": 1002, "HTML": 398}
package io.philarios.core import io.philarios.util.registry.Registry import io.philarios.util.registry.emptyRegistry interface Context<out C> { val value: C } fun emptyContext(): Context<Any?> = ValueContext(null) fun <C> contextOf(value: C): Context<C> = ValueContext(value) internal class ValueContext<out C>(override val value: C) : Context<C> suspend fun <C, T : Any> Context<C>.map( scaffolder: Scaffolder<C, T>, registry: Registry = emptyRegistry() ): Context<T> { return contextOf(value.let { scaffolder .createScaffold(it) .resolve(registry) }) } inline fun <C, T> Context<C>.map(transform: (C) -> T): Context<T> { return contextOf(value.let(transform)) } fun <T> Context<T>.unwrap(): T { return value }
0
Kotlin
0
0
ea311f14fe3e62ea5f2b76f13bafe76ac5dfe073
796
philarios
MIT License
.teamcity/delivery/HubProject.kts
JetBrains
261,739,564
false
{"C#": 191431, "Dockerfile": 179109, "Kotlin": 50785, "Batchfile": 18825, "Shell": 13946, "Python": 6106, "PowerShell": 4921}
package delivery import delivery.arm.PushProductionLinux2004_Aarch64 import delivery.production.PushHubLinux import delivery.production.PushHubWindows import delivery.production.manifest.PublishHubVersion import jetbrains.buildServer.configs.kotlin.v2019_2.Project object HubProject : Project({ name = "TeamCity Docker Images Deployment into Production Registry" description = "Configurations designed the promotion of TeamCity Docker Images from staging to production registry." buildType(PushHubLinux.push_hub_linux) buildType(PushHubWindows.push_hub_windows) buildType(PublishHubVersion.publish_hub_version) buildType(PushProductionLinux2004_Aarch64.push_production_linux_2004_aarch64) })
9
C#
59
91
16ea3a7aa8e4d17050bde5a7932246fb337c0090
718
teamcity-docker-images
Apache License 2.0
legacy/src/test/kotlin/uk/co/baconi/oauth/api/client/ClientPrincipalTest.kt
beercan1989
345,334,044
false
null
package uk.co.baconi.oauth.api.client import io.kotest.assertions.assertSoftly import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import io.kotest.matchers.throwable.shouldHaveMessage import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import uk.co.baconi.oauth.api.client.ClientId.ConsumerY import uk.co.baconi.oauth.api.client.ClientId.ConsumerZ import uk.co.baconi.oauth.api.client.ClientType.Confidential import uk.co.baconi.oauth.api.client.ClientType.Public class ClientPrincipalTest { @Nested inner class ConfidentialClientTest { @Test fun `should construct for a confidential client`() { val client = ConfidentialClient(mockk { every { id } returns ConsumerZ every { type } returns Confidential }) assertSoftly(client) { id shouldBe ConsumerZ configuration.type shouldBe Confidential } } @Test fun `throw exception if the configuration is not for a confidential client`() { val exception = shouldThrow<IllegalArgumentException> { ConfidentialClient(mockk { every { id } returns ConsumerY every { type } returns Public }) } exception shouldHaveMessage "type cannot be [Public]" } } @Nested inner class PublicClientTest { @Test fun `should construct for a public client`() { val client = PublicClient(mockk { every { id } returns ConsumerY every { type } returns Public }) assertSoftly(client) { id shouldBe ConsumerY configuration.type shouldBe Public } } @Test fun `throw exception if the configuration is not for a public client`() { val exception = shouldThrow<IllegalArgumentException> { PublicClient(mockk { every { id } returns ConsumerZ every { type } returns Confidential }) } exception shouldHaveMessage "type cannot be [Confidential]" } } }
0
Kotlin
0
0
90828b324ecc03501d7997b1e53524bc2d537f95
2,330
oauth-api
Apache License 2.0
app/src/main/java/com/developerspace/webrtcsample/BackgroundService.kt
pathakashish
414,473,036
false
null
package com.developerspace.webrtcsample import android.R import android.app.* import android.app.NotificationManager import android.content.Intent import android.graphics.Color import android.os.Build import android.os.IBinder import android.util.Log import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat class BackgroundService : Service() { private val TAG_FOREGROUND_SERVICE = "FOREGROUND_SERVICE" companion object { val ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE" val ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE" } override fun onBind(intent: Intent?): IBinder? { // TODO: Return the communication channel to the service. throw UnsupportedOperationException("Not yet implemented") } override fun onCreate() { super.onCreate() Log.d(TAG_FOREGROUND_SERVICE, "My foreground service onCreate().") } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent != null) { val action = intent.action if (action != null) when (action) { ACTION_START_FOREGROUND_SERVICE -> { startForegroundService() Toast.makeText( applicationContext, "Foreground service is started.", Toast.LENGTH_LONG ).show() } ACTION_STOP_FOREGROUND_SERVICE -> { stopForegroundService() Toast.makeText( applicationContext, "Foreground service is stopped.", Toast.LENGTH_LONG ).show() } } } return super.onStartCommand(intent, flags, startId) } /* Used to build and start foreground service. */ private fun startForegroundService() { Log.d(TAG_FOREGROUND_SERVICE, "Start foreground service.") if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createNotificationChannel("my_service", "My Background Service") } else return } @RequiresApi(Build.VERSION_CODES.O) private fun createNotificationChannel(channelId: String, channelName: String) { val resultIntent = Intent(this, MainActivity::class.java) // Create the TaskStackBuilder and add the intent, which inflates the back stack val stackBuilder: TaskStackBuilder = TaskStackBuilder.create(this) stackBuilder.addNextIntentWithParentStack(resultIntent) val resultPendingIntent: PendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT) val chan = NotificationChannel(channelId, channelName, android.app.NotificationManager.IMPORTANCE_DEFAULT) chan.lightColor = Color.BLUE chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE val manager = (getSystemService(NOTIFICATION_SERVICE) as android.app.NotificationManager) manager.createNotificationChannel(chan) val notificationBuilder = NotificationCompat.Builder(this, channelId) val notification = notificationBuilder.setOngoing(true) .setSmallIcon(R.drawable.ic_delete) .setContentTitle("Screen is being shared") .setPriority(NotificationManager.IMPORTANCE_MIN) .setCategory(Notification.CATEGORY_SERVICE) .setContentIntent(resultPendingIntent) //intent .build() val notificationManager = NotificationManagerCompat.from(this) notificationManager.notify(1, notificationBuilder.build()) startForeground(1, notification) } private fun stopForegroundService() { Log.d(TAG_FOREGROUND_SERVICE, "Stop foreground service.") // Stop foreground service and remove the notification. stopForeground(true) // Stop the foreground service. stopSelf() } }
0
Kotlin
0
0
a9856bd3d9fbe44f613b24d2099f6f3fe71e2aea
4,146
WebRTCNativeAndroid
MIT License
docs/code/example/example-customising-output-01.kt
adamko-dev
465,838,213
false
{"Kotlin": 70444}
// This file was automatically generated from customising-output.md by Knit tool. Do not edit. @file:Suppress("PackageDirectoryMismatch", "unused") package dev.adamko.kxstsgen.example.exampleCustomisingOutput01 import kotlinx.serialization.* import dev.adamko.kxstsgen.* import kotlinx.serialization.builtins.serializer import dev.adamko.kxstsgen.core.* @Serializable data class Item( val price: Double, val count: Int, ) fun main() { val tsGenerator = KxsTsGenerator() tsGenerator.descriptorOverrides += Double.serializer().descriptor to TsDeclaration.TsTypeAlias( id = TsElementId("Double"), typeRef = TsTypeRef.Declaration( id = TsElementId("double"), parent = null, nullable = false, ) ) println(tsGenerator.generate(Item.serializer())) }
11
Kotlin
5
56
9a0866cd6e64456bff0c35ded462e91f1b144150
809
kotlinx-serialization-typescript-generator
Apache License 2.0
app/app/src/main/java/com/example/tanimals/weatherPicker.kt
JiggleWigglesnicker
224,185,127
false
null
package com.example.tanimals import android.os.Bundle import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class weatherPicker : AppCompatActivity() { private var weatherData: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_weather_picker) } }
3
Kotlin
0
0
10886046276fb90d11feb3a125f591e65bb5a639
392
Tanimals
MIT License
kadamy_delivery_user_android/app/src/main/java/com/kadamy/customer/activity/ChangePasswordActivity.kt
yefsoft09
784,271,487
false
{"Kotlin": 885209, "PHP": 634806, "Blade": 602183, "JavaScript": 56504, "Java": 955}
package com.kadamy.customer.activity import android.app.Activity import android.app.Dialog import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.view.LayoutInflater import android.view.View import android.view.Window import android.view.WindowManager import android.widget.TextView import androidx.lifecycle.lifecycleScope import com.kadamy.customer.R import com.kadamy.customer.api.ApiClient import com.kadamy.customer.api.SingleResponsee import com.kadamy.customer.base.BaseActivity import com.kadamy.customer.databinding.ActivityChangepasswordBinding import com.kadamy.customer.remote.NetworkResponse import com.kadamy.customer.utils.Common import com.kadamy.customer.utils.Common.alertErrorOrValidationDialog import com.kadamy.customer.utils.Common.dismissLoadingProgress import com.kadamy.customer.utils.Common.isCheckNetwork import com.kadamy.customer.utils.Constants import com.kadamy.customer.utils.SharePreference import kotlinx.coroutines.launch class ChangePasswordActivity : BaseActivity() { private lateinit var binding: ActivityChangepasswordBinding override fun setLayout(): View = binding.root override fun InitView() { binding = ActivityChangepasswordBinding.inflate(layoutInflater) Common.getCurrentLanguage(this@ChangePasswordActivity, false) if (SharePreference.getStringPref( this@ChangePasswordActivity, SharePreference.SELECTED_LANGUAGE ).equals(resources.getString(R.string.language_hindi)) ) { binding.ivBack.rotation = 180F } else { binding.ivBack.rotation = 0F } } fun onClick(v: View?) { when (v!!.id) { R.id.ivBack -> { finish() } R.id.tvSubmit -> { if(ApiClient.System_environment==Constants.SendBox) { Common.showErrorFullMsg(this@ChangePasswordActivity, resources.getString(R.string.send_box_error_alert)) }else { if (binding.edOldPass.text.toString() == "") { Common.showErrorFullMsg( this@ChangePasswordActivity, resources.getString(R.string.validation_all) ) } else if (binding.edNewPassword.text.toString() == "") { Common.showErrorFullMsg( this@ChangePasswordActivity, resources.getString(R.string.validation_all) ) } else if (binding.edConfirmPassword.text.toString() == "") { Common.showErrorFullMsg( this@ChangePasswordActivity, resources.getString(R.string.validation_all) ) } else if (binding.edConfirmPassword.text.toString() != binding.edNewPassword.text.toString()) { Common.showErrorFullMsg( this@ChangePasswordActivity, resources.getString(R.string.validation_valid_cpassword) ) } else { if (SharePreference.getBooleanPref( this@ChangePasswordActivity, SharePreference.isLogin ) ) { val hasmap = HashMap<String, String>() hasmap["user_id"] = SharePreference.getStringPref( this@ChangePasswordActivity, SharePreference.userId )!! hasmap["old_password"] = binding.edOldPass.text.toString() hasmap["new_password"] = binding.edNewPassword.text.toString() if (isCheckNetwork(this@ChangePasswordActivity)) { callApiChangePassword(hasmap) } else { alertErrorOrValidationDialog( this@ChangePasswordActivity, resources.getString(R.string.no_internet) ) } } else { openActivity(LoginActivity::class.java) finish() finishAffinity() } } } } } } private fun callApiChangePassword(hasmap: HashMap<String, String>) { Common.showLoadingProgress(this@ChangePasswordActivity) lifecycleScope.launch { when (val response = ApiClient.getClient().setChangePassword(hasmap)) { is NetworkResponse.Success -> { val restResponse: SingleResponsee = response.body if (restResponse.status == 1) { dismissLoadingProgress() successfulDialog( this@ChangePasswordActivity, restResponse.message.toString() ) } } is NetworkResponse.ApiError -> { Common.dismissLoadingProgress() Common.showErrorFullMsg( this@ChangePasswordActivity, response.body.message.toString().replace("\\n", System.lineSeparator()) ) } is NetworkResponse.NetworkError -> { Common.dismissLoadingProgress() Common.showErrorFullMsg( this@ChangePasswordActivity, resources.getString(R.string.no_internet) ) } is NetworkResponse.UnknownError -> { Common.dismissLoadingProgress() Common.showErrorFullMsg( this@ChangePasswordActivity, resources.getString(R.string.error_msg) ) } } } } fun successfulDialog(act: Activity, msg: String?) { var dialog: Dialog? = null try { dialog?.dismiss() dialog = Dialog(act, R.style.AppCompatAlertDialogStyleBig) dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog.window!!.setLayout( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT ) dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog.setCancelable(false) val mInflater = LayoutInflater.from(act) val mView = mInflater.inflate(R.layout.dlg_validation, null, false) val textDesc: TextView = mView.findViewById(R.id.tvMessage) textDesc.text = msg val tvOk: TextView = mView.findViewById(R.id.tvOk) val finalDialog: Dialog = dialog tvOk.setOnClickListener { finalDialog.dismiss() finish() } dialog.setContentView(mView) dialog.show() } catch (e: java.lang.Exception) { e.printStackTrace() } } override fun onResume() { super.onResume() Common.getCurrentLanguage(this@ChangePasswordActivity, false) } }
0
Kotlin
0
0
65c4e1217c87049a4cc2ac4d1fe92d0c3a467d6f
7,563
ProyectoProg1_AppDelivery
MIT License
EX4/Ex4/src/Main.kt
KaioPortella
765,941,497
false
{"Kotlin": 26837}
fun main() { // Criando um novo objeto Baralho val baralho = Baralho() // Embaralhando o baralho baralho.embaralhar() // Criando um novo objeto Jogador val jogador = Jogador() // Distribuindo 5 cartas do baralho para o jogador e armazenando as cartas recebidas val cartasRecebidas = baralho.distribuir(5) // O jogador recebe as cartas distribuídas jogador.receberCartas(cartasRecebidas) }
0
Kotlin
0
0
0728e1b2f3dbf328a6be92ae05f39db165f32bd8
428
programacao-mobile
MIT License
common/src/commonMain/kotlin/com/camackenzie/exvi/client/model/APIInfo.kt
CallumMackenzie
450,286,341
false
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.camackenzie.exvi.client.model import com.camackenzie.exvi.core.api.APIRequest import com.camackenzie.exvi.core.api.APIResult import com.camackenzie.exvi.core.api.BooleanResult import com.camackenzie.exvi.core.api.CompatibleVersionRequest import com.camackenzie.exvi.core.model.ExviSerializer import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers /** * * @author callum */ object APIInfo { private const val STAGE_NAME = "test" const val ROOT = "https://s36irvth41.execute-api.us-east-2.amazonaws.com/" private const val STAGE = ROOT + STAGE_NAME const val ENDPOINT = "$STAGE/data" fun checkAppCompatibility( appVersion: Int, coroutineScope: CoroutineScope = CoroutineScope(Dispatchers.Default), dispatcher: CoroutineDispatcher = Dispatchers.Default, onSuccess: () -> Unit = {}, onFail: (APIResult<String>) -> Unit = {}, onComplete: () -> Unit = {} ) = APIRequest.requestAsync( ENDPOINT, CompatibleVersionRequest(appVersion), APIRequest.jsonHeaders(), coroutineScope, dispatcher ) { if (it.failed()) onFail(it) else { val versionValid: BooleanResult = ExviSerializer.fromJson(it.body) if (versionValid.result) onSuccess() else onFail(it) } onComplete() } }
1
Kotlin
0
0
85c0bde76ab0bf4a8ee2a2ad0ea3bd249bc7422b
1,609
exvi-client
Apache License 2.0
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/areas/daemonheim/spawns_13881.plugin.kts
2011Scape
578,880,245
false
null
package gg.rsmod.plugins.content.areas.daemonheim spawn_npc(npc = Npcs.FREMENNIK_SHIPMASTER_9708, x = 3513, z = 3694, direction = Direction.WEST, static = true)
5
Kotlin
8
13
11ae0b9d6f49e6580119f6f7803a01edc6673a5a
161
tek5-game
Apache License 2.0
app/src/main/java/com/sev4ikwasd/rutschedule/data/datasource/local/dao/ScheduleDao.kt
sev4ikwasd
532,048,126
false
null
package com.sev4ikwasd.rutschedule.data.datasource.local.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query import androidx.room.Transaction import com.sev4ikwasd.rutschedule.data.entity.ClassEntity import com.sev4ikwasd.rutschedule.data.entity.ScheduleEntity import com.sev4ikwasd.rutschedule.data.entity.ScheduleWithClassesEntity @Dao interface ScheduleDao { @Transaction @Query("SELECT * FROM ScheduleEntity WHERE groupId=:groupId") fun getScheduleWithClasses(groupId: Int): ScheduleWithClassesEntity @Transaction fun changeScheduleWithClasses(scheduleWithClassesEntity: ScheduleWithClassesEntity) { deleteAll() insertScheduleWithClasses(scheduleWithClassesEntity) } @Transaction fun insertScheduleWithClasses(scheduleWithClassesEntity: ScheduleWithClassesEntity) { val scheduleId: Long = insertSchedule(scheduleWithClassesEntity.schedule) for (classEntity in scheduleWithClassesEntity.classes) { classEntity.scheduleId = scheduleId insertClass(classEntity) } } @Insert fun insertSchedule(scheduleEntity: ScheduleEntity): Long @Insert fun insertClass(classEntity: ClassEntity) @Query("DELETE FROM ScheduleEntity") fun deleteAll() }
0
Kotlin
0
0
dccabf0817a2b4a0ec90519a21afc6cb09002dac
1,299
rut-schedule
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/iotfleetwise/CfnDecoderManifestDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.iotfleetwise import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.String import kotlin.Unit import software.amazon.awscdk.services.iotfleetwise.CfnDecoderManifest import software.amazon.awscdk.services.iotfleetwise.CfnDecoderManifestProps import software.constructs.Construct @Generated public fun Construct.cfnDecoderManifest(id: String, props: CfnDecoderManifestProps): CfnDecoderManifest = CfnDecoderManifest(this, id, props) @Generated public fun Construct.cfnDecoderManifest( id: String, props: CfnDecoderManifestProps, initializer: @AwsCdkDsl CfnDecoderManifest.() -> Unit, ): CfnDecoderManifest = CfnDecoderManifest(this, id, props).apply(initializer) @Generated public fun Construct.buildCfnDecoderManifest(id: String, initializer: @AwsCdkDsl CfnDecoderManifest.Builder.() -> Unit): CfnDecoderManifest = CfnDecoderManifest.Builder.create(this, id).apply(initializer).build()
1
Kotlin
0
0
e9a0ff020b0db2b99e176059efdb124bf822d754
988
aws-cdk-kt
Apache License 2.0
feature/loginwithemailphone/src/main/java/com/puskal/loginwithemailphone/LoginWithEmailPhoneScreen.kt
puskal-khadka
622,175,439
false
null
package com.puskal.loginwithemailphone import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material3.* import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.puskal.composable.TopBar import com.puskal.loginwithemailphone.tabs.EmailUsernameTabScreen import com.puskal.loginwithemailphone.tabs.PhoneTabScreen import com.puskal.theme.Black import com.puskal.theme.R import com.puskal.theme.SeparatorColor import com.puskal.theme.SubTextColor import kotlinx.coroutines.launch /** * Created by <NAME> on 3/27/2023. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun LoginWithEmailPhoneScreen( navController: NavController, viewModel: LoginWithEmailPhoneViewModel = hiltViewModel() ) { Scaffold(topBar = { TopBar( title = stringResource(id = R.string.login_or_sign_up), actions = { Icon( painter = painterResource(id = R.drawable.ic_question_circle), contentDescription = null, modifier = Modifier.padding(end = 16.dp) ) } ) { navController.navigateUp() } }) { Column( modifier = Modifier .fillMaxSize() .padding(it) ) { LoginPager(viewModel) } } } @OptIn(ExperimentalFoundationApi::class) @Composable internal fun LoginPager(viewModel: LoginWithEmailPhoneViewModel) { val pagerState = rememberPagerState() val pages = LoginPages.values().asList() val coroutineScope = rememberCoroutineScope() LaunchedEffect(key1 = pagerState) { snapshotFlow { pagerState.settledPage }.collect { viewModel.onTriggerEvent(LoginEmailPhoneEvent.EventPageChange(it)) } } TabRow( selectedTabIndex = pagerState.currentPage, indicator = { val modifier = Modifier .tabIndicatorOffset(it[pagerState.currentPage]) .padding(horizontal = 26.dp) TabRowDefaults.Indicator(modifier, color = Black) }, divider = { Divider(thickness = 0.5.dp, color = SeparatorColor) }, ) { pages.forEachIndexed { index, item -> val isSelected = pagerState.currentPage == index Tab( selected = isSelected, onClick = { coroutineScope.launch { pagerState.animateScrollToPage(index) } }, selectedContentColor = Color.Black, unselectedContentColor = SubTextColor, text = { Text( text = stringResource(id = item.title), style = MaterialTheme.typography.bodySmall ) } ) } } HorizontalPager( modifier = Modifier.fillMaxSize(), state = pagerState, pageCount = pages.size, key = { it } ) { page -> when (page) { 0 -> PhoneTabScreen(viewModel) 1 -> EmailUsernameTabScreen(viewModel) } } }
0
Kotlin
3
26
e0e3c0f9fae50411b034346a720f276692119a90
3,944
TikTok-Compose
Apache License 2.0
app/src/main/java/com/zobaer53/zedmovies/di/DatabaseModule.kt
zobaer53
661,586,013
false
{"Kotlin": 498107, "JavaScript": 344099, "C++": 10825, "CMake": 2160}
package com.zobaer53.zedmovies.di import android.content.Context import androidx.room.Room import com.zobaer53.zedmovies.BuildConfig import com.zobaer53.zedmovies.data.database.zedMoviesDatabase import com.zobaer53.zedmovies.data.database.util.zedMoviesVersionProvider import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DatabaseModule { @Provides @Singleton fun providezedMoviesDatabase(@ApplicationContext context: Context) = Room.databaseBuilder( context, zedMoviesDatabase::class.java, zedMoviesDatabase.zedMovies_DATABASE ).build() @Provides fun providezedMoviesVersionProvider() = object : zedMoviesVersionProvider { override val version: String = BuildConfig.VERSION_NAME } @Provides fun provideMovieDao(database: zedMoviesDatabase) = database.movieDao @Provides fun provideTvShowDao(database: zedMoviesDatabase) = database.tvShowDao @Provides fun provideMovieRemoteKeyDao(database: zedMoviesDatabase) = database.movieRemoteKeyDao @Provides fun provideTvShowRemoteKeyDao(database: zedMoviesDatabase) = database.tvShowRemoteKeyDao @Provides fun provideMovieDetailsDao(database: zedMoviesDatabase) = database.movieDetailsDao @Provides fun provideTvShowDetailsDao(database: zedMoviesDatabase) = database.tvShowDetailsDao @Provides fun provideWishlistDao(database: zedMoviesDatabase) = database.wishlistDao }
0
Kotlin
3
6
1e70d46924b711942b573364745fa74ef1f8493f
1,650
NoFlix
Apache License 2.0
circle-menu/src/main/java/com/ramotion/circlemenu/CircleMenuView.kt
gohousr
188,952,559
true
{"Kotlin": 29091}
package com.ramotion.circlemenu import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet import android.animation.Keyframe import android.animation.ObjectAnimator import android.animation.PropertyValuesHolder import android.animation.ValueAnimator import android.content.Context import android.content.res.ColorStateList import android.content.res.TypedArray import android.graphics.Color import android.graphics.Rect import android.os.Build import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.view.animation.OvershootInterpolator import android.widget.FrameLayout import com.google.android.material.floatingactionbutton.FloatingActionButton import java.util.ArrayList import androidx.annotation.AttrRes import androidx.annotation.DrawableRes import androidx.core.view.ViewCompat /** * CircleMenuView */ class CircleMenuView : FrameLayout { private val mButtons = ArrayList<View>() private val mButtonRect = Rect() private var mMenuButton: FloatingActionButton? = null private var mRingView: RingEffectView? = null private var mClosedState = true private var mIsAnimating = false @get:DrawableRes var iconMenu: Int = 0 @get:DrawableRes var iconClose: Int = 0 /** * See [R.styleable.CircleMenuView_duration_ring] * @return current ring animation duration. */ /** * See [R.styleable.CircleMenuView_duration_ring] * @param duration ring animation duration in milliseconds. */ var durationRing: Int = 0 /** * See [R.styleable.CircleMenuView_long_click_duration_ring] * @return current long click ring animation duration. */ /** * See [R.styleable.CircleMenuView_long_click_duration_ring] * @param duration long click ring animation duration in milliseconds. */ var longClickDurationRing: Int = 0 /** * See [R.styleable.CircleMenuView_duration_open] * @return current open animation duration. */ /** * See [R.styleable.CircleMenuView_duration_open] * @param duration open animation duration in milliseconds. */ var durationOpen: Int = 0 /** * See [R.styleable.CircleMenuView_duration_close] * @return current close animation duration. */ /** * See [R.styleable.CircleMenuView_duration_close] * @param duration close animation duration in milliseconds. */ var durationClose: Int = 0 private var mDesiredSize: Int = 0 private var mRingRadius: Int = 0 private var mDistance: Float = 0.toFloat() /** * See [CircleMenuView.EventListener] * @return current event listener or null. */ /** * See [CircleMenuView.EventListener] * @param listener new event listener or null. */ var eventListener: EventListener? = null private val openMenuAnimation: Animator get() { val alphaAnimation = ObjectAnimator.ofFloat(mMenuButton!!, "alpha", DEFAULT_CLOSE_ICON_ALPHA) val kf0 = Keyframe.ofFloat(0f, 0f) val kf1 = Keyframe.ofFloat(0.5f, 60f) val kf2 = Keyframe.ofFloat(1f, 0f) val pvhRotation = PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2) val rotateAnimation = ObjectAnimator.ofPropertyValuesHolder(mMenuButton, pvhRotation) rotateAnimation.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { private var iconChanged = false override fun onAnimationUpdate(valueAnimator: ValueAnimator) { val fraction = valueAnimator.animatedFraction if (fraction >= 0.5f && !iconChanged) { iconChanged = true mMenuButton!!.setImageResource(iconClose) } } }) val centerX = mMenuButton!!.x val centerY = mMenuButton!!.y val buttonsCount = mButtons.size val angleStep = 360f / buttonsCount val buttonsAppear = ValueAnimator.ofFloat(0f, mDistance) buttonsAppear.interpolator = OvershootInterpolator() buttonsAppear.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { for (view in mButtons) { view.visibility = View.VISIBLE } } }) buttonsAppear.addUpdateListener { valueAnimator -> val fraction = valueAnimator.animatedFraction val value = valueAnimator.animatedValue as Float offsetAndScaleButtons(centerX, centerY, angleStep, value, fraction) } val result = AnimatorSet() result.playTogether(alphaAnimation, rotateAnimation, buttonsAppear) result.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { mIsAnimating = true } override fun onAnimationEnd(animation: Animator) { mIsAnimating = false } }) return result } private val closeMenuAnimation: Animator get() { val scaleX1 = ObjectAnimator.ofFloat(mMenuButton!!, "scaleX", 0f) val scaleY1 = ObjectAnimator.ofFloat(mMenuButton!!, "scaleY", 0f) val alpha1 = ObjectAnimator.ofFloat(mMenuButton!!, "alpha", 0f) val set1 = AnimatorSet() set1.playTogether(scaleX1, scaleY1, alpha1) set1.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { for (view in mButtons) { view.visibility = View.INVISIBLE } } override fun onAnimationEnd(animation: Animator) { mMenuButton!!.rotation = 60f mMenuButton!!.setImageResource(iconMenu) } }) val angle = ObjectAnimator.ofFloat(mMenuButton!!, "rotation", 0f) val alpha2 = ObjectAnimator.ofFloat(mMenuButton!!, "alpha", 1f) val scaleX2 = ObjectAnimator.ofFloat(mMenuButton!!, "scaleX", 1f) val scaleY2 = ObjectAnimator.ofFloat(mMenuButton!!, "scaleY", 1f) val set2 = AnimatorSet() set2.interpolator = OvershootInterpolator() set2.playTogether(angle, alpha2, scaleX2, scaleY2) val result = AnimatorSet() result.play(set1).before(set2) result.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { mIsAnimating = true } override fun onAnimationEnd(animation: Animator) { mIsAnimating = false } }) return result } /** * See [R.styleable.CircleMenuView_distance] * @return current distance in pixels. */ /** * See [R.styleable.CircleMenuView_distance] * @param distance in pixels. */ var distance: Float get() = mDistance set(distance) { mDistance = distance invalidate() } /** * CircleMenu event listener. */ open class EventListener { /** * Invoked on menu button click, before animation start. * @param view current CircleMenuView instance. */ open fun onMenuOpenAnimationStart(view: CircleMenuView) {} /** * Invoked on menu button click, after animation end. * @param view - current CircleMenuView instance. */ open fun onMenuOpenAnimationEnd(view: CircleMenuView) {} /** * Invoked on close menu button click, before animation start. * @param view - current CircleMenuView instance. */ open fun onMenuCloseAnimationStart(view: CircleMenuView) {} /** * Invoked on close menu button click, after animation end. * @param view - current CircleMenuView instance. */ open fun onMenuCloseAnimationEnd(view: CircleMenuView) {} /** * Invoked on button click, before animation start. * @param view - current CircleMenuView instance. * @param buttonIndex - clicked button zero-based index. */ open fun onButtonClickAnimationStart(view: CircleMenuView, buttonIndex: Int) {} /** * Invoked on button click, after animation end. * @param view - current CircleMenuView instance. * @param buttonIndex - clicked button zero-based index. */ open fun onButtonClickAnimationEnd(view: CircleMenuView, buttonIndex: Int) {} /** * Invoked on button long click. Invokes {@see onButtonLongClickAnimationStart} and {@see onButtonLongClickAnimationEnd} * if returns true. * @param view current CircleMenuView instance. * @param buttonIndex clicked button zero-based index. * @return true if the callback consumed the long click, false otherwise. */ open fun onButtonLongClick(view: CircleMenuView, buttonIndex: Int): Boolean { return false } /** * Invoked on button long click, before animation start. * @param view - current CircleMenuView instance. * @param buttonIndex - clicked button zero-based index. */ open fun onButtonLongClickAnimationStart(view: CircleMenuView, buttonIndex: Int) {} /** * Invoked on button long click, after animation end. * @param view - current CircleMenuView instance. * @param buttonIndex - clicked button zero-based index. */ open fun onButtonLongClickAnimationEnd(view: CircleMenuView, buttonIndex: Int) {} } private inner class OnButtonClickListener : View.OnClickListener { override fun onClick(view: View) { if (mIsAnimating) { return } val click = getButtonClickAnimation(view as FloatingActionButton) click.duration = durationRing.toLong() click.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { if (eventListener != null) { eventListener!!.onButtonClickAnimationStart(this@CircleMenuView, mButtons.indexOf(view)) } } override fun onAnimationEnd(animation: Animator) { mClosedState = true if (eventListener != null) { eventListener!!.onButtonClickAnimationEnd(this@CircleMenuView, mButtons.indexOf(view)) } } }) click.start() } } private inner class OnButtonLongClickListener : View.OnLongClickListener { override fun onLongClick(view: View): Boolean { if (eventListener == null) { return false } val result = eventListener!!.onButtonLongClick(this@CircleMenuView, mButtons.indexOf(view)) if (result && !mIsAnimating) { val click = getButtonClickAnimation(view as FloatingActionButton) click.duration = longClickDurationRing.toLong() click.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { eventListener!!.onButtonLongClickAnimationStart(this@CircleMenuView, mButtons.indexOf(view)) } override fun onAnimationEnd(animation: Animator) { mClosedState = true eventListener!!.onButtonLongClickAnimationEnd(this@CircleMenuView, mButtons.indexOf(view)) } }) click.start() } return result } } @JvmOverloads constructor(context: Context, attrs: AttributeSet?, @AttrRes defStyleAttr: Int = 0) : super(context, attrs, defStyleAttr) { if (attrs == null) { throw IllegalArgumentException("No buttons icons or colors set") } val menuButtonColor: Int val icons: MutableList<Int> val colors: MutableList<Int> val a = context.theme.obtainStyledAttributes(attrs, R.styleable.CircleMenuView, 0, 0) try { val iconArrayId = a.getResourceId(R.styleable.CircleMenuView_button_icons, 0) val colorArrayId = a.getResourceId(R.styleable.CircleMenuView_button_colors, 0) val iconsIds = resources.obtainTypedArray(iconArrayId) try { val colorsIds = resources.getIntArray(colorArrayId) val buttonsCount = Math.min(iconsIds.length(), colorsIds.size) icons = ArrayList(buttonsCount) colors = ArrayList(buttonsCount) for (i in 0 until buttonsCount) { icons.add(iconsIds.getResourceId(i, -1)) colors.add(colorsIds[i]) } } finally { iconsIds.recycle() } iconMenu = a.getResourceId(R.styleable.CircleMenuView_icon_menu, R.drawable.ic_menu_black_24dp) iconClose = a.getResourceId(R.styleable.CircleMenuView_icon_close, R.drawable.ic_close_black_24dp) durationRing = a.getInteger(R.styleable.CircleMenuView_duration_ring, resources.getInteger(android.R.integer.config_mediumAnimTime)) longClickDurationRing = a.getInteger(R.styleable.CircleMenuView_long_click_duration_ring, resources.getInteger(android.R.integer.config_longAnimTime)) durationOpen = a.getInteger(R.styleable.CircleMenuView_duration_open, resources.getInteger(android.R.integer.config_mediumAnimTime)) durationClose = a.getInteger(R.styleable.CircleMenuView_duration_close, resources.getInteger(android.R.integer.config_mediumAnimTime)) val density = context.resources.displayMetrics.density val defaultDistance = DEFAULT_DISTANCE * density mDistance = a.getDimension(R.styleable.CircleMenuView_distance, defaultDistance) menuButtonColor = a.getColor(R.styleable.CircleMenuView_icon_color, Color.WHITE) } finally { a.recycle() } initLayout(context) initMenu(menuButtonColor) initButtons(context, icons, colors) } /** * Constructor for creation CircleMenuView in code, not in xml-layout. * @param context current context, will be used to access resources. * @param icons buttons icons resource ids array. Items must be @DrawableRes. * @param colors buttons colors resource ids array. Items must be @DrawableRes. */ constructor(context: Context, icons: List<Int>, colors: List<Int>) : super(context) { val density = context.resources.displayMetrics.density val defaultDistance = DEFAULT_DISTANCE * density iconMenu = R.drawable.ic_menu_black_24dp iconClose = R.drawable.ic_close_black_24dp durationRing = resources.getInteger(android.R.integer.config_mediumAnimTime) longClickDurationRing = resources.getInteger(android.R.integer.config_longAnimTime) durationOpen = resources.getInteger(android.R.integer.config_mediumAnimTime) durationClose = resources.getInteger(android.R.integer.config_mediumAnimTime) mDistance = defaultDistance initLayout(context) initMenu(Color.WHITE) initButtons(context, icons, colors) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) val w = View.resolveSizeAndState(mDesiredSize, widthMeasureSpec, 0) val h = View.resolveSizeAndState(mDesiredSize, heightMeasureSpec, 0) setMeasuredDimension(w, h) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) if (!changed && mIsAnimating) { return } mMenuButton!!.getContentRect(mButtonRect) mRingView!!.setStrokeWidth(mButtonRect.width()) mRingView!!.radius = mRingRadius val lp = mRingView!!.layoutParams as FrameLayout.LayoutParams lp.width = right - left lp.height = bottom - top } private fun initLayout(context: Context) { LayoutInflater.from(context).inflate(R.layout.circle_menu, this, true) setWillNotDraw(true) clipChildren = false clipToPadding = false val density = context.resources.displayMetrics.density val buttonSize = DEFAULT_BUTTON_SIZE * density mRingRadius = (buttonSize + (mDistance - buttonSize / 2)).toInt() mDesiredSize = (mRingRadius.toFloat() * 2f * DEFAULT_RING_SCALE_RATIO).toInt() mRingView = findViewById(R.id.ring_view) } private fun initMenu(menuButtonColor: Int) { val animListener = object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { if (eventListener != null) { if (mClosedState) { eventListener!!.onMenuOpenAnimationStart(this@CircleMenuView) } else { eventListener!!.onMenuCloseAnimationStart(this@CircleMenuView) } } } override fun onAnimationEnd(animation: Animator) { if (eventListener != null) { if (mClosedState) { eventListener!!.onMenuOpenAnimationEnd(this@CircleMenuView) } else { eventListener!!.onMenuCloseAnimationEnd(this@CircleMenuView) } } mClosedState = !mClosedState } } mMenuButton = findViewById(R.id.circle_menu_main_button) mMenuButton!!.setImageResource(iconMenu) mMenuButton!!.backgroundTintList = ColorStateList.valueOf(menuButtonColor) mMenuButton!!.setOnClickListener(OnClickListener { if (mIsAnimating) { return@OnClickListener } val animation = if (mClosedState) openMenuAnimation else closeMenuAnimation animation.duration = (if (mClosedState) durationClose else durationOpen).toLong() animation.addListener(animListener) animation.start() }) } private fun initButtons(context: Context, icons: List<Int>, colors: List<Int>) { val buttonsCount = Math.min(icons.size, colors.size) for (i in 0 until buttonsCount) { val button = FloatingActionButton(context) button.setImageResource(icons[i]) button.backgroundTintList = ColorStateList.valueOf(colors[i]) button.isClickable = true button.setOnClickListener(OnButtonClickListener()) button.setOnLongClickListener(OnButtonLongClickListener()) button.scaleX = 0f button.scaleY = 0f button.layoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT) addView(button) mButtons.add(button) } } private fun offsetAndScaleButtons(centerX: Float, centerY: Float, angleStep: Float, offset: Float, scale: Float) { var i = 0 val cnt = mButtons.size while (i < cnt) { val angle = angleStep * i - 90 val x = Math.cos(Math.toRadians(angle.toDouble())).toFloat() * offset val y = Math.sin(Math.toRadians(angle.toDouble())).toFloat() * offset val button = mButtons[i] button.x = centerX + x button.y = centerY + y button.scaleX = 1.0f * scale button.scaleY = 1.0f * scale i++ } } private fun getButtonClickAnimation(button: FloatingActionButton): Animator { val buttonNumber = mButtons.indexOf(button) + 1 val stepAngle = 360f / mButtons.size val rOStartAngle = 270 - stepAngle + stepAngle * buttonNumber val rStartAngle = if (rOStartAngle > 360) rOStartAngle % 360 else rOStartAngle val x = Math.cos(Math.toRadians(rStartAngle.toDouble())).toFloat() * mDistance val y = Math.sin(Math.toRadians(rStartAngle.toDouble())).toFloat() * mDistance val pivotX = button.pivotX val pivotY = button.pivotY button.pivotX = pivotX - x button.pivotY = pivotY - y val rotateButton = ObjectAnimator.ofFloat(button, "rotation", 0f, 360f) rotateButton.addListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { button.pivotX = pivotX button.pivotY = pivotY } }) val elevation = mMenuButton!!.compatElevation mRingView!!.visibility = View.INVISIBLE mRingView!!.startAngle = rStartAngle val csl = button.backgroundTintList if (csl != null) { mRingView!!.setStrokeColor(csl.defaultColor) } val ring = ObjectAnimator.ofFloat(mRingView!!, "angle", 360f) val scaleX = ObjectAnimator.ofFloat(mRingView!!, "scaleX", 1f, DEFAULT_RING_SCALE_RATIO) val scaleY = ObjectAnimator.ofFloat(mRingView!!, "scaleY", 1f, DEFAULT_RING_SCALE_RATIO) val visible = ObjectAnimator.ofFloat(mRingView!!, "alpha", 1f, 0f) val lastSet = AnimatorSet() lastSet.playTogether(scaleX, scaleY, visible, closeMenuAnimation) val firstSet = AnimatorSet() firstSet.playTogether(rotateButton, ring) val result = AnimatorSet() result.play(firstSet).before(lastSet) result.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { mIsAnimating = true if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { bringChildToFront(mRingView) bringChildToFront(button) } else { button.compatElevation = elevation + 1 ViewCompat.setZ(mRingView!!, elevation + 1) for (b in mButtons) { if (b !== button) { (b as FloatingActionButton).compatElevation = 0f } } } mRingView!!.scaleX = 1f mRingView!!.scaleY = 1f mRingView!!.visibility = View.VISIBLE } override fun onAnimationEnd(animation: Animator) { mIsAnimating = false if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { for (b in mButtons) { (b as FloatingActionButton).compatElevation = elevation } ViewCompat.setZ(mRingView!!, elevation) } } }) return result } private fun openOrClose(open: Boolean, animate: Boolean) { if (mIsAnimating) { return } if (open && !mClosedState) { return } if (!open && mClosedState) { return } if (animate) { mMenuButton!!.performClick() } else { mClosedState = !open val centerX = mMenuButton!!.x val centerY = mMenuButton!!.y val buttonsCount = mButtons.size val angleStep = 360f / buttonsCount val offset = if (open) mDistance else 0f val scale = if (open) 1f else 0f mMenuButton!!.setImageResource(if (open) iconClose else iconMenu) mMenuButton!!.alpha = if (open) DEFAULT_CLOSE_ICON_ALPHA else 1f val visibility = if (open) View.VISIBLE else View.INVISIBLE for (view in mButtons) { view.visibility = visibility } offsetAndScaleButtons(centerX, centerY, angleStep, offset, scale) } } /** * Open menu programmatically * @param animate open with animation or not */ fun open(animate: Boolean) { openOrClose(true, animate) } /** * Close menu programmatically * @param animate close with animation or not */ fun close(animate: Boolean) { openOrClose(false, animate) } companion object { private val DEFAULT_BUTTON_SIZE = 56 private val DEFAULT_DISTANCE = DEFAULT_BUTTON_SIZE * 1.5f private val DEFAULT_RING_SCALE_RATIO = 1.3f private val DEFAULT_CLOSE_ICON_ALPHA = 0.3f } }
0
Kotlin
0
0
2297808c4f92bb805fe11cfd6c06f32efdef390b
22,501
circle-menu-android
MIT License
DeviceTracking/app/src/main/java/com/alpsproject/devicetracking/delegates/PermissionDelegate.kt
berkethetechnerd
313,860,328
false
null
package com.alpsproject.devicetracking.delegates interface PermissionDelegate { fun permissionGranted() fun permissionRejected() }
0
Kotlin
1
0
f803320bc35c4cee9ba44d8fa03b5d03b4bb2705
139
ALPS-DeviceTracking
MIT License
common-jvm/src/test/kotlin/com/vc137/boids/integration/SerialSimulatorTest.kt
vic-c137
112,715,056
false
null
package com.vc137.boids.integration import com.vc137.boids.awaitSystemCliCommand import com.vc137.boids.currentSystemUnixTimestamp import com.vc137.boids.currentSystemWorkingDirectory import com.vc137.boids.implementation.* import com.vc137.boids.overwriteSystemFile import com.vc137.boids.simulation.* import com.vc137.boids.visualization.LineAppender import com.vc137.boids.visualization.createDefaultGnuplotScript import kotlin.test.Test import kotlin.test.assertEquals class SerialSimulatorTest { /** * Live test that demonstrates rendering 3d visualization of * the swarm simulation generated for the run - requires that * gnuplot be installed on the test environment * * To install gnuplot with Homebrew: * * brew install gnuplot * * To install Homebrew: * * /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" */ @Test fun testSerialSimulatorRunsForExpectedDuration() { // Setup val configuration = getBaselineConfiguration() val rules = getBaselineRules() val simulator = ::serialSimulator val swarmSource = ::randomSwarmSource val simulation = Simulation(configuration, rules, simulator, swarmSource) val pwd = currentSystemWorkingDirectory() val outputFile = pwd + "/output/visualization_${currentSystemUnixTimestamp()}" val scriptFile = pwd + "/output/create_visualization.gp" // Run val result = simulation.run() // Visualize val script = createDefaultGnuplotScript(outputFile, configuration, result, object : LineAppender { override fun appendln(builder: StringBuilder) { builder.append("\n") } }) try { overwriteSystemFile(scriptFile, script) "gnuplot $scriptFile".awaitSystemCliCommand() } catch (ex: Exception) { } // Assert assertEquals(result.last().timestamp, configuration.iterations) assertEquals(result.size.toLong(), configuration.iterations + 1) assertEquals(result.first().swarm.size.toLong(), configuration.swarmSize) } }
0
Kotlin
0
0
bb84bc075a292a7785658384cccc458c015038c0
2,219
kotlin-boids
Apache License 2.0
app/src/main/java/com/noto/app/domain/model/Enums.kt
alialbaali
245,781,254
false
null
package com.noto.app.domain.model enum class NotoColor { Gray, Blue, Pink, Cyan, Purple, Red, Yellow, Orange, Green, Brown, BlueGray, Teal, Indigo, DeepPurple, DeepOrange, DeepGreen, LightBlue, LightGreen, LightRed, LightPink, Black, } enum class Icon { Futuristic, DarkRain, Airplane, BlossomIce, DarkAlpine, DarkSide, Earth, Fire, Purpleberry, SanguineSun, } enum class FolderListSortingType { Manual, CreationDate, Alphabetical, } enum class NoteListSortingType { Manual, CreationDate, Alphabetical, } enum class SortingOrder { Ascending, Descending, } enum class Theme { System, SystemBlack, Light, Dark, Black, } enum class Layout { Linear, Grid, } enum class Font { Nunito, Monospace, } enum class Grouping { Default, CreationDate, Label, } enum class Language { System, English, Turkish, Arabic, Indonesian, @Deprecated("Not supported anymore.") Russian, @Deprecated("Not supported anymore.") Tamil, Spanish, French, German; companion object { @Suppress("DEPRECATION") val Deprecated = listOf(Tamil, Russian) } } enum class VaultTimeout { Immediately, OnAppClose, After1Hour, After4Hours, After12Hours, } enum class NewNoteCursorPosition { Body, Title, } enum class GroupingOrder { Ascending, Descending, } enum class FilteringType { Inclusive, Exclusive, }
22
Kotlin
5
110
eddbc37678b501264a03d71d05d1bcc074a0f571
1,354
Noto
Apache License 2.0
telek-hc/src/main/kotlin/by/dev/madhead/telek/telek/hc/TelekHC.kt
madhead
249,262,852
false
null
package by.dev.madhead.telek.telek.hc import by.dev.madhead.telek.model.ForceReply import by.dev.madhead.telek.model.InlineKeyboardMarkup import by.dev.madhead.telek.model.Message import by.dev.madhead.telek.model.ReplyKeyboardMarkup import by.dev.madhead.telek.model.ReplyKeyboardRemove import by.dev.madhead.telek.model.ReplyMarkup import by.dev.madhead.telek.model.Update import by.dev.madhead.telek.model.User import by.dev.madhead.telek.model.WebhookInfo import by.dev.madhead.telek.model.communication.AnswerCallbackQueryRequest import by.dev.madhead.telek.model.communication.GetUpdatesRequest import by.dev.madhead.telek.model.communication.InputFile import by.dev.madhead.telek.model.communication.Response import by.dev.madhead.telek.model.communication.SendMessageRequest import by.dev.madhead.telek.model.communication.SendPhotoRequest import by.dev.madhead.telek.model.communication.SetWebhookRequest import by.dev.madhead.telek.telek.Telek import by.dev.madhead.telek.telek.TelekException import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import kotlinx.serialization.ContextSerializer import kotlinx.serialization.ImplicitReflectionSerializer import kotlinx.serialization.KSerializer import kotlinx.serialization.builtins.list import kotlinx.serialization.builtins.serializer import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonConfiguration import kotlinx.serialization.modules.SerializersModule import org.apache.http.client.methods.HttpGet import org.apache.http.client.methods.HttpPost import org.apache.http.client.methods.HttpUriRequest import org.apache.http.entity.BufferedHttpEntity import org.apache.http.entity.ContentType import org.apache.http.entity.StringEntity import org.apache.http.entity.mime.MultipartEntityBuilder import org.apache.http.entity.mime.content.InputStreamBody import org.apache.http.entity.mime.content.StringBody import org.apache.http.impl.nio.client.HttpAsyncClients import org.apache.http.util.EntityUtils import org.apache.logging.log4j.LogManager import java.io.ByteArrayInputStream import java.io.File import java.io.FileInputStream import java.net.URI /** * [Telek] implementation based on [Apache HttpComponents][http://hc.apache.org]. */ @ImplicitReflectionSerializer @Suppress("TooManyFunctions") class TelekHC(private val token: String) : Telek, AutoCloseable { companion object { val logger = LogManager.getLogger(TelekHC::class.java) } private val client = HttpAsyncClients.createDefault() private val json = Json( configuration = JsonConfiguration.Stable.copy(encodeDefaults = false, ignoreUnknownKeys = true), context = SerializersModule { polymorphic(ReplyMarkup::class) { ForceReply::class with ForceReply.serializer() InlineKeyboardMarkup::class with InlineKeyboardMarkup.serializer() ReplyKeyboardMarkup::class with ReplyKeyboardMarkup.serializer() ReplyKeyboardRemove::class with ReplyKeyboardRemove.serializer() } } ) init { client.start() } override suspend fun getUpdates(request: GetUpdatesRequest): List<Update> { val httpRequest = HttpPost().apply { uri = methodURI("getUpdates") entity = StringEntity(json.stringify(GetUpdatesRequest.serializer(), request), ContentType.APPLICATION_JSON) } return callApi(httpRequest, Update.serializer().list) } override suspend fun setWebhook(request: SetWebhookRequest) { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun deleteWebhook() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getWebhookInfo(): WebhookInfo { val httpRequest = HttpGet().apply { uri = methodURI("getWebhookInfo") } return callApi(httpRequest, WebhookInfo.serializer()) } override suspend fun getMe(): User { val httpRequest = HttpGet().apply { uri = methodURI("getMe") } return callApi(httpRequest, User.serializer()) } override suspend fun sendMessage(request: SendMessageRequest): Message { val httpRequest = HttpPost().apply { uri = methodURI("sendMessage") entity = StringEntity(json.stringify(SendMessageRequest.serializer(), request), ContentType.APPLICATION_JSON) } return callApi(httpRequest, Message.serializer()) } override suspend fun forwardMessage() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendPhoto(request: SendPhotoRequest): Message { val httpRequest = when (val photo = request.photo) { is InputFile.StringInputFile -> HttpPost().apply { uri = methodURI("sendPhoto") entity = StringEntity(json.stringify(SendPhotoRequest.serializer(), request), ContentType.APPLICATION_JSON) } else -> HttpPost().apply { uri = methodURI("sendPhoto") entity = withContext(Dispatchers.IO) { BufferedHttpEntity( MultipartEntityBuilder.create().apply { addPart("chat_id", StringBody(request.chatId.asString(), ContentType.MULTIPART_FORM_DATA)) when (photo) { is InputFile.FilePathInputFile -> { val file = File(photo.path) addPart( "photo", InputStreamBody(FileInputStream(file), ContentType.DEFAULT_BINARY, file.name) ) } is InputFile.BytesInputFile -> { addPart( "photo", InputStreamBody(ByteArrayInputStream(photo.bytes), ContentType.DEFAULT_BINARY, photo.filename) ) } } request.caption?.let { addPart("caption", StringBody(it, ContentType.MULTIPART_FORM_DATA)) } request.parseMode?.let { addPart("parse_mode", StringBody(it.name, ContentType.MULTIPART_FORM_DATA)) } request.parseMode?.let { addPart("parse_mode", StringBody(it.name, ContentType.MULTIPART_FORM_DATA)) } if (request.disableNotification == true) { addPart("disable_notification", StringBody("true", ContentType.MULTIPART_FORM_DATA)) } request.replyToMessageId?.let { addPart("reply_to_message_id", StringBody(it.toString(), ContentType.MULTIPART_FORM_DATA)) } request.replyMarkup?.let { addPart("reply_markup", StringBody( json.stringify(ContextSerializer(ReplyMarkup::class), it), ContentType.APPLICATION_JSON )) } }.build() ) } } } return callApi(httpRequest, Message.serializer()) } override suspend fun sendAudio() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendDocument() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendVideo() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendAnimation() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendVoice() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendVideoNote() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendMediaGroup() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendLocation() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun editMessageLiveLocation() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun stopMessageLiveLocation() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendVenue() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendContact() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendPoll() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendDice() { TODO("Not yet implemented") } override suspend fun sendChatAction() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getUserProfilePhotos() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getFile() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun kickChatMember() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun unbanChatMember() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun restrictChatMember() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun promoteChatMember() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setChatAdministratorCustomTitle() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setChatPermissions() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun exportChatInviteLink() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setChatPhoto() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun deleteChatPhoto() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setChatTitle() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setChatDescription() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun pinChatMessage() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun unpinChatMessage() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun leaveChat() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getChat() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getChatAdministrators() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getChatMembersCount() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getChatMember() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setChatStickerSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun deleteChatStickerSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun answerCallbackQuery(request: AnswerCallbackQueryRequest): Boolean { val httpRequest = HttpPost().apply { uri = methodURI("answerCallbackQuery") entity = StringEntity(json.stringify(AnswerCallbackQueryRequest.serializer(), request), ContentType.APPLICATION_JSON) } return callApi(httpRequest, Boolean.serializer()) } override suspend fun setMyCommands() { TODO("Not yet implemented") } override suspend fun getMyCommands() { TODO("Not yet implemented") } override suspend fun editMessageText() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun editMessageCaption() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun editMessageMedia() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun editMessageReplyMarkup() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun stopPoll() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun deleteMessage() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendSticker() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getStickerSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun uploadStickerFile() { TODO("Not yet implemented") } override suspend fun createNewStickerSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun addStickerToSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setStickerPositionInSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun deleteStickerFromSet() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setStickerSetThumb() { TODO("Not yet implemented") } override suspend fun answerInlineQuery() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendInvoice() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun answerShippingQuery() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun answerPreCheckoutQuery() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setPassportDataErrors() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun sendGame() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun setGameScore() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override suspend fun getGameHighScores() { TODO("not implemented") // To change body of created functions use File | Settings | File Templates. } override fun close() { client.close() } private fun methodURI(method: String) = URI("https://api.telegram.org/bot$token/$method") private suspend fun <T> callApi(httpRequest: HttpUriRequest, serializer: KSerializer<T>): T { val httpResponse = client.exekute(httpRequest) val response = withContext(Dispatchers.IO) { json.parse(Response.Companion, EntityUtils.toString(httpResponse.entity)) } return if (response is Response.Successful) { json.fromJson(serializer, response.result) } else { logger.error("${response.description}") throw TelekException(response.description, response) } } }
0
Kotlin
0
0
8f1dff19cce8394d76ef9ed6df4577a2d67e84f7
18,405
telek
MIT License
solve-lpaas/src/main/kotlin/it/unibo/tuprolog/solve/lpaas/util/Costants.kt
pikalab-unibo-students
593,963,677
false
{"Kotlin": 3974165, "Java": 19220, "ANTLR": 10366, "CSS": 3070, "Prolog": 818, "Dockerfile": 369}
package it.unibo.tuprolog.solve.lpaas.util import it.unibo.tuprolog.solve.classic.stdlib.DefaultBuiltins import it.unibo.tuprolog.solve.library.Library import it.unibo.tuprolog.solve.libs.io.IOLib import it.unibo.tuprolog.solve.libs.oop.OOPLib import it.unibo.tuprolog.theory.Theory import it.unibo.tuprolog.theory.parsing.parse const val EAGER_OPTION = "eagerness" const val TIMEOUT_OPTION = "timeout" const val LIMIT_OPTION = "limit" const val LAZY_OPTION = "laziness" val DEFAULT_STATIC_THEORY_STRING = """ f(b). f(d). """.trimIndent() val DEFAULT_STATIC_THEORY = Theory.parse(DEFAULT_STATIC_THEORY_STRING) fun <A, B> List<Pair<A, B>>.toMap(): MutableMap<A, B> { val map = mutableMapOf<A, B>() this.forEach { map[it.first] = it.second } return map } fun List<String>.joinAll(): String = this.joinToString { it } fun convertStringToKnownLibrary(libName: String): Library { return when(libName) { "prolog.io" -> IOLib "prolog.oop" -> OOPLib "prolog.lang" -> DefaultBuiltins else -> throw IllegalArgumentException() } }
18
Kotlin
1
0
9dc096ae9904d3fe3c100928df3dfb7a5b3168cf
1,134
ds-project-osimani-ay2021
Apache License 2.0
subprojects/delivery/feature-toggles/src/main/kotlin/com/avito/android/plugin/BlameParser.kt
avito-tech
230,265,582
false
null
package com.avito.android.plugin import java.time.Instant import java.time.ZoneId internal class BlameParser { private val allEmptySymbols = "\\s+".toRegex() private val trashSymbols = "[()<>]".toRegex() fun parseBlameCodeLines(blame: String): List<CodeElement> { return blame.splitToSequence(newLine) .mapIndexed { index, line -> val lineNumber = index + 1 val lineSplit = line.split("$lineNumber)") if (lineSplit.size != blameLineNumberSplitSize) { throw RuntimeException("Something wrong with blame: $line") } val codeLine = lineSplit.last() val otherStuff = lineSplit.first() val split = otherStuff.split(allEmptySymbols) val email = split[emailPart].replace(regex = trashSymbols, replacement = "") CodeElement( codeLine = codeLine, changeTime = split[timePart].toLocalDate(), email = email ) } .toList() } } private fun String.toLocalDate() = Instant.ofEpochSecond(this.toLong()).atZone(ZoneId.of("Europe/Moscow")).toLocalDate() private const val newLine = "\n" private const val emailPart = 2 private const val timePart = 3 private const val blameLineNumberSplitSize = 2
6
Kotlin
36
327
b8d12a06a169ae60d89d24f66978a7dc23833282
1,391
avito-android
MIT License
ok-marketplace-be-repository-sql/src/main/kotlin/ru/otus/otuskotlin/marketplace/backend/repository/sql/schema/ProposalTagDto.kt
otuskotlin
323,966,359
false
null
package ru.otus.otuskotlin.marketplace.backend.repository.sql.schema import org.jetbrains.exposed.dao.UUIDEntityClass import org.jetbrains.exposed.dao.id.EntityID import java.util.* class ProposalTagDto(id: EntityID<UUID>) : AdTagDto<ProposalDto>(id, ProposalsTagsTable, ProposalDto) { var proposal get() = ad set(value) { ad = value } companion object : UUIDEntityClass<ProposalTagDto>(ProposalsTagsTable) { } }
0
Kotlin
0
1
5f52fc91b3d71397cfabd02b5abb86a69d8567a1
464
202012-otuskotlin-marketplace
MIT License
verik-compiler/src/main/kotlin/io/verik/compiler/transform/lower/BlockExpressionReducerStage.kt
frwang96
269,980,078
false
null
/* * SPDX-License-Identifier: Apache-2.0 */ package io.verik.compiler.transform.lower import io.verik.compiler.ast.element.declaration.common.EProperty import io.verik.compiler.ast.element.expression.common.EBlockExpression import io.verik.compiler.ast.element.expression.common.EExpression import io.verik.compiler.common.TreeVisitor import io.verik.compiler.main.ProjectContext import io.verik.compiler.main.ProjectStage import io.verik.compiler.message.Messages /** * Stage that reduces block expressions that are generated as a result of expression extraction. */ object BlockExpressionReducerStage : ProjectStage() { override fun process(projectContext: ProjectContext) { projectContext.project.accept(BlockExpressionReducerVisitor) } private object BlockExpressionReducerVisitor : TreeVisitor() { override fun visitBlockExpression(blockExpression: EBlockExpression) { super.visitBlockExpression(blockExpression) val blockExpressionIndexerVisitor = BlockExpressionIndexerVisitor() val statements = ArrayList<EExpression>() for (statement in blockExpression.statements) { if (statement is EBlockExpression) { statements.addAll(statement.statements) continue } blockExpressionIndexerVisitor.reducibleBlockExpressions.clear() statement.accept(blockExpressionIndexerVisitor) blockExpressionIndexerVisitor.reducibleBlockExpressions.forEach { reduceBlockExpression(statements, it) } statements.add(statement) } statements.forEach { it.parent = blockExpression } blockExpression.statements = statements } private fun reduceBlockExpression(statements: ArrayList<EExpression>, blockExpression: EBlockExpression) { if (blockExpression.statements.isEmpty()) Messages.INTERNAL_ERROR.on(blockExpression, "Unexpected empty block expression") statements.addAll(blockExpression.statements.dropLast(1)) blockExpression.replace(blockExpression.statements.last()) } } private class BlockExpressionIndexerVisitor : TreeVisitor() { val reducibleBlockExpressions = ArrayList<EBlockExpression>() override fun visitBlockExpression(blockExpression: EBlockExpression) { val parent = blockExpression.parent if ((parent is EExpression && parent.childBlockExpressionShouldBeReduced(blockExpression)) || parent is EProperty ) { reducibleBlockExpressions.add(blockExpression) } } } }
0
Kotlin
1
33
ee22969235460fd144294bcbcbab0338c638eb92
2,748
verik
Apache License 2.0
src/main/java/dsl/OtherFunction.kt
wz7982
359,367,632
false
null
@file:JvmName("OtherFunction") package dsl /** * 空值转换函数,前面的表达式为空时选择后面的表达式 * @param query Query 检测表达式 * @param value Query 为空时使用的表达式 * @return Query 表达式类型 */ fun ifNull(query: Query, value: Query): Query { return QueryExprFunction("*IFNULL", listOf(query, value)) } /** * 空值转换函数,前面的表达式为空时选择后面的表达式 * @param query Query 检测表达式 * @param value T 为空时使用的值,合法的类型有Number、String、Date、List、Boolean以及null * @return Query 表达式类型 */ fun <T> ifNull(query: Query, value: T): Query { return ifNull(query, const(value)) } /** * 类型转换函数 * @param query Query 待转换表达式 * @param type String 转换的类型 * @return Query 表达式类型 */ fun cast(query: Query, type: String): Query { return QueryCast(query, type) } /** * 字符串聚合函数 * @param query Query 聚合的列 * @param separator String 分隔符 * @param distinct Boolean 是否去重 * @param orderBy Array<out OrderBy> 排序规则 * @return Query 表达式类型 */ fun stringAgg( query: Query, separator: String, distinct: Boolean = false, vararg orderBy: OrderBy ): Query { return QueryAggFunction("*STRING_AGG", listOf(query, const(separator)), distinct = distinct, orderBy = orderBy.toList()) } /** * 数组聚合函数 * @param query Query 聚合的列 * @param separator String 分隔符 * @param distinct Boolean 是否去重 * @param orderBy Array<out OrderBy> 排序规则 * @return Query */ fun arrayAgg( query: Query, separator: String, distinct: Boolean = false, vararg orderBy: OrderBy ): Query { return QueryAggFunction("*ARRAY_AGG", listOf(query, const(separator)), distinct = distinct, orderBy = orderBy.toList()) } /** * 查找字符否在某个以","隔开的字符串中 * @param value Query 查找的字符 * @param query Query 查找的列 * @return Query 表达式类型 */ fun findInSet(value: Query, query: Query): Query { return QueryExprFunction("*FIND_IN_SET", listOf(value, query)) } /** * 查找字符否在某个以","隔开的字符串中 * @param value String 查找的字符 * @param query Query 查找的列 * @return Query 表达式类型 */ fun findInSet(value: String, query: Query): Query { return findInSet(const(value), query) } /** * jsonLength函数 * @param query Query 查找的表达式 * @return Query 表达式类型 */ fun jsonLength(query: Query): Query { return QueryExprFunction("*JSON_LENGTH", listOf(query)) } /** * 拼接函数 * @param query Array<out Query> 拼接的表达式列表 * @return Query 表达式类型 */ fun concat(vararg query: Query): Query { return QueryExprFunction("*CONCAT", query.toList()) } /** * 拼接函数 * @param separator String 分隔符 * @param query Array<out Query> 拼接的表达式列表 * @return Query 表达式类型 */ fun concatWs(separator: String, vararg query: Query): Query { listOf<Query>(const(separator)) + query.toList() return QueryExprFunction("*CONCAT_WS", listOf<Query>(const(separator)) + query.toList()) }
0
Kotlin
1
6
bd0ddeaf1c0853ae061e3e40f1dd94006e5ecda4
2,668
easysql
Apache License 2.0
src/main/kotlin/cc/rits/membership/console/paymaster/configuration/IAMConfiguration.kt
membership-console
558,499,219
false
null
package cc.rits.membership.console.paymaster.configuration import io.micronaut.context.annotation.Property import jakarta.inject.Singleton /** * IAMのコンフィグレーション */ @Singleton data class IAMConfiguration( @Property(name = "iam.api.host") val host: String )
5
Kotlin
0
3
612d59a4419e09ff0e20dbdea0aa1114fb12507f
270
paymaster
MIT License
src/commonTest/kotlin/com.adamratzman/spotify/priv/ClientPersonalizationApiTest.kt
jkzilla
386,782,106
true
{"Kotlin": 914973, "Shell": 443, "JavaScript": 88}
/* Spotify Web API, Kotlin Wrapper; MIT License, 2017-2021; Original author: <NAME> */ package com.adamratzman.spotify.priv import com.adamratzman.spotify.SpotifyClientApi import com.adamratzman.spotify.buildSpotifyApi import com.adamratzman.spotify.endpoints.client.ClientPersonalizationApi import com.adamratzman.spotify.runBlockingTest import kotlin.test.Test import kotlin.test.assertTrue class ClientPersonalizationApiTest { var api: SpotifyClientApi? = null init { runBlockingTest { (buildSpotifyApi() as? SpotifyClientApi)?.let { api = it } } } fun testPrereq() = api != null @Test fun testGetTopArtists() { runBlockingTest { if (!testPrereq()) return@runBlockingTest else api!! assertTrue( api!!.personalization .getTopArtists(5, timeRange = ClientPersonalizationApi.TimeRange.MEDIUM_TERM) .items .isNotEmpty() ) } } @Test fun testGetTopTracks() { runBlockingTest { if (!testPrereq()) return@runBlockingTest else api!! assertTrue(api!!.personalization.getTopTracks(5).items.isNotEmpty()) } } }
0
Kotlin
1
0
7922dd82e018562cb06cd2e6362c3e40b9b70ef1
1,246
spotify-web-api-kotlin
MIT License
src/main/kotlin/xyz/bluspring/argyle/wrappers/FabricCustomValueArrayWrapper.kt
KiltMC
763,325,301
false
{"Kotlin": 78949, "Java": 848}
package xyz.bluspring.argyle.wrappers import net.fabricmc.loader.api.metadata.CustomValue import org.quiltmc.loader.api.LoaderValue class FabricCustomValueArrayWrapper(val key: String, val wrapped: CustomValue.CvArray) : LoaderValue.LArray { override fun type(): LoaderValue.LType? { return LoaderValue.LType.valueOf(wrapped.type.name) } override fun location(): String? { return key } override fun asObject(): LoaderValue.LObject? { TODO("Not yet implemented") } override fun asArray(): LoaderValue.LArray? { return FabricCustomValueArrayWrapper(key, wrapped) } override fun asString(): String? { TODO("Not yet implemented") } override fun asNumber(): Number? { TODO("Not yet implemented") } override fun asBoolean(): Boolean { TODO("Not yet implemented") } override val size: Int get() = wrapped.size() override fun add(element: LoaderValue): Boolean { return false } override fun add(index: Int, element: LoaderValue) { } override fun addAll(index: Int, elements: Collection<LoaderValue>): Boolean { return false } override fun addAll(elements: Collection<LoaderValue>): Boolean { return false } override fun clear() { } override fun contains(element: LoaderValue): Boolean { return wrapped.contains(QuiltLoaderValueWrapper(key, element)) } override fun containsAll(elements: Collection<LoaderValue>): Boolean { return false } override fun get(index: Int): LoaderValue { return QuiltLoaderValueWrapper(key, wrapped[index]) } override fun indexOf(element: LoaderValue): Int { return wrapped.indexOf(QuiltLoaderValueWrapper(key, element)) } override fun isEmpty(): Boolean { return wrapped.size() == 0 } override fun iterator(): MutableIterator<LoaderValue> { return wrapped.map { QuiltLoaderValueWrapper(key, it) }.toMutableList().listIterator() } override fun lastIndexOf(element: LoaderValue): Int { return wrapped.lastIndexOf(QuiltLoaderValueWrapper(key, element)) } override fun listIterator(): MutableListIterator<LoaderValue> { TODO("Not yet implemented") } override fun listIterator(index: Int): MutableListIterator<LoaderValue> { TODO("Not yet implemented") } override fun remove(element: LoaderValue): Boolean { return false } override fun removeAll(elements: Collection<LoaderValue>): Boolean { return false } override fun removeAt(index: Int): LoaderValue { throw IllegalStateException() } override fun retainAll(elements: Collection<LoaderValue>): Boolean { return false } override fun set(index: Int, element: LoaderValue): LoaderValue { throw IllegalStateException() } override fun subList(fromIndex: Int, toIndex: Int): MutableList<LoaderValue> { return wrapped.toList().subList(fromIndex, toIndex).map { QuiltLoaderValueWrapper(key, it) }.toMutableList() } }
0
Kotlin
0
2
f1ca175463eb9c5211a38a7a3d5b54cfe14624bd
3,135
Argyle
Apache License 2.0
src/main/kotlin/utils/Utils.kt
MinecraftDiplom
800,851,458
false
{"Kotlin": 145460, "Java": 79}
@file:OptIn(ExperimentalCoroutinesApi::class) package utils import com.github.kotlintelegrambot.entities.ChatId import com.github.kotlintelegrambot.entities.Message import com.github.kotlintelegrambot.entities.TelegramFile import kotlinx.coroutines.* import models.braks.FamilyTree import java.time.ZoneId import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.* @DelicateCoroutinesApi @OptIn(ExperimentalCoroutinesApi::class) val DAEMON = newSingleThreadContext("TelegramBot-Daemon") @OptIn(DelicateCoroutinesApi::class) fun withDaemon(block: suspend () ->Unit) { CoroutineScope(DAEMON).launch { block() } } val Message.chatId: ChatId get() = ChatId.fromId(this.chat.id) val moscowZone: TimeZone = TimeZone.getTimeZone(ZoneId.of("Europe/Moscow")) fun calendarMoscow() : Calendar = GregorianCalendar.getInstance(moscowZone) fun getTimeMillis(): Long{ calendarMoscow().apply { return timeInMillis } } fun String.cut(requiredLength: Int, postFix: String = "..."): String { return if (length > requiredLength) { substring(0, requiredLength - 3) + postFix }else this.toString() } fun List<String>.toForm(formLength: Int = 10, wallCornerEmoji :String = "➕", wallEmoji: String = "➖", ):String{ val builder = StringBuilder() builder.append(wallCornerEmoji) builder.append(wallEmoji.repeat(formLength-2)) builder.appendLine(wallCornerEmoji) this.forEach { builder.appendLine(it) } builder.append(wallCornerEmoji) builder.append(wallEmoji.repeat(formLength-2)) builder.append(wallCornerEmoji) return builder.toString() } fun List<String>.toUpperLineForm(formLength: Int = 10, wallCornerEmoji :String = "➕", wallEmoji: String = "➖", ):String{ val builder = StringBuilder() this.forEach { builder.appendLine(it) } builder.append(wallCornerEmoji) builder.append(wallEmoji.repeat(formLength-2)) builder.append(wallCornerEmoji) return builder.toString() } fun List<String>.toDownLineForm(formLength: Int = 10, wallCornerEmoji :String = "➕", wallEmoji: String = "➖", ):String{ val builder = StringBuilder() this.forEach { builder.appendLine(it) } builder.append(wallCornerEmoji) builder.append(wallEmoji.repeat(formLength-2)) builder.append(wallCornerEmoji) return builder.toString() } fun Long?.timeToString(): String{ val now = getTimeLocal(getTimeMillis()) val started = getTimeLocal(this ?: 0L) val seconds = ChronoUnit.SECONDS.between(started, now) val minutes = ChronoUnit.MINUTES.between(started, now) val hours = ChronoUnit.HOURS.between(started, now) val days = ChronoUnit.DAYS.between(started, now) val month = ChronoUnit.MONTHS.between(started, now) val years = ChronoUnit.YEARS.between(started, now) return when { years > 0 -> "$years лет" month > 0 -> "$month мес." days > 9 -> "$days дней" days > 0 -> "$days дн. ${hours%24} ч." hours > 0 -> "$hours ч. ${minutes%60} мин." minutes > 5 -> "$minutes мин. ${seconds%60} сек." minutes >= 1 -> "$minutes минут" else -> "Молодожёны" } } fun getTimeLocal(time: Long): ZonedDateTime{ return Date(time).toInstant().atZone(moscowZone.toZoneId()) } fun testTime():Long{ return System.currentTimeMillis() } suspend fun telegramTreeFileFromID(userID: Long): TelegramFile.ByByteArray{ return try { FamilyTree.create(userID).let { TelegramFile.ByByteArray(it.toImage(), "$userID-tree.png") } }catch (e:Exception) { e.printStackTrace() TelegramFile.ByByteArray("Ошибка при создании семейного древа".toByteArray(), "error.png") } } inline fun <T> block(block:() -> T) : T { return block() }
0
Kotlin
0
0
235c1eb1add51fbf819231ad88ab8879222c97aa
3,817
TelegramBot
MIT License
src/main/kotlin/hashmap/easy/RansomNote.kt
jiahaoliuliu
747,189,993
false
{"Kotlin": 426555}
package arrayandlist.easy import junit.framework.Assert.assertFalse import junit.framework.Assert.assertTrue import org.junit.Test /** * Ransom Note * Harold is a kidnapper who wrote a ransom note, but now he is worried it will be traced back to him * through his handwriting. He found a magazine and wants to know if he can cut out whole words from it * and use them to create an untraceable replica of his ransom note. The words in his note are case-sensitive * and he must use only whole words available in the magazine. He cannot use substrings or concatenation * to create the words he needs. * Given the words in the magazine and the words in the ransom note, print Yes if he can replicate his ransom * note exactly using whole words from the magazine; otherwise, print No. * Example: * managezine = "attack at dawn" note = "Attack at dawn" * The magazine has all the right words, but there is a case mismatch. The answer is No. * * Check: Problem not in Leet code, but in Hacker rank */ class RansomNote { /** * Initial thought * We need to find if the magazine contains all the words from note. So in the dictionary * we need to put all the words of note, and then check it with magazine. * * Note the words from note could be repeated. In this case, we just need one of them. So * we compare the occurrences and check if the magazine has at least one of the each * word required by note * */ private fun checkMagazine(magazine: Array<String>, note: Array<String>): Boolean { // Corner case if (note.isEmpty()) { println("Yes") return true } // Index all the elements in the note with hashmap val dictionary = HashMap<String, Int>() note.forEach{ var occurrences = dictionary.getOrDefault(it, 0) dictionary[it] = ++occurrences } // Extract the ocurrences in the magazine magazine.forEach { val occurrences = dictionary.get(it) // If the dictionary has it occurrences?.let { occurrencesNotNull -> dictionary[it] = occurrencesNotNull - 1 } } dictionary.forEach {(_, v) -> if (v > 0) { return false } } return true } @Test fun test1() { // Given val magazine = arrayOf("give", "me", "one", "grand", "today", "night") val note = arrayOf("give", "one", "grand", "today") // When val result = checkMagazine(magazine, note) // Then assertTrue(result) } @Test fun test2() { // Given val magazine = arrayOf("ive", "got", "a", "lovely", "bunch", "of", "coconuts") val note = arrayOf("ive", "got", "some", "coconuts") // When val result = checkMagazine(magazine, note) // Then assertFalse(result) } }
0
Kotlin
0
0
bbfa01d01896f108858790e94f049d22c0b76bcd
2,976
CodingExercises
Apache License 2.0
prime-router/src/test/kotlin/FileSettingsTests.kt
Anilm19
357,812,403
true
{"Kotlin": 750852, "HCL": 81464, "HTML": 64595, "Shell": 33722, "CSS": 30875, "Liquid": 24818, "PLpgSQL": 12858, "Python": 5030, "JavaScript": 3086, "Dockerfile": 2437}
package gov.cdc.prime.router import java.io.ByteArrayInputStream import java.time.ZoneId import java.time.ZonedDateTime import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFails import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue import kotlin.test.fail class FileSettingsTests { private val receiversYaml = """ --- # Arizona PHD - name: phd1 description: Arizona PHD jurisdiction: STATE stateCode: AZ receivers: - name: elr organizationName: phd1 topic: test jurisdictionalFilter: [ "matches(a, 1)"] deidentify: false translation: type: CUSTOM schemaName: one format: CSV """.trimIndent() private val sendersAndReceiversYaml = """ --- # Arizona PHD - name: phd1 description: Arizona PHD jurisdiction: STATE stateCode: AZ receivers: - name: elr organizationName: phd1 topic: test jurisdictionalFilter: [ "matches(a, 1)"] deidentify: false timing: operation: MERGE numberPerDay: 24 initialTime: 00:00 timeZone: ARIZONA translation: type: CUSTOM schemaName: one format: CSV senders: - name: sender organizationName: phd1 topic: topic schemaName: one format: CSV """.trimIndent() @Test fun `test loading a receiver`() { val settings = FileSettings() settings.loadOrganizations(ByteArrayInputStream(receiversYaml.toByteArray())) val result = settings.findReceiver("phd1.elr") assertEquals(1, result?.jurisdictionalFilter?.size) } @Test fun `test loading a sender and receiver`() { val settings = FileSettings() settings.loadOrganizations(ByteArrayInputStream(sendersAndReceiversYaml.toByteArray())) val result = settings.findSender("phd1.sender") assertEquals("sender", result?.name) } @Test fun `test loading a single organization`() { val settings = FileSettings().loadOrganizations( DeepOrganization( name = "single", description = "blah blah", jurisdiction = Organization.Jurisdiction.FEDERAL, stateCode = null, countyName = null, senders = listOf(), receivers = listOf( Receiver("elr", "single", "topic", "schema") ) ) ) val result = settings.findReceiver("single.elr") ?: fail("Expected to find service") assertEquals("elr", result.name) } @Test fun `test loading local settings`() { val settings = FileSettings(FileSettings.defaultSettingsDirectory, "-local") assertNotNull(settings) } @Test fun `test loading test settings`() { val settings = FileSettings(FileSettings.defaultSettingsDirectory, "-test") assertNotNull(settings) } @Test fun `test loading prod settings`() { val settings = FileSettings(FileSettings.defaultSettingsDirectory, "-prod") assertNotNull(settings) } @Test fun `test nextBatchTime`() { val timing = Receiver.Timing( Receiver.BatchOperation.NONE, 24, "04:05", USTimeZone.ARIZONA ) // AZ is -7:00 from UTC assertTrue(timing.isValid()) // The result should be in the AZ timezone val now1 = ZonedDateTime.of(2020, 10, 2, 0, 0, 0, 999, ZoneId.of("UTC")).toOffsetDateTime() val expected1 = ZonedDateTime.of(2020, 10, 1, 17, 5, 0, 0, ZoneId.of("US/Arizona")).toOffsetDateTime() val actual1 = timing.nextTime(now1) assertEquals(expected1, actual1) // Test that the minDuration comes into play val now2 = ZonedDateTime.of(2020, 10, 1, 0, 5, 0, 0, ZoneId.of("UTC")).toOffsetDateTime() val actual2 = timing.nextTime(now2) val expected2 = ZonedDateTime.of(2020, 9, 30, 18, 5, 0, 0, ZoneId.of("US/Arizona")).toOffsetDateTime() assertEquals(expected2, actual2) } @Test fun `test find sender`() { val settings = FileSettings(FileSettings.defaultSettingsDirectory) val sender = settings.findSender("simple_report") assertNotNull(sender) val sender2 = settings.findSender("simple_report.default") assertNotNull(sender2) } @Test fun `test find receiver`() { val settings = FileSettings() val org1 = DeepOrganization( "test", "test", Organization.Jurisdiction.FEDERAL, null, null, receivers = listOf( Receiver("service1", "test", "topic1", "schema1"), ) ) settings.loadOrganizationList((listOf(org1))) assertEquals(org1.name, settings.findOrganization("test")?.name) assertEquals(org1.receivers[0].name, settings.findReceiver(fullName = "test.service1")?.name) assertNull(settings.findReceiver(fullName = "service1")) } @Test fun `test duplicate receiver name`() { val settings = FileSettings() val org1 = DeepOrganization( "test", "test", Organization.Jurisdiction.FEDERAL, null, null, receivers = listOf( Receiver("service1", "test", "topic1", "schema1"), Receiver("service1", "test", "topic1", "schema1") ) ) assertFails { settings.loadOrganizationList(listOf(org1)) } } }
0
null
0
0
2cd204474aceeaeaea721e96038eebd46672d909
6,124
prime-data-hub
Apache License 2.0
src/aoc2023/Day08.kt
dayanruben
433,250,590
false
{"Kotlin": 73462}
package aoc2023 import checkValue import readInput fun main() { val (year, day) = "2023" to "Day08" fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b) fun lcm(a: Long, b: Long): Long = (a * b) / gcd(a, b) fun List<Long>.lcm() = this.reduce { acc, n -> lcm(acc, n) } fun parse(input: List<String>): Pair<String, Map<String, Pair<String, String>>> { val inst = input.first() val networkMap = input.drop(2).associate { line -> val (node, lr) = line.split(" = ") val (left, right) = lr.drop(1).dropLast(1).split(", ") node to (left to right) } return inst to networkMap } fun minSteps(inst: String, networkMap: Map<String, Pair<String, String>>, start: String, isEnd: (String) -> Boolean): Long { var steps = 0 var current = start while (!isEnd(current)) { current = when (inst[steps % inst.length]) { 'L' -> networkMap[current]?.first ?: "" else -> networkMap[current]?.second ?: "" } steps++ } return steps.toLong() } fun part1(input: List<String>): Long { val (inst, networkMap) = parse(input) return minSteps(inst, networkMap, "AAA") { it == "ZZZ" } } fun part2(input: List<String>): Long { val (inst, networkMap) = parse(input) return networkMap.keys.filter { it.last() == 'A' }.map { start -> minSteps(inst, networkMap, start) { it.last() == 'Z' } }.lcm() } val testInput1 = readInput(name = "${day}_p1_test1", year = year) val testInput2 = readInput(name = "${day}_p1_test2", year = year) val testInput3 = readInput(name = "${day}_p2_test", year = year) val input = readInput(name = day, year = year) checkValue(part1(testInput1), 2) checkValue(part1(testInput2), 6) println(part1(input)) checkValue(part2(testInput3), 6) println(part2(input)) }
1
Kotlin
2
30
68a2f97b0bb535094df6369bb590a71f05bfc163
1,987
aoc-kotlin
Apache License 2.0
core/storage/src/main/java/com/elnfach/storage/ThemeSettingStorageImpl.kt
elnfach
649,768,901
false
{"Kotlin": 257352}
package com.elnfach.storage import android.content.Context import com.elnfach.model.ThemeOption import com.elnfach.storage.repository.ThemeSettingStorage const val SHARED_PREFS_THEME_SETTING = "shared_prefs_theme_setting" const val KEY_THEME_SETTING = "theme_setting" class ThemeSettingStorageImpl(context: Context) : ThemeSettingStorage { private val sharedPreferences = context.getSharedPreferences(SHARED_PREFS_THEME_SETTING, Context.MODE_PRIVATE) override fun save(theme: ThemeOption) { sharedPreferences.edit().putString(KEY_THEME_SETTING, theme.value).apply() } override fun get(): com.elnfach.model.ThemeOption { return com.elnfach.model.ThemeOption( sharedPreferences.getString( KEY_THEME_SETTING, "DEFAULT" ) ?: "DEFAULT" ) } }
0
Kotlin
0
0
99a118ade7691bcabb1af6cabaa652476b20a68d
852
ArtHouse
Apache License 2.0
libraries/di/src/commonMain/kotlin/catchup/di/Scopes.kt
ZacSweers
57,029,623
false
{"Kotlin": 699458, "Java": 11152, "Shell": 7329}
package catchup.di import javax.inject.Scope import kotlin.annotation.AnnotationRetention.RUNTIME import kotlin.reflect.KClass abstract class AppScope private constructor() @Scope @Retention(RUNTIME) annotation class SingleIn(val scope: KClass<*>)
37
Kotlin
201
1,980
3ac348452590f8d9ba02c3e6163fb210df9e37f4
251
CatchUp
Apache License 2.0
client/android/divkit-demo-app/src/main/java/com/yandex/divkit/demo/permissions/PermissionRequest.kt
divkit
523,491,444
false
{"Kotlin": 7327303, "Swift": 5164616, "Svelte": 1148832, "TypeScript": 912803, "Dart": 630920, "Python": 536031, "Java": 507940, "JavaScript": 152546, "CSS": 37870, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8895, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38}
package com.yandex.divkit.demo.permissions import android.Manifest import android.os.Build import androidx.annotation.RequiresApi import androidx.annotation.StringRes /** * Unified representation of permission * * Should be passed to PermissionManager, when need to request permissions. */ data class PermissionRequest( val requestCode: Int, val requiredPermissions: List<Permission>, val optionalPermissions: List<Permission> = emptyList(), @StringRes val explainMessageResId: Int = 0, val explainMessage: String? = null, ) // For java, which lacks named arguments and fast list builders class PermissionRequestBuilder { private var requestCode = -1 private val requiredPermissions = mutableListOf<Permission>() private val optionalPermissions = mutableListOf<Permission>() @StringRes private var explainMessageResId = 0 private var explainMessage: String? = null fun requestCode(requestCode: Int): PermissionRequestBuilder { this.requestCode = requestCode return this } fun requiredPermission(permission: Permission): PermissionRequestBuilder { requiredPermissions.add(permission) return this } fun optionalPermission(permission: Permission): PermissionRequestBuilder { optionalPermissions.add(permission) return this } fun explainMessageResId(@StringRes explainMessageResId: Int): PermissionRequestBuilder { this.explainMessageResId = explainMessageResId return this } fun explainMessage(explainMessage: String): PermissionRequestBuilder { this.explainMessage = explainMessage return this } fun build() = PermissionRequest( requestCode = requestCode.takeUnless { it == -1 } ?: throw IllegalArgumentException("requestCode is required"), requiredPermissions = requiredPermissions.toList(), optionalPermissions = optionalPermissions.toList(), explainMessageResId = explainMessageResId, explainMessage = explainMessage ) } enum class Permission(val permissionString: String) { ACCESS_COARSE_LOCATION(Manifest.permission.ACCESS_COARSE_LOCATION), ACCESS_FINE_LOCATION(Manifest.permission.ACCESS_FINE_LOCATION), // Required by SearchApp for permission URI handling. @Suppress("unused") @RequiresApi(Build.VERSION_CODES.Q) ACCESS_BACKGROUND_LOCATION(Manifest.permission.ACCESS_BACKGROUND_LOCATION), RECORD_AUDIO(Manifest.permission.RECORD_AUDIO), READ_CONTACTS(Manifest.permission.READ_CONTACTS), CALL_PHONE(Manifest.permission.CALL_PHONE), READ_EXTERNAL_STORAGE(Manifest.permission.READ_EXTERNAL_STORAGE), WRITE_EXTERNAL_STORAGE(Manifest.permission.WRITE_EXTERNAL_STORAGE), CAMERA(Manifest.permission.CAMERA), READ_PHONE_STATE(Manifest.permission.READ_PHONE_STATE), ; companion object { fun find(permissionString: String) = values().find { it.permissionString == permissionString } } }
5
Kotlin
128
2,240
dd102394ed7b240ace9eaef9228567f98e54d9cf
3,029
divkit
Apache License 2.0
app/src/main/kotlin/me/tylerbwong/stack/ui/bookmarks/BookmarksViewModel.kt
adarshgumashta
300,819,766
true
{"Kotlin": 374878}
package me.tylerbwong.stack.ui.bookmarks import androidx.hilt.lifecycle.ViewModelInject import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import me.tylerbwong.stack.api.model.Question import me.tylerbwong.stack.api.service.QuestionService import me.tylerbwong.stack.data.auth.AuthRepository import me.tylerbwong.stack.data.repository.SiteRepository import me.tylerbwong.stack.ui.BaseViewModel // TODO Fetch bookmarks from QuestionDao for offline class BookmarksViewModel @ViewModelInject constructor( private val authRepository: AuthRepository, private val siteRepository: SiteRepository, private val questionService: QuestionService ) : BaseViewModel() { internal val bookmarks: LiveData<List<Question>> get() = mutableBookmarks private val mutableBookmarks = MutableLiveData<List<Question>>() private val isAuthenticated: Boolean get() = authRepository.isAuthenticated.value ?: false internal val siteLiveData: LiveData<String> get() = siteRepository.siteLiveData internal fun fetchBookmarks() { if (isAuthenticated) { launchRequest { mutableBookmarks.value = questionService.getBookmarks().items } } } }
0
null
0
0
b48b73a7d600e66f40dd5f07a9c1f04996a1ef0e
1,256
stack
Apache License 2.0
organization-service/src/main/kotlin/com/service/organizationservice/repository/OrganizationRepository.kt
marioluciano
395,477,997
false
null
package com.service.organization.repository import com.service.organization.model.Organization import io.micronaut.configuration.hibernate.jpa.scope.CurrentSession import io.micronaut.spring.tx.annotation.Transactional import javax.inject.Singleton import javax.persistence.EntityManager import javax.persistence.PersistenceContext @Singleton open class OrganizationRepository( @param:CurrentSession @field:PersistenceContext val entityManager: EntityManager ) { @Transactional open fun add(organization: Organization): Organization { entityManager.persist(organization) return organization } @Transactional(readOnly = true) open fun findById(id: Long): Organization = entityManager.find(Organization::class.java, id) @Transactional(readOnly = true) open fun findAll(): List<Organization> = entityManager.createQuery("SELECT o FROM Organization o").resultList as List<Organization> }
0
Kotlin
0
0
9d176c0511741b111755c36915d13f773fc85626
973
kotlin-microservice
Apache License 2.0
products/src/androidTest/java/com/demo/minnies/shop/data/repos/ProductsRepoImplTest.kt
jsonkile
572,488,327
false
null
package com.demo.minnies.shop.data.repos import com.demo.minnies.database.models.Category import com.demo.minnies.database.models.Product import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.first import kotlinx.coroutines.test.runTest import org.junit.Assert import org.junit.Before import org.junit.Rule import org.junit.Test import javax.inject.Inject @OptIn(ExperimentalCoroutinesApi::class) @HiltAndroidTest internal class ProductsRepoImplTest { @get:Rule val hiltAndroidRule = HiltAndroidRule(this) @Inject lateinit var shopRepoRoomImpl: ProductsRepoRoomImpl @Before fun setup() { hiltAndroidRule.inject() } @Test fun getAllItems_ReturnsAllItems() = runTest { val currentSize = shopRepoRoomImpl.getAllItems().first().size shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0 ) ) shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0 ) ) Assert.assertEquals(currentSize + 2, shopRepoRoomImpl.getAllItems().first().size) } @Test fun addItem_SuccessfullyAddsItem() = runTest { val currentSize = shopRepoRoomImpl.getAllItems().first().size shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0 ) ) shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0 ) ) Assert.assertEquals(currentSize + 2, shopRepoRoomImpl.getAllItems().first().size) } @Test fun getProductById_ReturnsCorrectProduct() = runTest { val id = shopRepoRoomImpl.addItem( Product( name = "Happy", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0 ) ) Assert.assertEquals("Happy", shopRepoRoomImpl.getProductById(id.toInt()).first()?.name) } @Test fun getFeaturedItems_ReturnsFeaturedItems() = runTest { val currentFeaturedListSize = shopRepoRoomImpl.getFeaturedItems().first().size shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0, featured = true ) ) shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0, featured = false ) ) shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0, featured = true ) ) Assert.assertEquals( currentFeaturedListSize + 2, shopRepoRoomImpl.getFeaturedItems().first().size ) } @Test fun getItemsByCategory_ReturnsCorrectItems() = runTest { val currentTopsListSize = shopRepoRoomImpl.getItemsByCategory(Category.Top).first().size shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Top, price = 0.0, featured = true ) ) shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Top, price = 0.0, featured = false ) ) shopRepoRoomImpl.addItem( Product( name = "", image = "", description = "", sizes = emptyList(), category = Category.Kicks, price = 0.0, featured = true ) ) Assert.assertEquals( currentTopsListSize + 2, shopRepoRoomImpl.getItemsByCategory(Category.Top).first().size ) } }
0
Kotlin
0
0
59ac66b66f3e5122b1cfd60f637af223f2aca53d
5,315
Minnies
MIT License
src/main/java/com/bukowiecki/breakpoints/ui/ManageTagsDialog.kt
marcin-bukowiecki
401,104,358
false
null
/* * Copyright 2021 <NAME>. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package com.bukowiecki.breakpoints.ui import com.bukowiecki.breakpoints.controller.TagsController import com.bukowiecki.breakpoints.tagging.TagsProperties import com.bukowiecki.breakpoints.utils.BreakpointManagerBundle import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.openapi.ui.DialogWrapper import com.intellij.psi.PsiFile import com.intellij.ui.JBSplitter import com.intellij.uiDesigner.core.GridConstraints import com.intellij.uiDesigner.core.GridLayoutManager import com.intellij.util.ui.JBUI import com.intellij.xdebugger.breakpoints.XLineBreakpoint import java.awt.BorderLayout import javax.swing.JButton import javax.swing.JComponent import javax.swing.JPanel /** * @author <NAME> */ class ManageTagsDialog(val breakpoint: XLineBreakpoint<*>, val editor: Editor, val psiFile: PsiFile, val project: Project, private val saveCallback: () -> Unit = {}) : DialogWrapper(project) { private val myTags = mutableListOf<TagRowPanel>() private val myController = TagsController(this) init { val instance = TagsProperties.getInstance(project) breakpoint.sourcePosition?.let { sourcePosition -> instance.findState(sourcePosition).let { it.tags.forEachIndexed { i, tag -> val tagPanel = if (i == 0) { TagRowPanel(3, myController) } else { TagRowPanel(2, myController) } tagPanel.setKey(tag.key) tagPanel.setValue(tag.value) myTags.add(tagPanel) } } } super.init() setOKButtonText(BreakpointManagerBundle.message("breakpoints.tags.manage.save")) title = BreakpointManagerBundle.message("breakpoints.tags.manage.title") myController.validate() } override fun doOKAction() { if (myController.validate()) { super.doOKAction() myController.save() saveCallback.invoke() } } fun getTags() = myTags override fun createCenterPanel(): JComponent { val mainPanel = JBUI.Panels.simplePanel() val splitPane = JBSplitter(true, 0.9f) val footerPanel = JPanel(GridLayoutManager(1, 1)) val addTagButton = JButton("Add Tag") val gridConstraints = GridConstraints() gridConstraints.row = 0 gridConstraints.column = 0 gridConstraints.anchor = GridConstraints.ANCHOR_CENTER footerPanel.add(addTagButton, gridConstraints, -1) addTagButton.addActionListener { addRow(splitPane) buildTagsPanel(splitPane) } if (getTags().isEmpty()) { addRow(splitPane) //first row } buildTagsPanel(splitPane) splitPane.secondComponent = footerPanel mainPanel.add(splitPane, BorderLayout.CENTER) return mainPanel } private fun addRow(splitPane: JBSplitter) { val rowPanel = if (getTags().size == 0) { TagRowPanel(3, myController) } else { TagRowPanel(2, myController) } myTags.add(rowPanel) rowPanel.getRemoveButton().addActionListener { if (myTags.isNotEmpty()) { if (myTags.first() != rowPanel) { myTags.remove(rowPanel) } buildTagsPanel(splitPane) } } } private fun buildTagsPanel(splitPane: JBSplitter) { val tagRowsPanel = JPanel(GridLayoutManager(myTags.size, 1)) for ((i, tag) in myTags.withIndex()) { val gridConstraints = GridConstraints() gridConstraints.row = i gridConstraints.column = 0 gridConstraints.anchor = GridConstraints.ANCHOR_NORTH tagRowsPanel.add( tag, gridConstraints, -1 ) } splitPane.firstComponent = tagRowsPanel splitPane.validate() splitPane.repaint() } override fun getDimensionServiceKey(): String? { return javaClass.name } fun enableSave() { okAction.isEnabled = true } fun disableSave() { okAction.isEnabled = false } }
0
Kotlin
0
2
a6f5005b34894980bd49c04a61387cca79877307
4,558
breakpoint-manager-plugin
Apache License 2.0
stem-plugin/src/main/java/com/likethesalad/stem/utils/TemplatesProviderLoader.kt
LikeTheSalad
216,664,268
false
{"Kotlin": 167175, "Java": 3041, "Shell": 65}
package com.likethesalad.stem.utils import com.likethesalad.android.templates.common.utils.CommonConstants import com.likethesalad.android.templates.provider.api.TemplatesProvider import io.github.classgraph.ClassGraph import io.github.classgraph.ScanResult import java.io.File import java.net.URLClassLoader object TemplatesProviderLoader { @Suppress("UNCHECKED_CAST") fun load(jars: List<File>): List<TemplatesProvider> { if (jars.isEmpty()) { return emptyList() } val scanResult = scanJars(jars.toSet()) return scanResult.use { result -> result.getClassesImplementing(TemplatesProvider::class.java).loadClasses().map { it.newInstance() } } as List<TemplatesProvider> } private fun scanJars(jarFiles: Set<File>): ScanResult { return ClassGraph() .acceptPackages(CommonConstants.PROVIDER_PACKAGE_NAME) .overrideClassLoaders(createLocalClassloader(jarFiles)) .scan() } private fun createLocalClassloader(jarFiles: Set<File>): ClassLoader { val urls = jarFiles.map { it.toURI().toURL() } return URLClassLoader(urls.toTypedArray(), javaClass.classLoader) } }
3
Kotlin
12
182
3579c0527f6795f94538ab242ddf721cd72e0756
1,242
android-stem
MIT License
feature-governance-impl/src/main/java/io/novafoundation/nova/feature_governance_impl/presentation/track/TrackModel.kt
novasamatech
415,834,480
false
{"Kotlin": 8137060, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_governance_impl.presentation.track import io.novafoundation.nova.common.utils.images.Icon import io.novafoundation.nova.common.utils.letOrHide import io.novafoundation.nova.feature_governance_impl.R import io.novafoundation.nova.feature_governance_impl.presentation.view.NovaChipView class TracksModel( val tracks: List<TrackModel>, val overview: String ) class TrackModel(val name: String, val icon: Icon) fun NovaChipView.setTrackModel(trackModel: TrackModel?) = letOrHide(trackModel) { track -> setText(track.name) setIcon(track.icon) setIconTint(R.color.chip_icon) }
12
Kotlin
6
9
618357859a4b7af95391fc0991339b78aff1be82
634
nova-wallet-android
Apache License 2.0
app/src/main/java/com/example/android/navigation/MainActivity.kt
Sherlockqq
397,250,073
false
null
/* * Copyright 2018, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.navigation import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.findNavController import androidx.navigation.ui.NavigationUI import com.example.android.navigation.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var drawerLayout: DrawerLayout override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.i("MainFragment", "onCreate called") val binding = DataBindingUtil.setContentView<ActivityMainBinding>( this, R.layout.activity_main) drawerLayout = binding.drawerLayout val navController = this.findNavController(R.id.myNavHostFragment) NavigationUI.setupActionBarWithNavController(this,navController) NavigationUI.setupWithNavController(binding.navView, navController) NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout) } override fun onSupportNavigateUp(): Boolean { val navController = this.findNavController(R.id.myNavHostFragment) return NavigationUI.navigateUp(navController, drawerLayout) } override fun onStart() { super.onStart() Log.i("MainFragment", "onStart called") } override fun onResume() { super.onResume() Log.i("MainFragment", "onResume called") } override fun onPause() { super.onPause() Log.i("MainFragment", "onPause called") } override fun onStop() { super.onStop() Log.i("MainFragment", "onStop called") } override fun onDestroy() { super.onDestroy() Log.i("MainFragment", "onDestroy called") } }
0
Kotlin
0
0
989ab9fe56c762484cb44ac17da785a86d7f7a63
2,490
AndroidTrivia-Starter
Apache License 2.0
vortex/src/main/java/com/yazan98/vortex/base/interactor/VortexInteractor.kt
TrendingTechnology
193,901,833
false
null
package com.yazan98.vortex.base.interactor import com.yazan98.vortex.base.platform.BaseVortex import com.yazan98.vortex.base.rx.VortexThreadProvider /** * Copyright (C) 2019 Yazan Tarifi * Licensed under the Apache License, Version 2.0 * * Created By : Yazan Tarifi * Date : 6/19/2019 * Time : 2:50 PM */ abstract class VortexInteractor<R, P> : InteractorImplementor<R, P> { init { BaseVortex().initPlatform() } abstract class SchedulerInteractor<R, P> : VortexInteractor<R, P>() { abstract fun getThreadProvider(): VortexThreadProvider } //TODO: Implement this when make processor abstract class ValidatorInteractor<R, P> : VortexInteractor<R, P>() abstract class ReactiveInteractor<R, P, S> : VortexInteractor<R, P>() { abstract var subscriber: S } }
0
Kotlin
0
0
fd7782ed0038661bc7004fd0782978c1988a463e
824
Vortex
Apache License 2.0
src/main/kotlin/com/mygomii/firebasenotificationweb/data/models/TokenReq.kt
mygomii
861,548,117
false
{"Kotlin": 1845}
package com.mygomii.firebasenotificationweb.data.models data class TokenReq( val token: String, )
0
Kotlin
0
0
05ae7a3fc5ef5dce44de74f70a7114659799472f
102
firebase-notification-web
Apache License 2.0
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/RutingAvInntektsmeldingOppgaverTest.kt
navikt
193,907,367
false
null
package no.nav.helse.spleis.e2e import java.util.UUID import no.nav.helse.EnableToggle import no.nav.helse.Toggle import no.nav.helse.februar import no.nav.helse.hendelser.Sykmeldingsperiode import no.nav.helse.hendelser.Søknad import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom import no.nav.helse.hendelser.til import no.nav.helse.januar import no.nav.helse.økonomi.Prosentdel.Companion.prosent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test internal class RutingAvInntektsmeldingOppgaverTest : AbstractEndToEndTest() { @Test fun `dersom vi mottar inntektsmelding før søknad skal det sendes et utsett_oppgave-event`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) val inntektsmeldingId = håndterInntektsmelding(listOf(1.januar til 16.januar)) assertEquals(listOf(inntektsmeldingId), observatør.utsettOppgaveEventer().map { it.hendelse }) } @Test fun `dersom inntektsmeldingen ikke treffer noen sykmeldinger skal det ikke sendes ut et utsett_oppgave-event`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.februar til 16.februar)) assertEquals(emptyList<UUID>(), observatør.utsettOppgaveEventer().map { it.hendelse }) } @Test fun `dersom inntektsmeldingen kommer etter søknad skal det ikke sendes ut et utsett_oppgave-event`() { // Utsettelse av oppgaveopprettelse blir da håndtert av vedtaksperiode_endret-event håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar)) assertEquals(emptyList<UUID>(), observatør.utsettOppgaveEventer().map { it.hendelse }) } @Test fun `dersom vi mottar inntektsmeldingen før vi har mottatt noen andre dokumenter skal det ikke sendes ut et utsett_oppgave-event`() { håndterInntektsmelding(listOf(1.februar til 16.februar)) assertEquals(emptyList<UUID>(), observatør.utsettOppgaveEventer().map { it.hendelse }) } @Test fun `dersom vi mottar inntektsmelding før søknad og søknaden feiler skal det opprettes oppgave for både søknad og inntektsmelding`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) val inntektsmeldingId = håndterInntektsmelding(listOf(1.januar til 16.januar)) val søknadId = håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), andreInntektskilder = listOf(Søknad.Inntektskilde(true, "FRILANSER"))) håndterInntektsmeldingReplay(inntektsmeldingId, 1.vedtaksperiode.id(ORGNUMMER)) assertEquals(listOf(søknadId, inntektsmeldingId), observatør.opprettOppgaveEvent().flatMap { it.hendelser }) assertEquals(listOf(1.vedtaksperiode.id(ORGNUMMER)), observatør.inntektsmeldingReplayEventer) } @Test fun `inntektsmelding replay av forkastede perioder skal kun be om replay for relevant vedtaksperiode`() { håndterSykmelding(Sykmeldingsperiode(1.januar(2017), 31.januar(2017), 100.prosent)) val søknadId1 = håndterSøknad(Sykdom(1.januar(2017), 31.januar(2017), 100.prosent)) val inntektsmeldingId1 = håndterInntektsmelding(listOf(1.januar(2017) til 16.januar(2017))) person.invaliderAllePerioder(hendelselogg, null) håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) val inntektsmeldingId2 = håndterInntektsmelding(listOf(1.januar til 16.januar)) val søknadId2 = håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), andreInntektskilder = listOf(Søknad.Inntektskilde(true, "FRILANSER"))) håndterInntektsmeldingReplay(inntektsmeldingId1, 2.vedtaksperiode.id(ORGNUMMER)) håndterInntektsmeldingReplay(inntektsmeldingId2, 2.vedtaksperiode.id(ORGNUMMER)) assertEquals(listOf(søknadId1, inntektsmeldingId1, søknadId2, inntektsmeldingId2), observatør.opprettOppgaveEvent().flatMap { it.hendelser }) assertEquals(listOf(1.vedtaksperiode.id(ORGNUMMER), 2.vedtaksperiode.id(ORGNUMMER)), observatør.inntektsmeldingReplayEventer) } @Test fun `dersom vi har en nærliggende utbetaling og vi mottar inntektsmelding før søknad og søknaden feiler - skal det opprettes oppgave i speilkøen i gosys`() { håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent)) håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent)) håndterInntektsmelding(listOf(1.januar til 16.januar)) håndterYtelser(1.vedtaksperiode) håndterVilkårsgrunnlag(1.vedtaksperiode) håndterYtelser(1.vedtaksperiode) håndterSimulering(1.vedtaksperiode) håndterUtbetalingsgodkjenning(1.vedtaksperiode) håndterUtbetalt() håndterSykmelding(Sykmeldingsperiode(7.februar, 28.februar, 100.prosent)) val inntektsmeldingId = håndterInntektsmelding(listOf(1.januar til 16.januar), førsteFraværsdag = 7.februar) val søknadId = håndterSøknad(Sykdom(7.februar, 28.februar, 100.prosent), andreInntektskilder = listOf(Søknad.Inntektskilde(true, "FRILANSER"))) håndterInntektsmeldingReplay(inntektsmeldingId, 2.vedtaksperiode.id(ORGNUMMER)) assertEquals(listOf(søknadId, inntektsmeldingId), observatør.opprettOppgaveForSpeilsaksbehandlereEvent().flatMap { it.hendelser }) } }
0
Kotlin
3
4
22fe9640780c8c8c13165c2efb0dfc4d96ba9965
5,420
helse-spleis
MIT License
tart/src/androidTest/java/tart/test/utilities/TestActivity.kt
square
407,688,593
false
null
package tart.test.utilities import android.app.Activity import android.os.Bundle import com.squareup.tart.test.R class TestActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.test) } }
6
Kotlin
5
146
07c573cd4c8bd1b84d63f93bafa3c52ce55d3cf1
283
tart
Apache License 2.0
ktap/src/test/kotlin/dev/fanie/ktap/fake/TypeMirrorFakes.kt
iFanie
266,369,610
false
null
package dev.fanie.ktap.fake import javax.lang.model.element.AnnotationMirror import javax.lang.model.type.TypeKind import javax.lang.model.type.TypeMirror import javax.lang.model.type.TypeVisitor import kotlin.reflect.KClass internal fun typeMirror( kind: TypeKind? = null, annotations: List<KClass<out Annotation>>? = null, annotationMirrors: List<AnnotationMirror>? = null, toString: String? = null ) = object : TypeMirror { override fun getKind(): TypeKind = kind!! override fun <R : Any?, P : Any?> accept(p0: TypeVisitor<R, P>?, p1: P): R = wontDo() override fun <A : Annotation> getAnnotationsByType(p0: Class<A>): Array<A> = wontDo() override fun <A : Annotation> getAnnotation(p0: Class<A>): A? = tryToFind(p0, annotations!!) override fun getAnnotationMirrors(): List<AnnotationMirror> = annotationMirrors!! override fun toString(): String = toString!! }
0
Kotlin
0
4
a7a1e0d506ee814fa1d11443ef8c97290a6f0f77
909
KTAP
Apache License 2.0
coroutines/src/main/kotlin/gridfs/MongoBucket.kt
cufyorg
502,485,629
false
null
/* * Copyright 2022-2023 cufy.org and meemer.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cufy.mongodb.gridfs import com.mongodb.reactivestreams.client.gridfs.GridFSBuckets import kotlinx.coroutines.channels.ClosedSendChannelException import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.toList import kotlinx.coroutines.reactive.asFlow import kotlinx.coroutines.reactive.awaitFirstOrNull import kotlinx.coroutines.reactive.awaitSingle import kotlinx.coroutines.reactive.collect import org.cufy.bson.* import org.cufy.bson.java.java import org.cufy.mongodb.* import org.cufy.mongodb.gridfs.internal.downloadToPublisher0 import org.cufy.mongodb.gridfs.internal.uploadFromPublisher0 import org.cufy.mongodb.gridfs.java.JavaMongoBucket import org.cufy.mongodb.gridfs.java.apply import org.cufy.mongodb.gridfs.java.kt import org.cufy.mongodb.java.kt import java.nio.ByteBuffer /* ============= ------------------ ============= */ /** * A generic-free coroutine dependant wrapper for * a mongodb bucket. * * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket * @author LSafer * @since 2.0.0 */ interface MongoBucket { /** * The wrapped bucket. */ val java: JavaMongoBucket } /** * Create a new GridFS bucket with the default `fs` bucket name. * * @param database the database instance to use with GridFS. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBuckets.create * @since 2.0.0 */ fun createMongoBucket(database: MongoDatabase): MongoBucket { return GridFSBuckets.create(database.java).kt } /** * Create a new GridFS bucket with a custom bucket name. * * @param database the database instance to use with GridFS. * @param name the custom bucket name to use. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBuckets.create * @since 2.0.0 */ fun createMongoBucket(database: MongoDatabase, name: String): MongoBucket { return GridFSBuckets.create(database.java, name).kt } /* ============= ------------------ ============= */ /** * The bucket name. * * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.getBucketName * @since 2.0.0 */ val MongoBucket.bucketName: String get() = java.bucketName /** * Sets the chunk size in bytes. Defaults to 255. * * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.getChunkSizeBytes * @since 2.0.0 */ val MongoBucket.chunkSizeBytes: Int get() = java.chunkSizeBytes /** * Get the write concern for the GridFSBucket. * * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.getWriteConcern * @since 2.0.0 */ val MongoBucket.writeConcern: WriteConcern get() = java.writeConcern.kt /** * Get the read preference for the GridFSBucket. * * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.getReadPreference * @since 2.0.0 */ val MongoBucket.readPreference: ReadPreference get() = java.readPreference /** * Get the read concern for the GridFSBucket. * * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.getReadConcern * @since 2.0.0 */ val MongoBucket.readConcern: ReadConcern get() = java.readConcern.kt /* ============= ------------------ ============= */ /** * Uploads the chunks sent to the given [channel] to a GridFS bucket. * * Receives the chunks from [channel] and uploads it * as chunks in the `chunks` collection. * After all the chunks have been uploaded, it creates a files * collection document for [filename] in the `files` collection. * * **Note: This function will suspend until the file is done uploading.** * * Closing [channel] will only stop the receiving the chunks from it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param filename the filename. * @param metadata user provided data for the `metadata` field of the files collection document. * @param channel the channel providing the file data. * @param options the upload options. * @return the id of the uploaded file. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.uploadFromPublisher * @since 2.0.0 */ suspend fun MongoBucket.upload( channel: ReceiveChannel<ByteBuffer>, filename: String, metadata: BsonDocument = BsonDocument.Empty, options: UploadOptions = UploadOptions(), session: ClientSession? = null ): BsonObjectId { val publisher = java.uploadFromPublisher0(channel.receiveAsFlow(), filename, metadata, options, session) return publisher.awaitSingle().bson } /** * Uploads the chunks sent to the given [channel] to a GridFS bucket. * * Receives the chunks from [channel] and uploads it * as chunks in the `chunks` collection. * After all the chunks have been uploaded, it creates a files * collection document for [filename] in the `files` collection. * * **Note: This function will suspend until the file is done uploading.** * * Closing [channel] will only stop the receiving the chunks from it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param filename the filename. * @param metadata user provided data for the `metadata` field of the files collection document. * @param channel the channel providing the file data. * @param options the upload options. * @return the id of the uploaded file. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.uploadFromPublisher * @since 2.0.0 */ suspend fun MongoBucket.upload( channel: ReceiveChannel<ByteBuffer>, filename: String, metadata: BsonDocumentBlock, session: ClientSession? = null, options: UploadOptions.() -> Unit = {} ) = upload(channel, filename, BsonDocument(metadata), UploadOptions(options), session) // /** * Uploads the chunks sent to the given [channel] to a GridFS bucket. * * Receives the chunks from [channel] and uploads it * as chunks in the `chunks` collection. * After all the chunks have been uploaded, it creates a files * collection document for [filename] in the `files` collection. * * **Note: This function will suspend until the file is done uploading.** * * Closing [channel] will only stop the receiving the chunks from it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param id the custom id value of the file. * @param filename the filename. * @param metadata user provided data for the `metadata` field of the files collection document. * @param channel the channel providing the file data. * @param options the upload options. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.uploadFromPublisher * @since 2.0.0 */ suspend fun MongoBucket.upload( channel: ReceiveChannel<ByteBuffer>, filename: String, id: BsonElement, metadata: BsonDocument = BsonDocument.Empty, options: UploadOptions = UploadOptions(), session: ClientSession? = null ) { val publisher = java.uploadFromPublisher0(channel.receiveAsFlow(), filename, id, metadata, options, session) publisher.awaitFirstOrNull() } /** * Uploads the chunks sent to the given [channel] to a GridFS bucket. * * Receives the chunks from [channel] and uploads it * as chunks in the `chunks` collection. * After all the chunks have been uploaded, it creates a files * collection document for [filename] in the `files` collection. * * **Note: This function will suspend until the file is done uploading.** * * Closing [channel] will only stop the receiving the chunks from it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param id the custom id value of the file. * @param filename the filename. * @param metadata user provided data for the `metadata` field of the files collection document. * @param channel the channel providing the file data. * @param options the upload options. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.uploadFromPublisher * @since 2.0.0 */ suspend fun MongoBucket.upload( channel: ReceiveChannel<ByteBuffer>, filename: String, id: BsonElement, metadata: BsonDocumentBlock, session: ClientSession? = null, options: UploadOptions.() -> Unit = {} ) = upload(channel, filename, id, BsonDocument(metadata), UploadOptions(options), session) /* ============= ------------------ ============= */ /** * Downloads the contents of the stored file specified by [id] * to the given [channel]. * * **Note: this function will suspend until the file is done downloading.** * * Closing [channel] will only stop the sending of the chunks through it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param id the id of the file to be downloaded. * @param channel the channel receiving the file data. * @param options the download options. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.downloadToPublisher * @since 2.0.0 */ suspend fun MongoBucket.download( channel: SendChannel<ByteBuffer>, id: BsonElement, options: DownloadOptions = DownloadOptions(), session: ClientSession? = null ): MongoFile { val publisher = java.downloadToPublisher0(id, options, session) try { publisher.collect { channel.send(it) } } catch (_: ClosedSendChannelException) { // it is completely ok to close mid-download } return publisher.gridFSFile.awaitSingle().kt } /** * Downloads the contents of the stored file specified by [id] * to the given [channel]. * * **Note: this function will suspend until the file is done downloading.** * * Closing [channel] will only stop the sending of the chunks through it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param id the id of the file to be downloaded. * @param channel the channel receiving the file data. * @param options the download options. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.downloadToPublisher * @since 2.0.0 */ suspend fun MongoBucket.download( channel: SendChannel<ByteBuffer>, id: BsonElement, session: ClientSession? = null, options: DownloadOptions.() -> Unit ) = download(channel, id, DownloadOptions(options), session) // /** * Downloads the contents of the stored file specified by [filename] and [revision] * to the given [channel]. * * **Note: this function will suspend until the file is done downloading.** * * Closing [channel] will only stop the sending of the chunks through it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param filename the name of the file to be downloaded. * @param revision the revision of the file to be downloaded. * @param channel the channel receiving the file data. * @param options the download options. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.downloadToPublisher * @since 2.0.0 */ suspend fun MongoBucket.download( channel: SendChannel<ByteBuffer>, filename: String, options: DownloadOptions = DownloadOptions(), revision: FileRevision = FileRevision.Latest, session: ClientSession? = null ): MongoFile { val publisher = java.downloadToPublisher0(filename, options, revision, session) try { publisher.collect { channel.send(it) } } catch (_: ClosedSendChannelException) { // it is completely ok to close mid-download } return publisher.gridFSFile.awaitSingle().kt } /** * Downloads the contents of the stored file specified by [filename] and [revision] * to the given [channel]. * * **Note: this function will suspend until the file is done downloading.** * * Closing [channel] will only stop the sending of the chunks through it * and won't cause the invocation of this function to fail. * * @param session the client session with which to associate this operation. * @param filename the name of the file to be downloaded. * @param revision the revision of the file to be downloaded. * @param channel the channel receiving the file data. * @param options the download options. * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.downloadToPublisher * @since 2.0.0 */ suspend fun MongoBucket.download( channel: SendChannel<ByteBuffer>, filename: String, revision: FileRevision = FileRevision.Latest, session: ClientSession? = null, options: DownloadOptions.() -> Unit ) = download(channel, filename, DownloadOptions(options), revision, session) /* ============= ------------------ ============= */ /** * Finds all documents in the collection that match the filter. * * Below is an example of filtering against the filename and some nested metadata that can also be stored along with the file data: * * ```kotlin * find({ * "filename" by "mongodb.png" * "metadata.contentType" by "image/png" * }) * ``` * * @param session the client session with which to associate this operation. * @param filter the query filter. * @return a list containing the found files. * @since 2.0.0 * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.find */ suspend fun MongoBucket.find( filter: BsonDocument = BsonDocument.Empty, options: BucketFindOptions = BucketFindOptions(), session: ClientSession? = null ): List<MongoFile> { val publisher = when (session) { null -> java.find(filter.java) else -> java.find(session.java, filter.java) } return publisher .apply(options) .asFlow() .toList() .map { it.kt } } /** * Finds all documents in the collection that match the filter. * * Below is an example of filtering against the filename and some nested metadata that can also be stored along with the file data: * * ```kotlin * find({ * "filename" by "mongodb.png" * "metadata.contentType" by "image/png" * }) * ``` * * @param session the client session with which to associate this operation. * @param filter the query filter. * @return a list containing the found files. * @since 2.0.0 * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.find */ suspend fun MongoBucket.find( filter: BsonDocumentBlock, session: ClientSession? = null, options: BucketFindOptions.() -> Unit = {} ) = find(BsonDocument(filter), BucketFindOptions(options), session) /* ============= ------------------ ============= */ /** * Given a [id], delete this stored file's `files` * collection document and associated `chunks` from * a GridFS bucket. * * @param session the client session with which to associate this operation. * @param id the id of the file to be deleted * @since 2.0.0 * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.delete */ suspend fun MongoBucket.delete( id: BsonElement, session: ClientSession? = null ) { val publisher = when (session) { null -> java.delete(id.java) else -> java.delete(session.java, id.java) } publisher.awaitFirstOrNull() } /* ============= ------------------ ============= */ /** * Renames the stored file with the specified [id]. * * @param session the client session with which to associate this operation. * @param id the id of the file in the files collection to rename * @param filename the new filename for the file * @since 2.0.0 * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.rename */ suspend fun MongoBucket.rename( id: BsonElement, filename: String, session: ClientSession? = null ) { val publisher = when (session) { null -> java.rename(id.java, filename) else -> java.rename(session.java, id.java, filename) } publisher.awaitFirstOrNull() } /* ============= ------------------ ============= */ /** * Drops the data associated with this bucket from the database. * * @param session the client session with which to associate this operation. * @since 2.0.0 * @see com.mongodb.reactivestreams.client.gridfs.GridFSBucket.drop */ suspend fun MongoBucket.drop( session: ClientSession? = null ) { val publisher = when (session) { null -> java.drop() else -> java.drop(session.java) } publisher.awaitFirstOrNull() } /* ============= ------------------ ============= */
1
Kotlin
1
5
9e2f9ace50cdd8345d68a7943ef0c24b6072427c
17,146
monkt
Apache License 2.0
src/main/kotlin/com/nasller/codeglance/render/FastMainMinimap.kt
Nasller
472,645,501
false
null
package com.nasller.codeglance.render import com.intellij.ide.ui.UISettings import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.ReadAction import com.intellij.openapi.application.runInEdt import com.intellij.openapi.diagnostic.Attachment import com.intellij.openapi.editor.* import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.event.DocumentEvent import com.intellij.openapi.editor.ex.EditorEx import com.intellij.openapi.editor.ex.FoldingListener import com.intellij.openapi.editor.ex.RangeHighlighterEx import com.intellij.openapi.editor.ex.util.EditorUtil import com.intellij.openapi.editor.ex.util.EmptyEditorHighlighter import com.intellij.openapi.editor.impl.EditorImpl import com.intellij.openapi.editor.impl.softwrap.mapping.IncrementalCacheUpdateEvent import com.intellij.openapi.editor.impl.softwrap.mapping.SoftWrapApplianceManager import com.intellij.openapi.util.SystemInfoRt import com.intellij.openapi.util.TextRange import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.DocumentEventUtil import com.intellij.util.DocumentUtil import com.intellij.util.MathUtil import com.intellij.util.Range import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.util.containers.ContainerUtil import com.intellij.util.text.CharArrayUtil import com.intellij.util.ui.EdtInvocationManager import com.intellij.util.ui.UIUtil import com.nasller.codeglance.config.CodeGlanceColorsPage import com.nasller.codeglance.config.CodeGlanceConfigService import com.nasller.codeglance.panel.GlancePanel import com.nasller.codeglance.util.MyVisualLinesIterator import it.unimi.dsi.fastutil.objects.ObjectArrayList import org.jetbrains.concurrency.CancellablePromise import org.jetbrains.concurrency.Promise import org.slf4j.LoggerFactory import java.awt.Color import java.awt.Font import java.awt.image.BufferedImage import java.beans.PropertyChangeEvent import java.lang.reflect.Proxy import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt @Suppress("UnstableApiUsage") class FastMainMinimap(glancePanel: GlancePanel, virtualFile: VirtualFile?) : BaseMinimap(glancePanel, virtualFile){ private val myDocument = editor.document override val rangeList: MutableList<Pair<Int, Range<Int>>> = ContainerUtil.createLockFreeCopyOnWriteList() private val renderDataList = ObjectArrayList<LineRenderData>().also { it.addAll(ObjectArrayList.wrap(arrayOfNulls(editor.visibleLineCount))) } private val mySoftWrapChangeListener = Proxy.newProxyInstance(platformClassLoader, softWrapListenerClass) { _, method, args -> return@newProxyInstance if(HOOK_ON_RECALCULATION_END_METHOD == method.name && args?.size == 1){ onSoftWrapRecalculationEnd(args[0] as IncrementalCacheUpdateEvent) }else null }.also { editor.softWrapModel.applianceManager.addSoftWrapListener(it) } private val imgArray = arrayOf(getBufferedImage(), getBufferedImage()) @Volatile private var myLastImageIndex = 0 @Volatile private var myResetDataPromise: CancellablePromise<Unit>? = null private var myRenderDirty = false init { makeListener() } override fun getImageOrUpdate(): BufferedImage { return imgArray[myLastImageIndex] } override fun updateMinimapImage(canUpdate: Boolean){ if (canUpdate && myDocument.textLength > 0) { if(lock.compareAndSet(false,true)) { val copyList = renderDataList.toList() val action = Runnable { ReadAction.nonBlocking<Unit> { update(copyList) }.expireWith(this).finishOnUiThread(ModalityState.any()) { lock.set(false) glancePanel.repaint() if (myRenderDirty) { myRenderDirty = false updateMinimapImage() } }.submit(AppExecutorUtil.getAppExecutorService()) } if(editor.editorKind != EditorKind.CONSOLE){ glancePanel.psiDocumentManager.performForCommittedDocument(myDocument, action) }else action.run() }else { myRenderDirty = true } } } override fun rebuildDataAndImage() { runInEdt(modalityState){ if(canUpdate()) resetMinimapData() } } private fun getMinimapImage(drawHeight: Int): BufferedImage? { val index = if(myLastImageIndex == 0) 1 else 0 var curImg = imgArray[index] if (curImg.height < drawHeight || curImg.width < glancePanel.width) { curImg.flush() curImg = getBufferedImage(drawHeight) imgArray[index] = curImg } return if(glancePanel.checkVisible()) curImg else null } private fun update(copyList: List<LineRenderData?>){ val curImg = getMinimapImage(copyList.filterNotNull().sumOf { it.y + it.aboveBlockLine }) ?: return val graphics = curImg.createGraphics() graphics.composite = GlancePanel.CLEAR graphics.fillRect(0, 0, curImg.width, curImg.height) val markAttributes by lazy(LazyThreadSafetyMode.NONE) { editor.colorsScheme.getAttributes(CodeGlanceColorsPage.MARK_COMMENT_ATTRIBUTES).also { UISettings.setupAntialiasing(graphics) } } val font by lazy(LazyThreadSafetyMode.NONE) { editor.colorsScheme.getFont(when (markAttributes.fontType) { Font.ITALIC -> EditorFontType.ITALIC Font.BOLD -> EditorFontType.BOLD Font.ITALIC or Font.BOLD -> EditorFontType.BOLD_ITALIC else -> EditorFontType.PLAIN }).deriveFont(config.markersScaleFactor * config.pixelsPerLine) } var totalY = 0 var skipY = 0 val curRangeList = mutableListOf<Pair<Int, Range<Int>>>() for ((index, it) in copyList.withIndex()) { if(it == null) continue //Coordinates if(it.lineType == LineType.CUSTOM_FOLD){ curRangeList.add(index to Range(totalY, totalY + it.y - config.pixelsPerLine + it.aboveBlockLine)) }else if(it.aboveBlockLine > 0){ curRangeList.add(index - 1 to Range(totalY, totalY + it.y - config.pixelsPerLine + it.aboveBlockLine)) } //Skipping if(skipY > 0){ if(skipY in 1 .. it.aboveBlockLine){ totalY += it.aboveBlockLine skipY = 0 }else { val curY = it.aboveBlockLine + it.y totalY += curY skipY -= curY continue } }else { totalY += it.aboveBlockLine } //Rendering if(it !== DefaultLineRenderData){ when(it.lineType){ LineType.CODE, LineType.CUSTOM_FOLD -> { var curX = it.startX var curY = totalY breakY@ for (renderData in it.renderData) { renderData.color.setColorRgba() for (char in renderData.renderChar) { curImg.renderImage(curX, curY, char.code) when (char.code) { 9 -> curX += 4 //TAB 10 -> {//ENTER if(it.lineType == LineType.CUSTOM_FOLD){ curX = 0 curY += config.pixelsPerLine }else break@breakY } else -> curX += 1 } } } } LineType.COMMENT -> { graphics.composite = GlancePanel.srcOver graphics.color = markAttributes.foregroundColor val commentText = myDocument.getText(TextRange(it.commentHighlighterEx!!.startOffset, it.commentHighlighterEx.endOffset)) val textFont = if (!SystemInfoRt.isMac && font.canDisplayUpTo(commentText) != -1) { UIUtil.getFontWithFallback(font).deriveFont(markAttributes.fontType, font.size2D) } else font graphics.font = textFont graphics.drawString(commentText, it.startX,totalY + (graphics.getFontMetrics(textFont).height / 1.5).roundToInt()) skipY = (config.markersScaleFactor.toInt() - 1) * config.pixelsPerLine } } } totalY += it.y } graphics.dispose() if(rangeList.isNotEmpty() || curRangeList.isNotEmpty()){ rangeList.clear() rangeList.addAll(curRangeList) } myLastImageIndex = if(myLastImageIndex == 0) 1 else 0 } private fun updateMinimapData(visLinesIterator: MyVisualLinesIterator, endVisualLine: Int){ val text = myDocument.immutableCharSequence val defaultColor = editor.colorsScheme.defaultForeground val docComment by lazy(LazyThreadSafetyMode.NONE){ editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.DOC_COMMENT).foregroundColor } val markCommentMap = glancePanel.markCommentState.getAllMarkCommentHighlight() .associateBy { DocumentUtil.getLineStartOffset(it.startOffset, myDocument) } val limitWidth = glancePanel.getConfigSize().width while (!visLinesIterator.atEnd()) { val start = visLinesIterator.getVisualLineStartOffset() val end = visLinesIterator.getVisualLineEndOffset() val visualLine = visLinesIterator.getVisualLine() if(myResetDataPromise != null) { //Check invalid somethings in background task if(visualLine >= renderDataList.size || start > end) return } //BLOCK_INLAY val aboveBlockLine = visLinesIterator.getBlockInlaysAbove().sumOf { (it.heightInPixels * scrollState.scale).toInt() } //CUSTOM_FOLD var foldRegion = visLinesIterator.getCurrentFoldRegion() var foldStartOffset = foldRegion?.startOffset ?: -1 if(foldRegion is CustomFoldRegion && foldStartOffset == start){ //jump over the fold line val heightLine = (foldRegion.heightInPixels * scrollState.scale).toInt().run{ if(this < config.pixelsPerLine) config.pixelsPerLine else this } //this is render document val line = myDocument.getLineNumber(foldStartOffset) - 1 + (heightLine / config.pixelsPerLine) val foldEndOffset = foldRegion.endOffset.run { if(DocumentUtil.isValidLine(line, myDocument)) { val lineEndOffset = myDocument.getLineEndOffset(line) if(this < lineEndOffset) this else lineEndOffset }else this } renderDataList[visualLine] = LineRenderData(listOf(RenderData(CharArrayUtil.fromSequence(text, foldStartOffset, foldEndOffset), docComment ?: defaultColor)), 0, heightLine, aboveBlockLine, LineType.CUSTOM_FOLD) }else { //COMMENT if(markCommentMap.containsKey(start)) { renderDataList[visualLine] = LineRenderData(emptyList(), 2, config.pixelsPerLine, aboveBlockLine, LineType.COMMENT, commentHighlighterEx = markCommentMap[start]) }else if(start < text.length && text.subSequence(start, end).isNotBlank()){ val hlIter = editor.highlighter.run { if(this is EmptyEditorHighlighter) OneLineHighlightDelegate(myDocument, start, end) else{ val highlighterIterator = createIterator(start) if(isLogFile){ if(highlighterIterator::class.java.name.contains("EmptyEditorHighlighter")){ OneLineHighlightDelegate(myDocument, start, end) }else IdeLogFileHighlightDelegate(myDocument, highlighterIterator) }else highlighterIterator } } if(hlIter is OneLineHighlightDelegate || !hlIter.atEnd()){ val renderList = mutableListOf<RenderData>() var foldLineIndex = visLinesIterator.getStartFoldingIndex() var width = 0 do { val curEnd = hlIter.end if(width > limitWidth || curEnd > text.length) break var curStart = if(start > hlIter.start && start < curEnd) start else hlIter.start //FOLD if(curStart == foldStartOffset){ val foldEndOffset = foldRegion!!.endOffset val foldText = StringUtil.replace(foldRegion.placeholderText, "\n", " ").toCharArray() width += foldText.size renderList.add(RenderData(foldText, editor.foldingModel .placeholderAttributes?.foregroundColor ?: defaultColor)) foldRegion = visLinesIterator.getFoldRegion(++foldLineIndex) foldStartOffset = foldRegion?.startOffset ?: -1 //case on fold InLine if(foldEndOffset < curEnd){ curStart = foldEndOffset }else { do hlIter.advance() while (!hlIter.atEnd() && hlIter.start < foldEndOffset) continue } } //CODE val renderStr = CharArrayUtil.fromSequence(text, curStart, limitLength(curStart,curEnd,limitWidth)) width += renderStr.size if(renderStr.isEmpty() || renderStr.all { it.isWhitespace() }) { renderList.add(RenderData(renderStr, defaultColor)) }else{ val highlightList = getHighlightColor(curStart, curEnd) if(highlightList.isNotEmpty()){ if(highlightList.size == 1 && highlightList.first().run{ startOffset == curStart && endOffset == curEnd }){ renderList.add(RenderData(renderStr, highlightList.first().foregroundColor)) }else { val lexerColor = runCatching { hlIter.textAttributes.foregroundColor }.getOrNull() ?: defaultColor var nextOffset = curStart var preColor: Color? = null for(offset in curStart .. curEnd){ val color = highlightList.firstOrNull { offset >= it.startOffset && offset < it.endOffset }?.foregroundColor ?: lexerColor if(preColor != null && preColor !== color){ renderList.add(RenderData(CharArrayUtil.fromSequence(text, nextOffset, limitLength(nextOffset,offset,limitWidth)), preColor)) nextOffset = offset } preColor = color } if(nextOffset < curEnd){ renderList.add(RenderData(CharArrayUtil.fromSequence(text, nextOffset, limitLength(nextOffset,curEnd,limitWidth)), preColor ?: lexerColor)) } } }else { renderList.add(RenderData(renderStr, runCatching { hlIter.textAttributes.foregroundColor }.getOrNull() ?: defaultColor)) } } hlIter.advance() }while (!hlIter.atEnd() && hlIter.start < end) renderDataList[visualLine] = LineRenderData(renderList, visLinesIterator.getStartsWithSoftWrap()?.indentInColumns ?: 0, config.pixelsPerLine, aboveBlockLine) }else { renderDataList[visualLine] = DefaultLineRenderData } }else { renderDataList[visualLine] = DefaultLineRenderData } } if(endVisualLine == 0 || visualLine <= endVisualLine) visLinesIterator.advance() else break } updateMinimapImage() } private fun resetMinimapData(){ assert(!myDocument.isInBulkUpdate) assert(!editor.inlayModel.isInBatchMode) doInvalidateRange(0, myDocument.textLength, true) } private var myDirty = false private var myFoldingBatchStart = false private var myFoldingChangeStartOffset = Int.MAX_VALUE private var myFoldingChangeEndOffset = Int.MIN_VALUE private var myDuringDocumentUpdate = false private var myDocumentChangeStartOffset = 0 private var myDocumentChangeEndOffset = 0 private var myResetChangeStartOffset = Int.MAX_VALUE private var myResetChangeEndOffset = Int.MIN_VALUE /** PrioritizedDocumentListener */ override fun beforeDocumentChange(event: DocumentEvent) { assertValidState() myDuringDocumentUpdate = true if (event.document.isInBulkUpdate) return val offset = event.offset val moveOffset = if (DocumentEventUtil.isMoveInsertion(event)) event.moveOffset else offset myDocumentChangeStartOffset = min(offset, moveOffset) myDocumentChangeEndOffset = max(offset, moveOffset) + event.newLength } override fun documentChanged(event: DocumentEvent) { myDuringDocumentUpdate = false if (event.document.isInBulkUpdate) return doInvalidateRange(myDocumentChangeStartOffset, myDocumentChangeEndOffset) assertValidState() } override fun getPriority(): Int = 170 //EditorDocumentPriorities /** FoldingListener */ override fun onFoldRegionStateChange(region: FoldRegion) { if (myDocument.isInBulkUpdate) return if(region.isValid) { myFoldingChangeStartOffset = min(myFoldingChangeStartOffset, region.startOffset) myFoldingChangeEndOffset = max(myFoldingChangeEndOffset, region.endOffset) } } override fun beforeFoldRegionDisposed(region: FoldRegion) { if (!myDuringDocumentUpdate || myDocument.isInBulkUpdate || region !is CustomFoldRegion) return myDocumentChangeStartOffset = min(myDocumentChangeStartOffset, region.getStartOffset()) myDocumentChangeEndOffset = max(myDocumentChangeEndOffset, region.getEndOffset()) } override fun onCustomFoldRegionPropertiesChange(region: CustomFoldRegion, flags: Int) { if (flags and FoldingListener.ChangeFlags.HEIGHT_CHANGED == 0 || myDocument.isInBulkUpdate || checkDirty()) return val startOffset = region.startOffset if (editor.foldingModel.getCollapsedRegionAtOffset(startOffset) !== region) return doInvalidateRange(startOffset, startOffset) } override fun onFoldProcessingStart() { myFoldingBatchStart = true } override fun onFoldProcessingEnd() { if (myDocument.isInBulkUpdate) return if (myFoldingChangeStartOffset <= myFoldingChangeEndOffset && (!myFoldingBatchStart || editor.visibleLineCount != renderDataList.size)) { doInvalidateRange(myFoldingChangeStartOffset, myFoldingChangeEndOffset) } myFoldingChangeStartOffset = Int.MAX_VALUE myFoldingChangeEndOffset = Int.MIN_VALUE myFoldingBatchStart = false assertValidState() } /** InlayModel.SimpleAdapter */ override fun onAdded(inlay: Inlay<*>) = checkinInlayAndUpdate(inlay) override fun onRemoved(inlay: Inlay<*>) = checkinInlayAndUpdate(inlay) override fun onUpdated(inlay: Inlay<*>, changeFlags: Int) = checkinInlayAndUpdate(inlay, changeFlags) private fun checkinInlayAndUpdate(inlay: Inlay<*>, changeFlags: Int? = null) { if(myDocument.isInBulkUpdate || editor.inlayModel.isInBatchMode || inlay.placement != Inlay.Placement.ABOVE_LINE || (changeFlags != null && changeFlags and InlayModel.ChangeFlags.HEIGHT_CHANGED == 0) || myDuringDocumentUpdate) return val offset = inlay.offset doInvalidateRange(offset,offset) } override fun onBatchModeFinish(editor: Editor) { if (myDocument.isInBulkUpdate) return resetMinimapData() } /** SoftWrapChangeListener */ override fun softWrapsChanged() { val enabled = editor.softWrapModel.isSoftWrappingEnabled if (enabled && !softWrapEnabled) { softWrapEnabled = true } else if (!enabled && softWrapEnabled) { softWrapEnabled = false resetMinimapData() } } override fun recalculationEnds() = Unit private fun onSoftWrapRecalculationEnd(event: IncrementalCacheUpdateEvent) { if (myDocument.isInBulkUpdate) return var invalidate = true if (editor.foldingModel.isInBatchFoldingOperation) { myFoldingChangeStartOffset = min(myFoldingChangeStartOffset, event.startOffset) myFoldingChangeEndOffset = max(myFoldingChangeEndOffset, event.actualEndOffset) invalidate = false } if (myDuringDocumentUpdate) { myDocumentChangeStartOffset = min(myDocumentChangeStartOffset, event.startOffset) myDocumentChangeEndOffset = max(myDocumentChangeEndOffset, event.actualEndOffset) invalidate = false } if (invalidate) { val startOffset = event.startOffset val endOffset = event.actualEndOffset if(startOffset == 0 && endOffset == myDocument.textLength) { if(glancePanel.hideScrollBarListener.isNotRunning().not()) return doInvalidateRange(startOffset, endOffset, true) }else doInvalidateRange(startOffset, endOffset) } } /** MarkupModelListener */ override fun afterAdded(highlighter: RangeHighlighterEx) { glancePanel.markCommentState.markCommentHighlightChange(highlighter, false) updateRangeHighlight(highlighter) } override fun beforeRemoved(highlighter: RangeHighlighterEx) { glancePanel.markCommentState.markCommentHighlightChange(highlighter, true) } override fun afterRemoved(highlighter: RangeHighlighterEx) = updateRangeHighlight(highlighter) private fun updateRangeHighlight(highlighter: RangeHighlighterEx) { EdtInvocationManager.invokeLaterIfNeeded { if (!glancePanel.checkVisible() || myDocument.isInBulkUpdate || editor.inlayModel.isInBatchMode || editor.foldingModel.isInBatchFoldingOperation || myDuringDocumentUpdate) return@invokeLaterIfNeeded if(highlighter.isThinErrorStripeMark.not() && (CodeGlanceColorsPage.MARK_COMMENT_ATTRIBUTES == highlighter.textAttributesKey || EditorUtil.attributesImpactForegroundColor(highlighter.getTextAttributes(editor.colorsScheme)))) { val textLength = myDocument.textLength val startOffset = MathUtil.clamp(highlighter.affectedAreaStartOffset, 0, textLength) val endOffset = MathUtil.clamp(highlighter.affectedAreaEndOffset, 0, textLength) if (startOffset > endOffset || startOffset >= textLength || endOffset < 0) return@invokeLaterIfNeeded if(myDuringDocumentUpdate) { myDocumentChangeStartOffset = min(myDocumentChangeStartOffset, startOffset) myDocumentChangeEndOffset = max(myDocumentChangeEndOffset, endOffset) }else if (myFoldingChangeEndOffset != Int.MIN_VALUE) { myFoldingChangeStartOffset = min(myFoldingChangeStartOffset, startOffset) myFoldingChangeEndOffset = max(myFoldingChangeEndOffset, endOffset) }else { doInvalidateRange(startOffset, endOffset) } }else if(highlighter.getErrorStripeMarkColor(editor.colorsScheme) != null){ glancePanel.repaint() } } } /** PropertyChangeListener */ override fun propertyChange(evt: PropertyChangeEvent) { if (EditorEx.PROP_HIGHLIGHTER != evt.propertyName) return resetMinimapData() } private fun doInvalidateRange(startOffset: Int, endOffset: Int, reset: Boolean = false) { if (checkDirty() || checkProcessReset(startOffset,endOffset,reset)) return val startVisualLine = editor.offsetToVisualLine(startOffset, false) val endVisualLine = editor.offsetToVisualLine(endOffset, true) val lineDiff = editor.visibleLineCount - renderDataList.size if (lineDiff > 0) { renderDataList.addAll(startVisualLine, ObjectArrayList.wrap(arrayOfNulls(lineDiff))) }else if (lineDiff < 0) { renderDataList.removeElements(startVisualLine, startVisualLine - lineDiff) } submitUpdateMinimapDataTask(startVisualLine, endVisualLine, reset) } private fun submitUpdateMinimapDataTask(startVisualLine: Int, endVisualLine: Int, reset: Boolean) { if(!glancePanel.checkVisible()) return try { val visLinesIterator = MyVisualLinesIterator(editor, startVisualLine) if(reset){ if(LOG.isDebugEnabled) LOG.info(Throwable().stackTraceToString()) myResetDataPromise = ReadAction.nonBlocking<Unit> { updateMinimapData(visLinesIterator, 0) }.coalesceBy(this).expireWith(this).finishOnUiThread(ModalityState.any()) { if (myResetChangeStartOffset <= myResetChangeEndOffset) { doInvalidateRange(myResetChangeStartOffset, myResetChangeEndOffset) myResetChangeStartOffset = Int.MAX_VALUE myResetChangeEndOffset = Int.MIN_VALUE assertValidState() } if(LOG.isDebugEnabled) LOG.info(renderDataList.toString()) }.submit(AppExecutorUtil.getAppExecutorService()).onSuccess { myResetDataPromise = null }.onError { myResetDataPromise = null } }else updateMinimapData(visLinesIterator, endVisualLine) }catch (e: Throwable){ LOG.error("submitMinimapDataUpdateTask error",e) } } //check has background tasks private fun checkProcessReset(startOffset: Int, endOffset: Int,reset: Boolean): Boolean{ if (myResetDataPromise != null) { if(myResetDataPromise?.state == Promise.State.PENDING){ if(reset) { myResetDataPromise?.cancel() myResetChangeStartOffset = Int.MAX_VALUE myResetChangeEndOffset = Int.MIN_VALUE }else { myResetChangeStartOffset = min(myResetChangeStartOffset, startOffset) myResetChangeEndOffset = max(myResetChangeEndOffset, endOffset) return true } } myResetDataPromise = null } return false } private fun checkDirty(): Boolean { if (editor.softWrapModel.isDirty) { myDirty = true return true } return if (myDirty) { myDirty = false resetMinimapData() true }else false } private fun assertValidState() { if (myDocument.isInBulkUpdate || editor.inlayModel.isInBatchMode || myResetDataPromise != null || myDirty) return if (editor.visibleLineCount != renderDataList.size) { LOG.error("Inconsistent state {}", Attachment("glance.txt", editor.dumpState())) resetMinimapData() assert(editor.visibleLineCount == renderDataList.size) } } override fun dispose() { super.dispose() editor.softWrapModel.applianceManager.removeSoftWrapListener(mySoftWrapChangeListener) renderDataList.clear() imgArray.forEach { it.flush() } } private data class LineRenderData(val renderData: List<RenderData>, val startX: Int, var y: Int, val aboveBlockLine: Int, val lineType: LineType = LineType.CODE, val commentHighlighterEx: RangeHighlighterEx? = null) private data class RenderData(val renderChar: CharArray, val color: Color){ override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as RenderData if (!renderChar.contentEquals(other.renderChar)) return false if (color != other.color) return false return true } override fun hashCode(): Int { var result = renderChar.contentHashCode() result = 31 * result + color.hashCode() return result } } private enum class LineType{ CODE, COMMENT, CUSTOM_FOLD} @Suppress("UNCHECKED_CAST") companion object{ private val LOG = LoggerFactory.getLogger(FastMainMinimap::class.java) private const val HOOK_ON_RECALCULATION_END_METHOD = "onRecalculationEnd" private val platformClassLoader = EditorImpl::class.java.classLoader private val softWrapListenerClass = arrayOf(Class.forName("com.intellij.openapi.editor.impl.softwrap.mapping.SoftWrapAwareDocumentParsingListener")) private val softWrapListeners = SoftWrapApplianceManager::class.java.getDeclaredField("myListeners").apply { isAccessible = true } private val DefaultLineRenderData = LineRenderData(emptyList(), 0, CodeGlanceConfigService.getConfig().pixelsPerLine, 0, LineType.CODE) fun changePixels(){ DefaultLineRenderData.y = CodeGlanceConfigService.getConfig().pixelsPerLine } private fun SoftWrapApplianceManager.addSoftWrapListener(listener: Any) { (softWrapListeners.get(this) as MutableList<Any>).add(listener) } private fun SoftWrapApplianceManager.removeSoftWrapListener(listener: Any) { (softWrapListeners.get(this) as MutableList<Any>).remove(listener) } private fun limitLength(start: Int, end: Int, limit: Int): Int{ val length = end - start return if(length > limit) start + limit else end } } }
3
Kotlin
14
136
a8e9c52fe4b8f4344ceb72fb2be9dc9a61056ce1
26,111
CodeGlancePro
Apache License 2.0
app/src/test/java/com/cjmobileapps/quidditchplayersandroid/util/TestTimeUtil.kt
CJMobileApps
750,394,460
false
{"Kotlin": 195996}
package com.cjmobileapps.quidditchplayersandroid.util import com.cjmobileapps.quidditchplayersandroid.util.time.TimeUtil object TestTimeUtil : TimeUtil { private var count = 1 fun resetTestTimeUtil() { count = 1 } override suspend fun delayWithRandomTime() { } override fun getRandomSeconds(): Long = 0 override fun isDelayLoopRunning(): Boolean = (count-- > 0) }
0
Kotlin
0
0
ce235c3b16e0cd9d37c98894f921db822883adb9
402
quidditch-players-android-2023
MIT License
core/src/main/kotlin/com/gitlab/kordlib/core/ClientResources.kt
cybernetics
314,534,887
true
{"Kotlin": 995285}
package com.gitlab.kordlib.core import com.gitlab.kordlib.core.supplier.EntitySupplyStrategy import com.gitlab.kordlib.gateway.Intents import io.ktor.client.HttpClient class ClientResources( val token: String, val shardCount: Int, val httpClient: HttpClient, val defaultStrategy: EntitySupplyStrategy<*>, val intents: Intents ) { override fun toString(): String { return "ClientResources(shardCount=$shardCount, httpClient=$httpClient, defaultStrategy=$defaultStrategy, intents=$intents)" } }
0
null
0
0
3bebe2f796bff84205c9ea6cceae51e2c41dee76
550
kord
MIT License
src/main/kotlin/no/skatteetaten/aurora/herkimer/controller/ResourceController.kt
Skatteetaten
286,416,587
false
null
package no.skatteetaten.aurora.herkimer.controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PatchMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import com.fasterxml.jackson.databind.JsonNode import com.fasterxml.jackson.databind.node.ObjectNode import no.skatteetaten.aurora.herkimer.dao.PrincipalUID import no.skatteetaten.aurora.herkimer.dao.ResourceKind import no.skatteetaten.aurora.herkimer.service.ByClaimedBy import no.skatteetaten.aurora.herkimer.service.ByNameAndKind import no.skatteetaten.aurora.herkimer.service.PrincipalService import no.skatteetaten.aurora.herkimer.service.ResourceService data class ResourcePayload( val name: String, val kind: ResourceKind, val ownerId: PrincipalUID, val parentId: Int? = null ) data class ResourceClaimPayload( val ownerId: PrincipalUID, val credentials: JsonNode, val name: String ) @RestController @RequestMapping("/resource") class ResourceController( private val resourceService: ResourceService, private val principalService: PrincipalService ) { @PostMapping fun create(@RequestBody payload: ResourcePayload): AuroraResponse<Resource> { val existingOwner = principalService.findById(payload.ownerId) ?: throw NoSuchResourceException("Could not find Principal with id=${payload.ownerId}") return payload.run { resourceService.createResource( name = name, kind = kind, ownerId = existingOwner.id, parentId = parentId ) }.toResource() .okResponse() } @PostMapping("/{resourceId}/claims") fun createClaimforResource( @PathVariable resourceId: Int, @RequestBody payload: ResourceClaimPayload ): AuroraResponse<ResourceClaim> { requireNotNull(principalService.findById(payload.ownerId)) { "Cannot create claim for resource with id=$resourceId. Owner does not exist, ownerId=${payload.ownerId}" } requireNotNull(resourceService.findById(resourceId)) { "Cannot create claim. Resource with id=$resourceId does not exist." } require(payload.credentials is ObjectNode) { "Credentials has to be JSON object. Arrays are not allowed." } return resourceService.createResourceClaim(payload.ownerId, resourceId, payload.credentials, payload.name) .toResource() .okResponse() } @GetMapping fun findAllResourcesByFilters( @RequestParam(required = false) claimedBy: PrincipalUID?, @RequestParam(required = false, defaultValue = "true") includeClaims: Boolean, @RequestParam(required = false, defaultValue = "true") onlyMyClaims: Boolean, @RequestParam(required = false) name: String?, @RequestParam(required = false) resourceKind: ResourceKind?, @RequestParam(defaultValue = "false") includeDeactivated: Boolean ): AuroraResponse<Resource> { if (claimedBy != null && principalService.findById(claimedBy) == null) return AuroraResponse() val params = when { claimedBy != null -> ByClaimedBy(claimedBy, name, resourceKind, onlyMyClaims) name != null && resourceKind != null -> ByNameAndKind(name, resourceKind) else -> throw IllegalArgumentException("When claimedBy is not specified name and resourceKind is required.") } return resourceService.findAllResourcesByParams(params, includeClaims, includeDeactivated) .toResources() .okResponse() } @GetMapping("/{id}") fun findById( @PathVariable id: Int, @RequestParam(required = false, defaultValue = "false") includeClaims: Boolean ) = resourceService.findById(id, includeClaims)?.toResource()?.okResponse() ?: throw NoSuchResourceException("Could not find Resource with id=$id") @PutMapping("/{id}") fun update( @PathVariable id: Int, @RequestBody payload: ResourcePayload ): AuroraResponse<Resource> { val existingResource = resourceService.findById(id) ?: throw NoSuchResourceException("Could not find Resource with id=$id") requireNotNull(principalService.findById(payload.ownerId)) { "The provided ownerId for the resource does not exist, resourceId=$id and ownerId=${payload.ownerId}" } return payload.run { resourceService.updateResource( existingResource.copy( name = name, ownerId = ownerId, kind = kind ) ).toResource() .okResponse() } } @PatchMapping("/{id}") fun updateResource( @PathVariable id: Int, @RequestBody updateRequest: UpdateResourcePayload ): AuroraResponse<Resource> { return resourceService.updateActive(id, updateRequest.active) ?.toResource() ?.okResponse() ?: throw NoSuchResourceException("Could not find Resource with id=$id") } } data class UpdateResourcePayload( val active: Boolean )
0
Kotlin
0
0
f8fad615f6da1742b0f4a51745179a47bceeee32
5,610
herkimer
Apache License 2.0
app/src/main/java/com/github/alexandrebenvides/remotesecuritylockarduino/activities/LockControlActivity.kt
alexandrebenevides
776,291,081
false
{"Kotlin": 12798}
package com.github.alexandrebenvides.remotesecuritylockarduino.activities import android.os.Bundle import android.view.View import android.widget.EditText import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.github.alexandrebenvides.remotesecuritylockarduino.R class LockControlActivity : AppCompatActivity() { private var passwordField: EditText? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_lock_control) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } passwordField = findViewById(R.id.passwordField) } fun disconnectBluetooth(view: View) { if (ConnectActivity.bluetoothConnection?.close() == true) { finish() } } fun unlock(view: View) { if (passwordField?.text.toString() != "") { ConnectActivity.bluetoothConnection?.sendMessage("a:" + passwordField?.text.toString()) } } fun lock(view: View) { ConnectActivity.bluetoothConnection?.sendMessage("f:0") } }
0
Kotlin
0
0
473ae334581251671960d1f7ecb036fa3a08e7b3
1,481
RemoteSecurityLockArduino
MIT License
app/src/test/kotlin/io/lenra/app/ManifestTestKotlin.kt
lenra-io
739,311,795
false
{"Gradle": 3, "Text": 3, "INI": 2, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Java": 84, "YAML": 2, "Kotlin": 2, "Groovy": 2}
package io.lenra.app; import org.junit.Assert.assertEquals; import org.junit.Test; import org.junit.Ignore; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.lenra.app.components.View; import io.lenra.app.components.view.definitions.Find; /** * Unit test for simple App. */ public class ManifestTestKotlin { val mapper: ObjectMapper = ObjectMapper(); @Test fun jsonApply() { val manifest = Manifest().apply { json = Exposer().apply { routes = listOf( Route().apply { path = "/counter/global" view = View().apply { name = "counter" find = Find( "counter", mapOf("user" to "global") ) } roles = listOf("guest", "user") }, Route().apply { path = "/counter/me" view = View().apply { name = "counter" find=Find( "counter", mapOf("user" to "@me") ) } } ) } }; assertEquals( ManifestTestJava.JSON_MANIFEST, mapper.writeValueAsString(manifest)); } }
5
Java
0
0
2d69fd15fd067d35b35619008973e1b2c622a5b0
1,090
app-lib-java
MIT License
jdbc/spring-data-jpa/src/main/kotlin/tech/ydb/jpa/simple/SimpleUserRepository.kt
ydb-platform
491,175,873
false
{"Maven POM": 20, "Text": 1, "Ignore List": 1, "Markdown": 2, "INI": 9, "XML": 12, "Kotlin": 30, "SQL": 2, "Java": 74, "YAML": 3, "HTML": 1}
package tech.ydb.jpa.simple; import org.springframework.data.domain.Limit; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Slice; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.ListCrudRepository; import org.springframework.scheduling.annotation.Async; import java.util.concurrent.CompletableFuture import java.util.stream.Stream /** * Simple repository interface for {@link User} instances. The interface is used to declare the so-called query methods, * i.e. methods to retrieve single entities or collections of them. */ interface SimpleUserRepository : ListCrudRepository<User, Long> { /** * Find the user with the given username. This method will be translated into a query using the * {@link jakarta.persistence.NamedQuery} annotation at the {@link User} class. * * @param username */ fun findByTheUsersName(username: String): User /** * Uses {@link Optional} as return and parameter type. * * @param username */ fun findByUsername(username: String?): User? /** * Find all users with the given lastname. This method will be translated into a query by constructing it directly * from the method name as there is no other query declared. * * @param lastname */ fun findByLastname(lastname: String): List<User> /** * Find at most the number of users defined via maxResults with the given lastname. * This method will be translated into a query by constructing it directly from the method name as there is no other * query declared. * * @param lastname * @param maxResults the maximum number of results returned. */ fun findByLastname(lastname: String, maxResults: Limit): List<User> /** * Returns all users with the given firstname. This method will be translated into a query using the one declared in * the {@link Query} annotation declared one. * * @param firstname */ @Query("select u from User u where u.firstname = :firstname") fun findByFirstname(firstname: String): List<User> /** * Returns at most the number of users defined via {@link Limit} with the given firstname. This method will be * translated into a query using the one declared in the {@link Query} annotation declared one. * * @param firstname * @param maxResults the maximum number of results returned. */ @Query("select u from User u where u.firstname = :firstname") fun findByFirstname(firstname: String, maxResults: Limit): List<User> /** * Returns all users with the given name as first- or lastname. This makes the query to method relation much more * refactoring-safe as the order of the method parameters is completely irrelevant. * * @param name */ @Query("select u from User u where u.firstname = :name or u.lastname = :name") fun findByFirstnameOrLastname(name: String): List<User> /** * Returns the total number of entries deleted as their lastnames match the given one. * * @param lastname * @return */ fun removeByLastname(lastname: String): Long /** * Returns a {@link Slice} counting a maximum number of {@link Pageable#getPageSize()} users matching given criteria * starting at {@link Pageable#getOffset()} without prior count of the total number of elements available. * * @param lastname * @param page */ fun findByLastnameOrderByUsernameAsc(lastname: String, page: Pageable): Slice<User> /** * Return the first 2 users ordered by their lastname asc. * * <pre> * Example for findFirstK / findTopK functionality. * </pre> */ fun findFirst2ByOrderByLastnameAsc(): List<User> /** * Return the first 2 users ordered by the given {@code sort} definition. * * <pre> * This variant is very flexible because one can ask for the first K results when a ASC ordering * is used as well as for the last K results when a DESC ordering is used. * </pre> * * @param sort */ fun findTop2By(sort: Sort): List<User> /** * Return all the users with the given firstname or lastname. Makes use of SpEL (Spring Expression Language). * * @param user */ @Query("select u from User u where u.firstname = :#{#user.firstname} or u.lastname = :#{#user.lastname}") fun findByFirstnameOrLastname(user: User): Iterable<User> /** * Sample default method. * * @param user */ fun findByLastname(user: User): List<User> { return findByLastname(user.lastname); } /** * Sample method to demonstrate support for {@link Stream} as a return type with a custom query. The query is executed * in a streaming fashion which means that the method returns as soon as the first results are ready. */ @Query("select u from User u") fun streamAllCustomers(): Stream<User> /** * Sample method to demonstrate support for {@link Stream} as a return type with a derived query. The query is * executed in a streaming fashion which means that the method returns as soon as the first results are ready. */ fun findAllByLastnameIsNotNull(): Stream<User> @Async fun readAllBy(): CompletableFuture<List<User>> }
1
Java
4
6
125bb467d959b5a10c44d7a30557996a6d204d6e
5,096
ydb-java-examples
Apache License 2.0
Common/src/main/java/at/petrak/hexcasting/common/casting/operators/OpRead.kt
yrsegal
534,034,284
true
{"Java Properties": 1, "Shell": 1, "Markdown": 2, "Batchfile": 1, "INI": 3, "Kotlin": 177, "Java": 279, "HTML": 1, "Python": 1}
package at.petrak.hexcasting.common.casting.operators import at.petrak.hexcasting.api.spell.ConstManaOperator import at.petrak.hexcasting.api.spell.SpellDatum import at.petrak.hexcasting.api.spell.casting.CastingContext import at.petrak.hexcasting.api.spell.mishaps.MishapBadOffhandItem import at.petrak.hexcasting.xplat.IXplatAbstractions object OpRead : ConstManaOperator { override val argc = 0 override fun execute(args: List<SpellDatum<*>>, ctx: CastingContext): List<SpellDatum<*>> { val (handStack, hand) = ctx.getHeldItemToOperateOn { val dataHolder = IXplatAbstractions.INSTANCE.findDataHolder(it) dataHolder != null && (dataHolder.readDatum(ctx.world) != null || dataHolder.emptyDatum() != null) } val datumHolder = IXplatAbstractions.INSTANCE.findDataHolder(handStack) ?: throw MishapBadOffhandItem.of(handStack, hand, "iota.read") val datum = datumHolder.readDatum(ctx.world) ?: datumHolder.emptyDatum() ?: throw MishapBadOffhandItem.of(handStack, hand, "iota.read") return listOf(datum) } }
0
null
0
0
c5c7b302d2b34d3fa1367bae390c985bc1bf45c0
1,122
HexMod
MIT License