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
kt/godot-library/src/main/kotlin/godot/gen/godot/GraphEdit.kt
utopia-rise
289,462,532
false
{"Kotlin": 1549917, "GDScript": 535642, "C++": 403741, "C": 13152, "C#": 10278, "Shell": 7406, "Java": 2165, "CMake": 939, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.CoreTypeHelper import godot.`annotation`.CoreTypeLocalCopy import godot.`annotation`.GodotBaseType import godot.core.Dictionary import godot.core.GodotError import godot.core.PackedVector2Array import godot.core.StringName import godot.core.TypeManager import godot.core.VariantArray import godot.core.VariantType.ARRAY import godot.core.VariantType.BOOL import godot.core.VariantType.DOUBLE import godot.core.VariantType.LONG import godot.core.VariantType.NIL import godot.core.VariantType.OBJECT import godot.core.VariantType.PACKED_VECTOR2_ARRAY import godot.core.VariantType.STRING_NAME import godot.core.VariantType.VECTOR2 import godot.core.Vector2 import godot.core.memory.TransferContext import godot.signals.Signal0 import godot.signals.Signal1 import godot.signals.Signal3 import godot.signals.Signal4 import godot.signals.signal import godot.util.VoidPtr import kotlin.Any import kotlin.Boolean import kotlin.Double import kotlin.Float import kotlin.Int import kotlin.Long import kotlin.NotImplementedError import kotlin.Suppress import kotlin.Unit /** * An editor for graph-like structures, using [godot.GraphNode]s. * * [godot.GraphEdit] provides tools for creation, manipulation, and display of various graphs. Its main purpose in the engine is to power the visual programming systems, such as visual shaders, but it is also available for use in user projects. * * [godot.GraphEdit] by itself is only an empty container, representing an infinite grid where [godot.GraphNode]s can be placed. Each [godot.GraphNode] represents a node in the graph, a single unit of data in the connected scheme. [godot.GraphEdit], in turn, helps to control various interactions with nodes and between nodes. When the user attempts to connect, disconnect, or delete a [godot.GraphNode], a signal is emitted in the [godot.GraphEdit], but no action is taken by default. It is the responsibility of the programmer utilizing this control to implement the necessary logic to determine how each request should be handled. * * **Performance:** It is greatly advised to enable low-processor usage mode (see [godot.OS.lowProcessorUsageMode]) when using GraphEdits. */ @GodotBaseType public open class GraphEdit : Control() { /** * Emitted to the GraphEdit when the connection between the [fromPort] of the [fromNode] [godot.GraphNode] and the [toPort] of the [toNode] [godot.GraphNode] is attempted to be created. */ public val connectionRequest: Signal4<StringName, Long, StringName, Long> by signal("fromNode", "fromPort", "toNode", "toPort") /** * Emitted to the GraphEdit when the connection between [fromPort] of [fromNode] [godot.GraphNode] and [toPort] of [toNode] [godot.GraphNode] is attempted to be removed. */ public val disconnectionRequest: Signal4<StringName, Long, StringName, Long> by signal("fromNode", "fromPort", "toNode", "toPort") /** * Emitted when user drags a connection from an output port into the empty space of the graph. */ public val connectionToEmpty: Signal3<StringName, Long, Vector2> by signal("fromNode", "fromPort", "releasePosition") /** * Emitted when user drags a connection from an input port into the empty space of the graph. */ public val connectionFromEmpty: Signal3<StringName, Long, Vector2> by signal("toNode", "toPort", "releasePosition") /** * Emitted at the beginning of a connection drag. */ public val connectionDragStarted: Signal3<StringName, Long, Boolean> by signal("fromNode", "fromPort", "isOutput") /** * Emitted at the end of a connection drag. */ public val connectionDragEnded: Signal0 by signal() /** * Emitted when this [godot.GraphEdit] captures a `ui_copy` action ([kbd]Ctrl + C[/kbd] by default). In general, this signal indicates that the selected [godot.GraphElement]s should be copied. */ public val copyNodesRequest: Signal0 by signal() /** * Emitted when this [godot.GraphEdit] captures a `ui_paste` action ([kbd]Ctrl + V[/kbd] by default). In general, this signal indicates that previously copied [godot.GraphElement]s should be pasted. */ public val pasteNodesRequest: Signal0 by signal() /** * Emitted when this [godot.GraphEdit] captures a `ui_graph_duplicate` action ([kbd]Ctrl + D[/kbd] by default). In general, this signal indicates that the selected [godot.GraphElement]s should be duplicated. */ public val duplicateNodesRequest: Signal0 by signal() /** * Emitted when this [godot.GraphEdit] captures a `ui_graph_delete` action ([kbd]Delete[/kbd] by default). * * [nodes] is an array of node names that should be removed. These usually include all selected nodes. */ public val deleteNodesRequest: Signal1<VariantArray<StringName>> by signal("nodes") /** * Emitted when the given [godot.GraphElement] node is selected. */ public val nodeSelected: Signal1<Node> by signal("node") /** * Emitted when the given [godot.GraphElement] node is deselected. */ public val nodeDeselected: Signal1<Node> by signal("node") /** * Emitted when a popup is requested. Happens on right-clicking in the GraphEdit. [position] is the position of the mouse pointer when the signal is sent. */ public val popupRequest: Signal1<Vector2> by signal("position") /** * Emitted at the beginning of a [godot.GraphElement]'s movement. */ public val beginNodeMove: Signal0 by signal() /** * Emitted at the end of a [godot.GraphElement]'s movement. */ public val endNodeMove: Signal0 by signal() /** * Emitted when the scroll offset is changed by the user. It will not be emitted when changed in code. */ public val scrollOffsetChanged: Signal1<Vector2> by signal("offset") /** * The scroll offset. */ @CoreTypeLocalCopy public var scrollOffset: Vector2 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getScrollOffsetPtr, VECTOR2) return (TransferContext.readReturnValue(VECTOR2, false) as Vector2) } set(`value`) { TransferContext.writeArguments(VECTOR2 to value) TransferContext.callMethod(rawPtr, MethodBindings.setScrollOffsetPtr, NIL) } /** * If `true`, the grid is visible. */ public var showGrid: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingGridPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowGridPtr, NIL) } /** * If `true`, enables snapping. */ public var snappingEnabled: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isSnappingEnabledPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setSnappingEnabledPtr, NIL) } /** * The snapping distance in pixels, also determines the grid line distance. */ public var snappingDistance: Int get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getSnappingDistancePtr, LONG) return (TransferContext.readReturnValue(LONG, false) as Long).toInt() } set(`value`) { TransferContext.writeArguments(LONG to value.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.setSnappingDistancePtr, NIL) } /** * Defines the control scheme for panning with mouse wheel. */ public var panningScheme: PanningScheme get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getPanningSchemePtr, LONG) return GraphEdit.PanningScheme.from(TransferContext.readReturnValue(LONG) as Long) } set(`value`) { TransferContext.writeArguments(LONG to value.id) TransferContext.callMethod(rawPtr, MethodBindings.setPanningSchemePtr, NIL) } /** * If `true`, enables disconnection of existing connections in the GraphEdit by dragging the right end. */ public var rightDisconnects: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isRightDisconnectsEnabledPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setRightDisconnectsPtr, NIL) } /** * The curvature of the lines between the nodes. 0 results in straight lines. */ public var connectionLinesCurvature: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getConnectionLinesCurvaturePtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setConnectionLinesCurvaturePtr, NIL) } /** * The thickness of the lines between the nodes. */ public var connectionLinesThickness: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getConnectionLinesThicknessPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setConnectionLinesThicknessPtr, NIL) } /** * If `true`, the lines between nodes will use antialiasing. */ public var connectionLinesAntialiased: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isConnectionLinesAntialiasedPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setConnectionLinesAntialiasedPtr, NIL) } /** * The current zoom value. */ public var zoom: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getZoomPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setZoomPtr, NIL) } /** * The lower zoom limit. */ public var zoomMin: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getZoomMinPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setZoomMinPtr, NIL) } /** * The upper zoom limit. */ public var zoomMax: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getZoomMaxPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setZoomMaxPtr, NIL) } /** * The step of each zoom level. */ public var zoomStep: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getZoomStepPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setZoomStepPtr, NIL) } /** * If `true`, the minimap is visible. */ public var minimapEnabled: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isMinimapEnabledPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setMinimapEnabledPtr, NIL) } /** * The size of the minimap rectangle. The map itself is based on the size of the grid area and is scaled to fit this rectangle. */ @CoreTypeLocalCopy public var minimapSize: Vector2 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getMinimapSizePtr, VECTOR2) return (TransferContext.readReturnValue(VECTOR2, false) as Vector2) } set(`value`) { TransferContext.writeArguments(VECTOR2 to value) TransferContext.callMethod(rawPtr, MethodBindings.setMinimapSizePtr, NIL) } /** * The opacity of the minimap rectangle. */ public var minimapOpacity: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getMinimapOpacityPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setMinimapOpacityPtr, NIL) } /** * If `true`, the menu toolbar is visible. */ public var showMenu: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingMenuPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowMenuPtr, NIL) } /** * If `true`, the label with the current zoom level is visible. The zoom level is displayed in percents. */ public var showZoomLabel: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingZoomLabelPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowZoomLabelPtr, NIL) } /** * If `true`, buttons that allow to change and reset the zoom level are visible. */ public var showZoomButtons: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingZoomButtonsPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowZoomButtonsPtr, NIL) } /** * If `true`, buttons that allow to configure grid and snapping options are visible. */ public var showGridButtons: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingGridButtonsPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowGridButtonsPtr, NIL) } /** * If `true`, the button to toggle the minimap is visible. */ public var showMinimapButton: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingMinimapButtonPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowMinimapButtonPtr, NIL) } /** * If `true`, the button to automatically arrange graph nodes is visible. */ public var showArrangeButton: Boolean get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.isShowingArrangeButtonPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } set(`value`) { TransferContext.writeArguments(BOOL to value) TransferContext.callMethod(rawPtr, MethodBindings.setShowArrangeButtonPtr, NIL) } public override fun new(scriptIndex: Int): Boolean { callConstructor(ENGINECLASS_GRAPHEDIT, scriptIndex) return true } /** * The scroll offset. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = graphedit.scrollOffset * //Your changes * graphedit.scrollOffset = myCoreType * `````` */ @CoreTypeHelper public open fun scrollOffsetMutate(block: Vector2.() -> Unit): Vector2 = scrollOffset.apply{ block(this) scrollOffset = this } /** * The size of the minimap rectangle. The map itself is based on the size of the grid area and is scaled to fit this rectangle. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = graphedit.minimapSize * //Your changes * graphedit.minimapSize = myCoreType * `````` */ @CoreTypeHelper public open fun minimapSizeMutate(block: Vector2.() -> Unit): Vector2 = minimapSize.apply{ block(this) minimapSize = this } /** * Returns whether the [mousePosition] is in the input hot zone. * * By default, a hot zone is a [godot.core.Rect2] positioned such that its center is at [inNode].[godot.GraphNode.getInputPortPosition]([inPort]) (For output's case, call [godot.GraphNode.getOutputPortPosition] instead). The hot zone's width is twice the Theme Property `port_grab_distance_horizontal`, and its height is twice the `port_grab_distance_vertical`. * * Below is a sample code to help get started: * * ``` * func _is_in_input_hotzone(in_node, in_port, mouse_position): * var port_size: Vector2 = Vector2(get_theme_constant("port_grab_distance_horizontal"), get_theme_constant("port_grab_distance_vertical")) * var port_pos: Vector2 = in_node.get_position() + in_node.get_input_port_position(in_port) - port_size / 2 * var rect = Rect2(port_pos, port_size) * * return rect.has_point(mouse_position) * ``` */ public open fun _isInInputHotzone( inNode: Object, inPort: Int, mousePosition: Vector2, ): Boolean { throw NotImplementedError("_is_in_input_hotzone is not implemented for GraphEdit") } /** * Returns whether the [mousePosition] is in the output hot zone. For more information on hot zones, see [_isInInputHotzone]. * * Below is a sample code to help get started: * * ``` * func _is_in_output_hotzone(in_node, in_port, mouse_position): * var port_size: Vector2 = Vector2(get_theme_constant("port_grab_distance_horizontal"), get_theme_constant("port_grab_distance_vertical")) * var port_pos: Vector2 = in_node.get_position() + in_node.get_output_port_position(in_port) - port_size / 2 * var rect = Rect2(port_pos, port_size) * * return rect.has_point(mouse_position) * ``` */ public open fun _isInOutputHotzone( inNode: Object, inPort: Int, mousePosition: Vector2, ): Boolean { throw NotImplementedError("_is_in_output_hotzone is not implemented for GraphEdit") } /** * Virtual method which can be overridden to customize how connections are drawn. */ public open fun _getConnectionLine(fromPosition: Vector2, toPosition: Vector2): PackedVector2Array { throw NotImplementedError("_get_connection_line is not implemented for GraphEdit") } /** * This virtual method can be used to insert additional error detection while the user is dragging a connection over a valid port. * * Return `true` if the connection is indeed valid or return `false` if the connection is impossible. If the connection is impossible, no snapping to the port and thus no connection request to that port will happen. * * In this example a connection to same node is suppressed: * * [codeblocks] * * [gdscript] * * func _is_node_hover_valid(from, from_port, to, to_port): * * return from != to * * [/gdscript] * * [csharp] * * public override bool _IsNodeHoverValid(StringName fromNode, int fromPort, StringName toNode, int toPort) * * { * * return fromNode != toNode; * * } * * [/csharp] * * [/codeblocks] */ public open fun _isNodeHoverValid( fromNode: StringName, fromPort: Int, toNode: StringName, toPort: Int, ): Boolean { throw NotImplementedError("_is_node_hover_valid is not implemented for GraphEdit") } /** * Create a connection between the [fromPort] of the [fromNode] [godot.GraphNode] and the [toPort] of the [toNode] [godot.GraphNode]. If the connection already exists, no connection is created. */ public fun connectNode( fromNode: StringName, fromPort: Int, toNode: StringName, toPort: Int, ): GodotError { TransferContext.writeArguments(STRING_NAME to fromNode, LONG to fromPort.toLong(), STRING_NAME to toNode, LONG to toPort.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.connectNodePtr, LONG) return GodotError.from(TransferContext.readReturnValue(LONG) as Long) } /** * Returns `true` if the [fromPort] of the [fromNode] [godot.GraphNode] is connected to the [toPort] of the [toNode] [godot.GraphNode]. */ public fun isNodeConnected( fromNode: StringName, fromPort: Int, toNode: StringName, toPort: Int, ): Boolean { TransferContext.writeArguments(STRING_NAME to fromNode, LONG to fromPort.toLong(), STRING_NAME to toNode, LONG to toPort.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isNodeConnectedPtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Removes the connection between the [fromPort] of the [fromNode] [godot.GraphNode] and the [toPort] of the [toNode] [godot.GraphNode]. If the connection does not exist, no connection is removed. */ public fun disconnectNode( fromNode: StringName, fromPort: Int, toNode: StringName, toPort: Int, ): Unit { TransferContext.writeArguments(STRING_NAME to fromNode, LONG to fromPort.toLong(), STRING_NAME to toNode, LONG to toPort.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.disconnectNodePtr, NIL) } /** * Sets the coloration of the connection between [fromNode]'s [fromPort] and [toNode]'s [toPort] with the color provided in the [theme_item activity] theme property. The color is linearly interpolated between the connection color and the activity color using [amount] as weight. */ public fun setConnectionActivity( fromNode: StringName, fromPort: Int, toNode: StringName, toPort: Int, amount: Float, ): Unit { TransferContext.writeArguments(STRING_NAME to fromNode, LONG to fromPort.toLong(), STRING_NAME to toNode, LONG to toPort.toLong(), DOUBLE to amount.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setConnectionActivityPtr, NIL) } /** * Returns an Array containing the list of connections. A connection consists in a structure of the form `{ from_port: 0, from_node: "GraphNode name 0", to_port: 1, to_node: "GraphNode name 1" }`. */ public fun getConnectionList(): VariantArray<Dictionary<Any?, Any?>> { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getConnectionListPtr, ARRAY) return (TransferContext.readReturnValue(ARRAY, false) as VariantArray<Dictionary<Any?, Any?>>) } /** * Removes all connections between nodes. */ public fun clearConnections(): Unit { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.clearConnectionsPtr, NIL) } /** * Ends the creation of the current connection. In other words, if you are dragging a connection you can use this method to abort the process and remove the line that followed your cursor. * * This is best used together with [connectionDragStarted] and [connectionDragEnded] to add custom behavior like node addition through shortcuts. * * **Note:** This method suppresses any other connection request signals apart from [connectionDragEnded]. */ public fun forceConnectionDragEnd(): Unit { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.forceConnectionDragEndPtr, NIL) } /** * Allows to disconnect nodes when dragging from the right port of the [godot.GraphNode]'s slot if it has the specified type. See also [removeValidRightDisconnectType]. */ public fun addValidRightDisconnectType(type: Int): Unit { TransferContext.writeArguments(LONG to type.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.addValidRightDisconnectTypePtr, NIL) } /** * Disallows to disconnect nodes when dragging from the right port of the [godot.GraphNode]'s slot if it has the specified type. Use this to disable disconnection previously allowed with [addValidRightDisconnectType]. */ public fun removeValidRightDisconnectType(type: Int): Unit { TransferContext.writeArguments(LONG to type.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.removeValidRightDisconnectTypePtr, NIL) } /** * Allows to disconnect nodes when dragging from the left port of the [godot.GraphNode]'s slot if it has the specified type. See also [removeValidLeftDisconnectType]. */ public fun addValidLeftDisconnectType(type: Int): Unit { TransferContext.writeArguments(LONG to type.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.addValidLeftDisconnectTypePtr, NIL) } /** * Disallows to disconnect nodes when dragging from the left port of the [godot.GraphNode]'s slot if it has the specified type. Use this to disable disconnection previously allowed with [addValidLeftDisconnectType]. */ public fun removeValidLeftDisconnectType(type: Int): Unit { TransferContext.writeArguments(LONG to type.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.removeValidLeftDisconnectTypePtr, NIL) } /** * Allows the connection between two different port types. The port type is defined individually for the left and the right port of each slot with the [godot.GraphNode.setSlot] method. * * See also [isValidConnectionType] and [removeValidConnectionType]. */ public fun addValidConnectionType(fromType: Int, toType: Int): Unit { TransferContext.writeArguments(LONG to fromType.toLong(), LONG to toType.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.addValidConnectionTypePtr, NIL) } /** * Disallows the connection between two different port types previously allowed by [addValidConnectionType]. The port type is defined individually for the left and the right port of each slot with the [godot.GraphNode.setSlot] method. * * See also [isValidConnectionType]. */ public fun removeValidConnectionType(fromType: Int, toType: Int): Unit { TransferContext.writeArguments(LONG to fromType.toLong(), LONG to toType.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.removeValidConnectionTypePtr, NIL) } /** * Returns whether it's possible to make a connection between two different port types. The port type is defined individually for the left and the right port of each slot with the [godot.GraphNode.setSlot] method. * * See also [addValidConnectionType] and [removeValidConnectionType]. */ public fun isValidConnectionType(fromType: Int, toType: Int): Boolean { TransferContext.writeArguments(LONG to fromType.toLong(), LONG to toType.toLong()) TransferContext.callMethod(rawPtr, MethodBindings.isValidConnectionTypePtr, BOOL) return (TransferContext.readReturnValue(BOOL, false) as Boolean) } /** * Returns the points which would make up a connection between [fromNode] and [toNode]. */ public fun getConnectionLine(fromNode: Vector2, toNode: Vector2): PackedVector2Array { TransferContext.writeArguments(VECTOR2 to fromNode, VECTOR2 to toNode) TransferContext.callMethod(rawPtr, MethodBindings.getConnectionLinePtr, PACKED_VECTOR2_ARRAY) return (TransferContext.readReturnValue(PACKED_VECTOR2_ARRAY, false) as PackedVector2Array) } /** * Gets the [godot.HBoxContainer] that contains the zooming and grid snap controls in the top left of the graph. You can use this method to reposition the toolbar or to add your own custom controls to it. * * **Warning:** This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [godot.CanvasItem.visible] property. */ public fun getMenuHbox(): HBoxContainer? { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getMenuHboxPtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as HBoxContainer?) } /** * Rearranges selected nodes in a layout with minimum crossings between connections and uniform horizontal and vertical gap between nodes. */ public fun arrangeNodes(): Unit { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.arrangeNodesPtr, NIL) } /** * Sets the specified [node] as the one selected. */ public fun setSelected(node: Node): Unit { TransferContext.writeArguments(OBJECT to node) TransferContext.callMethod(rawPtr, MethodBindings.setSelectedPtr, NIL) } public enum class PanningScheme( id: Long, ) { /** * [kbd]Mouse Wheel[/kbd] will zoom, [kbd]Ctrl + Mouse Wheel[/kbd] will move the view. */ SCROLL_ZOOMS(0), /** * [kbd]Mouse Wheel[/kbd] will move the view, [kbd]Ctrl + Mouse Wheel[/kbd] will zoom. */ SCROLL_PANS(1), ; public val id: Long init { this.id = id } public companion object { public fun from(`value`: Long) = entries.single { it.id == `value` } } } public companion object internal object MethodBindings { public val _isInInputHotzonePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "_is_in_input_hotzone") public val _isInOutputHotzonePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "_is_in_output_hotzone") public val _getConnectionLinePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "_get_connection_line") public val _isNodeHoverValidPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "_is_node_hover_valid") public val connectNodePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "connect_node") public val isNodeConnectedPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_node_connected") public val disconnectNodePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "disconnect_node") public val setConnectionActivityPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_connection_activity") public val getConnectionListPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_connection_list") public val clearConnectionsPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "clear_connections") public val forceConnectionDragEndPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "force_connection_drag_end") public val getScrollOffsetPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_scroll_offset") public val setScrollOffsetPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_scroll_offset") public val addValidRightDisconnectTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "add_valid_right_disconnect_type") public val removeValidRightDisconnectTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "remove_valid_right_disconnect_type") public val addValidLeftDisconnectTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "add_valid_left_disconnect_type") public val removeValidLeftDisconnectTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "remove_valid_left_disconnect_type") public val addValidConnectionTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "add_valid_connection_type") public val removeValidConnectionTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "remove_valid_connection_type") public val isValidConnectionTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_valid_connection_type") public val getConnectionLinePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_connection_line") public val setPanningSchemePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_panning_scheme") public val getPanningSchemePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_panning_scheme") public val setZoomPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_zoom") public val getZoomPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_zoom") public val setZoomMinPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_zoom_min") public val getZoomMinPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_zoom_min") public val setZoomMaxPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_zoom_max") public val getZoomMaxPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_zoom_max") public val setZoomStepPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_zoom_step") public val getZoomStepPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_zoom_step") public val setShowGridPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_grid") public val isShowingGridPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_grid") public val setSnappingEnabledPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_snapping_enabled") public val isSnappingEnabledPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_snapping_enabled") public val setSnappingDistancePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_snapping_distance") public val getSnappingDistancePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_snapping_distance") public val setConnectionLinesCurvaturePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_connection_lines_curvature") public val getConnectionLinesCurvaturePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_connection_lines_curvature") public val setConnectionLinesThicknessPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_connection_lines_thickness") public val getConnectionLinesThicknessPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_connection_lines_thickness") public val setConnectionLinesAntialiasedPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_connection_lines_antialiased") public val isConnectionLinesAntialiasedPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_connection_lines_antialiased") public val setMinimapSizePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_minimap_size") public val getMinimapSizePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_minimap_size") public val setMinimapOpacityPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_minimap_opacity") public val getMinimapOpacityPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_minimap_opacity") public val setMinimapEnabledPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_minimap_enabled") public val isMinimapEnabledPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_minimap_enabled") public val setShowMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_menu") public val isShowingMenuPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_menu") public val setShowZoomLabelPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_zoom_label") public val isShowingZoomLabelPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_zoom_label") public val setShowGridButtonsPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_grid_buttons") public val isShowingGridButtonsPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_grid_buttons") public val setShowZoomButtonsPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_zoom_buttons") public val isShowingZoomButtonsPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_zoom_buttons") public val setShowMinimapButtonPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_minimap_button") public val isShowingMinimapButtonPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_minimap_button") public val setShowArrangeButtonPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_show_arrange_button") public val isShowingArrangeButtonPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_showing_arrange_button") public val setRightDisconnectsPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_right_disconnects") public val isRightDisconnectsEnabledPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "is_right_disconnects_enabled") public val getMenuHboxPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "get_menu_hbox") public val arrangeNodesPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "arrange_nodes") public val setSelectedPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphEdit", "set_selected") } }
69
Kotlin
39
580
fd1af79075e7b918200aba3302496b70c76a2028
39,518
godot-kotlin-jvm
MIT License
src/test/kotlin/no/nav/helse/spout/AuditloggTest.kt
navikt
617,935,079
false
{"Kotlin": 23973, "HTML": 19781, "CSS": 5446, "JavaScript": 3846, "Dockerfile": 168}
package no.nav.helse.spout import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import java.time.LocalDateTime import java.util.UUID internal class AuditloggTest { @Test fun `logger audit på rett format`() { val tidspunkt = LocalDateTime.parse("2023-03-23T23:00:00.000000") val id = UUID.fromString("5beb1241-d2db-436e-a5e5-8f7712bdeca3") val melding = AuditOgSikkerlogg.auditMelding( navIdent = "X123456", fødselsnummer = "12345678910", tidspunkt = tidspunkt, eventName = "et_kult_event", id = id, begrunnelse = "Skal bare gjøre noen greier" ) val expected = "CEF:0|Spout|auditLog|1.0|audit:update|Sporingslogg|INFO|end=1679608800000 duid=12345678910 suid=X123456 request=et_kult_event sproc=5beb1241-d2db-436e-a5e5-8f7712bdeca3 msg=Skal bare gjøre noen greier" assertEquals(expected, melding) } }
0
Kotlin
0
0
568e70c7b23b714a7f8840c86391f0eeb5805b7a
970
helse-spout
MIT License
android-buddy-plugin/src/main/java/com/likethesalad/android/common/utils/Constants.kt
LikeTheSalad
289,290,234
false
null
package com.likethesalad.android.common.utils object Constants { const val LIBRARY_METADATA_DIR = "META-INF/android-buddy-plugins" const val PLUGINS_METADATA_FILE_NAME = "library_definition" const val PLUGINS_METADATA_FILE_EXT = "class" }
0
Kotlin
6
43
1089f89e1f8ad5fb9fdfb9195592cc8a7d04e299
251
android-buddy
MIT License
precompose/src/macosMain/kotlin/moe/tlaster/precompose/PreComposeWindow.kt
Tlaster
349,750,473
false
{"Kotlin": 191657}
package moe.tlaster.precompose import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.ExperimentalComposeApi import androidx.compose.runtime.remember import androidx.compose.ui.window.Window import moe.tlaster.precompose.lifecycle.LifecycleOwner import moe.tlaster.precompose.lifecycle.LifecycleRegistry import moe.tlaster.precompose.lifecycle.LocalLifecycleOwner import moe.tlaster.precompose.stateholder.LocalStateHolder import moe.tlaster.precompose.stateholder.StateHolder import moe.tlaster.precompose.ui.BackDispatcher import moe.tlaster.precompose.ui.BackDispatcherOwner import moe.tlaster.precompose.ui.LocalBackDispatcherOwner @ExperimentalComposeApi fun PreComposeWindow( title: String, // hideTitleBar: Boolean = false, // onCloseRequest: () -> Unit = {}, // onMinimizeRequest: () -> Unit = {}, // onDeminiaturizeRequest: () -> Unit = {}, content: @Composable () -> Unit, ) { // Ugly workaround until Native macOS support window resize and hide title bar. Window( title = title, content = { PreComposeApp { content.invoke() } }, ) } @Composable actual fun PreComposeApp( content: @Composable () -> Unit, ) { ProvidePreComposeCompositionLocals { content.invoke() } } @Composable fun ProvidePreComposeCompositionLocals( holder: PreComposeWindowHolder = remember { PreComposeWindowHolder() }, content: @Composable () -> Unit, ) { CompositionLocalProvider( LocalLifecycleOwner provides holder, LocalStateHolder provides holder.stateHolder, LocalBackDispatcherOwner provides holder, ) { content.invoke() } } class PreComposeWindowHolder : LifecycleOwner, BackDispatcherOwner { override val lifecycle by lazy { LifecycleRegistry() } val stateHolder by lazy { StateHolder() } override val backDispatcher by lazy { BackDispatcher() } }
40
Kotlin
49
849
276c933397d94b8dfc60b809942bc38b23d945bd
2,053
PreCompose
MIT License
app/src/main/java/com/jetpack/composemotionlayout/MotionLayoutHeader.kt
MakeItEasyDev
465,383,485
false
{"Kotlin": 12544}
package com.jetpack.composemotionlayout import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.MotionLayout @OptIn(ExperimentalMaterialApi::class, ExperimentalComposeUiApi::class) @Composable fun MotionLayoutHeader(progress: Float, scrollableBody: @Composable () -> Unit) { MotionLayout( start = JsonConstraintSetStart(), end = JsonConstraintSetEnd(), progress = progress, modifier = Modifier .fillMaxWidth() ) { Image( painter = painterResource(id = R.drawable.image), contentDescription = "poster", modifier = Modifier .layoutId("poster") .background(MaterialTheme.colors.primary), contentScale = ContentScale.FillWidth, alpha = 1f - progress ) Text( text = "Make it Easy", modifier = Modifier .layoutId("title") .wrapContentHeight(), color = motionColor("title", "textColor"), fontSize = motionFontSize("title", "textSize"), style = MaterialTheme.typography.h6, textAlign = TextAlign.Center ) Box( Modifier .layoutId("content") ) { scrollableBody() } } } @Composable private fun JsonConstraintSetStart() = ConstraintSet (""" { poster: { width: "spread", start: ['parent', 'start', 0], end: ['parent', 'end', 0], top: ['parent', 'top', 0], }, title: { top: ['poster', 'bottom', 16], start: ['parent', 'start', 16], custom: { textColor: "#000000", textSize: 40 } }, content: { width: "spread", start: ['parent', 'start', 0], end: ['parent', 'end', 0], top: ['title', 'bottom', 16], } } """ ) @Composable private fun JsonConstraintSetEnd() = ConstraintSet (""" { poster: { width: "spread", height: 56, start: ['parent', 'start', 0], end: ['parent', 'end', 0], top: ['parent', 'top', 0], }, title: { top: ['parent', 'top', 0], start: ['parent', 'start', 0], end: ['parent', 'end', 0], bottom: ['poster', 'bottom', 0], custom: { textColor: "#ffffff", textSize: 20 } }, content: { width: "spread", start: ['parent', 'start', 0], end: ['parent', 'end', 0], top: ['poster', 'bottom', 0], } } """)
0
Kotlin
2
7
359e78f49bdc8934a3f8da04830de82e62691781
3,097
Jetpack-Compose-Collapse-Toolbar-Motion-Layout
Apache License 2.0
app/src/main/java/com/gvkorea/gvktune/view/view/data/presenter/DataPresenter.kt
NewTurn2017
243,805,460
false
null
package com.gvkorea.gvktune.view.view.data.presenter import android.content.SharedPreferences import android.os.Handler import android.widget.Toast import com.gvkorea.gvktune.MainActivity.Companion.isSelected_CH1 import com.gvkorea.gvktune.MainActivity.Companion.isSelected_CH2 import com.gvkorea.gvktune.MainActivity.Companion.isSelected_CHA import com.gvkorea.gvktune.MainActivity.Companion.prefSettings import com.gvkorea.gvktune.MainActivity.Companion.selectedClient import com.gvkorea.gvktune.util.Protocol import com.gvkorea.gvktune.util.TimeUtils import com.gvkorea.gvktune.view.view.data.DataFragment import com.gvkorea.gvktune.view.view.data.DataFragment.Companion.noiseVolume import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.avgStart import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq1Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq2Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq3Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq4Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq5Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq6Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq7Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq8Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq9Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq10Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq11Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq12Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq13Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq14Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq15Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq16Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq17Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq18Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq19Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq20Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq21Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq22Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq23Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq24Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq25Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq26Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq27Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq28Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq29Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq30Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freq31Sum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.freqSum import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.isMeasure import com.gvkorea.gvktune.view.view.data.util.audio.RecordAudioRTA_31.Companion.spldB31 import com.opencsv.CSVWriter import kotlinx.android.synthetic.main.fragment_data.* import java.io.* import java.text.DecimalFormat import kotlin.collections.ArrayList import kotlin.random.Random class DataPresenter(val view: DataFragment, val handler: Handler, var tx_buff: ByteArray, val pref: SharedPreferences) { val timeUtils = TimeUtils() val NOISE_OFF = 3 val SWEEP = 0 val PINK = 2 val WHITE = 1 var protocol: Protocol = Protocol() private lateinit var outputStream: OutputStream private lateinit var dataOutputStream: DataOutputStream private lateinit var inputStream: InputStream private lateinit var dataInputStream: DataInputStream private val CMD_NOISE = 8 private val CHNNEL_INPUT = 0 private val CHNNEL_OUTPUT = 2 private val NFILT_0 = 0 private val NFILT_1 = 1 private val NFILT_2 = 2 private val NFILT_3 = 3 private val NFILT_4 = 4 private val CMD_EQ = 5 private val EQINTERVAL = 50L private val CHECKINTERVAL = 50L val avgArray = Array(100) { DoubleArray(10) } val rmsAfterAvg = DoubleArray(10) private val ranEQ = IntArray(31) val CMD_PARA2_CH1 = '1' val CMD_PARA2_CH2 = '2' val CMD_PARA2_CHA = 'A' private var writer: CSVWriter? = null private var dataCount = 1 fun mesureAvg(isStart: Boolean) { if (isStart) { handler.postDelayed({ freq1Sum = ArrayList() freq2Sum = ArrayList() freq3Sum = ArrayList() freq4Sum = ArrayList() freq5Sum = ArrayList() freq6Sum = ArrayList() freq7Sum = ArrayList() freq8Sum = ArrayList() freq9Sum = ArrayList() freq10Sum = ArrayList() freq11Sum = ArrayList() freq12Sum = ArrayList() freq13Sum = ArrayList() freq14Sum = ArrayList() freq15Sum = ArrayList() freq16Sum = ArrayList() freq17Sum = ArrayList() freq18Sum = ArrayList() freq19Sum = ArrayList() freq20Sum = ArrayList() freq21Sum = ArrayList() freq22Sum = ArrayList() freq23Sum = ArrayList() freq24Sum = ArrayList() freq25Sum = ArrayList() freq26Sum = ArrayList() freq27Sum = ArrayList() freq28Sum = ArrayList() freq29Sum = ArrayList() freq30Sum = ArrayList() freq31Sum = ArrayList() freqSum = ArrayList() avgStart = true isMeasure = true }, 100) } else { avgStart = true isMeasure = false } } fun eqReset() { SendPacket_InputGEQ_Reset(selectedChannal()) } fun selectedChannal(): Char { var para2 = 'A' when { isSelected_CH1 -> { para2 = CMD_PARA2_CH1 } isSelected_CH2 -> { para2 = CMD_PARA2_CH2 } isSelected_CHA -> { para2 = CMD_PARA2_CHA } } return para2 } fun SendPacket_InputGEQ_Reset(para2: Char) { if (selectedClient != null) { try { tx_buff = protocol.packet_input_EQ_Reset(para2) outputStream = selectedClient!!.getOutputStream() dataOutputStream = DataOutputStream(outputStream) } catch (e: Exception) { e.printStackTrace() } Thread { try { dataOutputStream.write(tx_buff, 0, tx_buff.size) dataOutputStream.flush() } catch (e: IOException) { e.printStackTrace() } }.start() try { Thread.sleep(EQINTERVAL) } catch (e: InterruptedException) { e.printStackTrace() } Thread.currentThread() Thread.interrupted() } else { msg("TCP Socket 연결 안됨") } } private fun msg(msg: String) { Toast.makeText(view.context, msg, Toast.LENGTH_SHORT).show() } fun gainDataStart() { view.btn_start.text = "진행중" view.btn_start.isEnabled = false eqReset() handler.postDelayed({ noiseVolume = -40 NoiseVolumeControl(noiseVolume) }, 200) } fun noise(noise: Int, gain: Int) { if (noise != NOISE_OFF) { val para2 = selectedChannal() SendPacket_NoiseGenerator(para2, noise, gain.toFloat(), 1) } else { val para2 = selectedChannal() SendPacket_NoiseGenerator(para2, PINK, gain.toFloat(), 0) } } fun NoiseVolumeControl(progress: Int) { noise(PINK, progress) handler.postDelayed({ val targetdB = view.sp_dataSpkVolume.selectedItem.toString().toInt() if (spldB31.toInt() < targetdB) { noiseVolume++ NoiseVolumeControl(noiseVolume) } else { handler.postDelayed({ // 데이터 수집 시작 noise(NOISE_OFF, progress) dataMiningStart() }, 100) } }, 500) } //수동설정 //avgTime -> 16k = 1500L 8k = 1100L 4k = 1100L val avgTime = 1100L val noOfdataGathering = 3000 private fun dataMiningStart() { for (i in ranEQ.indices) { if(i < 6){ ranEQ[i] = (25..35).random() }else{ ranEQ[i] = randomRange() } } // SendPacket_InputGEQ_ALL_Manual(ranEQ) SendPacket_EQ_All(selectedChannal(), ranEQ) handler.postDelayed({ averageRMS_For_Data() }, 100) handler.postDelayed({ CSV_Save() }, 300 + avgTime + 500) // avg time + 500 handler.postDelayed({ repeatDataGathering() }, 300 + avgTime + 700) } fun SendPacket_NoiseGenerator( para2: Char, data0: Int, data1: Float, data5: Int ) { if (selectedClient != null) { try { tx_buff = protocol.packet_NoiseGenerator( para2, data0, data1, data5 ) outputStream = selectedClient!!.getOutputStream() dataOutputStream = DataOutputStream(outputStream) } catch (e: Exception) { e.printStackTrace() } Thread { try { dataOutputStream.write(tx_buff, 0, tx_buff.size) dataOutputStream.flush() } catch (e: IOException) { e.printStackTrace() } }.start() try { Thread.sleep(CHECKINTERVAL) } catch (e: InterruptedException) { e.printStackTrace() } Thread.currentThread() Thread.interrupted() } else { msg("TCP Socket 연결 안됨") } } private fun repeatDataGathering() { if (dataCount > noOfdataGathering) { CSV_Save() view.btn_start.text = "수집 시작" view.btn_start.isEnabled = true view.btn_start.alpha = 1f } else { dataMiningStart() } } private fun CSV_Save() { // 파일 생성 if (writer == null) { val baseDir = android.os.Environment.getExternalStorageDirectory().absolutePath val filename = "data_" + dataCount + "_" + timeUtils.getDate() + "_reverb(${prefSettings.getReverbTimePref()})" +"_${view.sp_dataSpkModel.selectedItem}" + "_${view.sp_dataSpkVolume.selectedItem}" + ".csv" val filePath = baseDir + File.separator + filename try { writer = CSVWriter(FileWriter(filePath, true)) } catch (e: IOException) { e.printStackTrace() } CSV_recordForData() } else { // 파일 생성 하지 않고 기록 CSV_recordForData() } if (dataCount > 1) { if (dataCount % 10 == 0) { CSV_SaveForData() } } dataCount++ } private fun CSV_recordForData() { // val CurRMS = arrayOfNulls<String>(10) val CurEQVal = arrayOfNulls<String>(31) val datafile = arrayOfNulls<String>(63) for (i in 0..30) { CurEQVal[i] = ranEQ[i].toString() } for (i in 0..62) { when { i < 1 -> datafile[i] = dataCount.toString() i < 32 -> datafile[i] = CurEQVal[i - 1] //현재 EQ값 i < 63 -> datafile[i] = freqSum[i - 32] // 측정값 dB } } if (writer != null) { writer!!.writeNext(datafile) msg(dataCount.toString() + "번째 데이터 저장되었습니다.") } } private fun CSV_SaveForData() { try { writer?.close() writer = null msg("데이터 중간 저장합니다.") } catch (e: IOException) { e.printStackTrace() } } private fun doubleToString(value: Double): String { val format = DecimalFormat("##.#") return format.format(value) } private fun SendPacket_EQ_All(para2: Char, ranEQ: IntArray) { val ranEQToFloat = changeRandomEQToFloatArray(ranEQ) if (selectedClient != null) { try { tx_buff = protocol.packet_InputGEQ_All(para2, ranEQToFloat) outputStream = selectedClient!!.getOutputStream() dataOutputStream = DataOutputStream(outputStream) } catch (e: Exception) { e.printStackTrace() } Thread { try { dataOutputStream.write(tx_buff, 0, tx_buff.size) dataOutputStream.flush() } catch (e: IOException) { e.printStackTrace() } }.start() try { Thread.sleep(EQINTERVAL) } catch (e: InterruptedException) { e.printStackTrace() } Thread.currentThread() Thread.interrupted() } else { msg("TCP Socket 연결 안됨") } } private fun changeRandomEQToFloatArray(ranEQ: IntArray): FloatArray { val ranEQFloatArray = FloatArray(ranEQ.size) for (i in ranEQ.indices) { ranEQFloatArray[i] = ranEQ[i] * 0.5f - 15 } return ranEQFloatArray } private fun randomRange(): Int { return (Math.random() * 61).toInt()// 0~60 // 25~48 : (int) (Math.random() * 25) + 24; } private fun randomRange(diffValue: Int): Int { val max = 30 + diffValue val min = 30 - diffValue return (Math.random() * (max - min + 1)).toInt() + min } fun averageRMS_For_Data() { noise(PINK, noiseVolume) mesureAvg(true) handler.postDelayed({ mesureAvg(false) noise(NOISE_OFF, noiseVolume) }, avgTime) } fun gainDataStop() { dataCount = 1 noise(NOISE_OFF, noiseVolume) handler.removeMessages(0) view.btn_start.text = "수집 시작" view.btn_start.isEnabled = true view.btn_start.alpha = 1f if (writer != null) { try { writer?.close() } catch (e: IOException) { e.printStackTrace() } writer = null msg("데이터를 저장하고 종료합니다...") } } }
1
null
1
1
afaa1be61f6f1cc3fb6db213aaaa081483144ce5
15,836
GVKTUNE
MIT License
game-engine/src/main/kotlin/com/zenika/ageofdevsecops/infrastructure/challenge/JdbcPlayerScoreRepository.kt
zenika-open-source
176,924,113
false
null
package com.zenika.ageofdevsecops.infrastructure.challenge import com.zenika.ageofdevsecops.domain.challenge.PlayerScore import com.zenika.ageofdevsecops.domain.challenge.PlayerScoreRepository import org.springframework.jdbc.core.JdbcTemplate import org.springframework.stereotype.Repository @Repository class JdbcPlayerScoreRepository(val jdbcTemplate: JdbcTemplate) : PlayerScoreRepository { override fun save(playerScore: PlayerScore) { val sql = "REPLACE INTO SCORES(playerId,score,progression,devPoint,secPoint,opsPoint) VALUES (?,?,?,?,?,?)" jdbcTemplate.update(sql, playerScore.playerId, playerScore.score, playerScore.progression, playerScore.devPoint, playerScore.secPoint, playerScore.opsPoint) } override fun findAll(): List<PlayerScore> { val sql = "SELECT playerId,score,progression,devPoint,secPoint,opsPoint FROM SCORES" return jdbcTemplate.query(sql) { rs, _ -> PlayerScore( rs.getString("playerId"), rs.getInt("score"), rs.getInt("progression"), rs.getInt("devPoint"), rs.getInt("secPoint"), rs.getInt("opsPoint")) } } }
34
Kotlin
6
8
be41076dd729649eff49633e20745fa917a544a4
1,234
age-of-devsecops
Apache License 2.0
app/src/main/java/com/example/affirmations/MainActivity.kt
IvanRellanSan
603,903,090
false
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.affirmations import android.os.Bundle import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import com.example.affirmations.ui.components.AffirmationList import com.example.affirmations.ui.components.TopBar import com.example.affirmations.ui.theme.AffirmationsTheme import com.example.affirmations.ui.viewmodel.MainViewModel private const val tag = "MainActivity" class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) Log.d(tag, "onCreate called!") setContent { // TODO 5. Show screen AffirmationApp() } } override fun onStart() { super.onStart() Log.d(tag, "onStart called!") } override fun onResume() { super.onResume() Log.d(tag, "onResume called!") } override fun onRestart() { super.onRestart() Log.d(tag, "onRestart called!") } override fun onPause() { super.onPause() Log.d(tag, "onPause called!") } override fun onStop() { super.onStop() Log.d(tag, "onStop called!") } override fun onDestroy() { super.onDestroy() Log.d(tag, "onDestroy called!") } } @Composable fun AffirmationApp( mainViewModel: MainViewModel = MainViewModel() ) { // TODO 4. Apply Theme and affirmation list mainViewModel.loadData() val affirmations by mainViewModel.listState.collectAsState() AffirmationsTheme{ val scaffoldState = rememberScaffoldState() Scaffold( scaffoldState = scaffoldState, topBar = { TopBar() } ) { Column { // TextButtonComponent() AffirmationList( affirmations, modifier = Modifier .background( color = MaterialTheme.colors.background ) ) } } } }
0
Kotlin
0
0
613b4a253a0fc1f9db65655613729b6c599030cd
2,778
ComposeTrainingAffirmations
Apache License 2.0
server/src/main/kotlin/com/example/Application.kt
egdegd
411,764,804
true
{"Kotlin": 8608, "HTML": 2815, "JavaScript": 907}
package com.example import com.example.plugins.* import io.ktor.application.* import io.ktor.features.* import io.ktor.serialization.* fun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args) val Application.secret: String get() = environment.config.property("jwt.secret").getString() val Application.issuer: String get() = environment.config.property("jwt.issuer").getString() val Application.audience: String get() = environment.config.property("jwt.audience").getString() val Application.myRealm: String get() = environment.config.property("jwt.realm").getString() fun Application.module() { install(ContentNegotiation) { json() } configureSecurity() configureRouting() }
0
null
0
0
eb606832c9e4ef104aec982764a980f39192f742
726
memster
MIT License
features/ranges-practice/domain/src/main/java/com/mctech/pokergrinder/ranges_practice/domain/usecases/ObserveRangePracticeResultUseCase.kt
MayconCardoso
539,349,342
false
null
package com.mctech.pokergrinder.ranges_practice.domain.usecases import com.mctech.pokergrinder.ranges_practice.domain.RangesPracticeRepository import com.mctech.pokergrinder.ranges_practice.domain.entities.RangePracticeResult import kotlinx.coroutines.flow.Flow import javax.inject.Inject /** * Used to observe all ranges. * * @property repository grind data repository. */ class ObserveRangePracticeResultUseCase @Inject constructor( private val repository: RangesPracticeRepository, ) { operator fun invoke(): Flow<List<RangePracticeResult>> { return repository.observePracticeResult() } }
7
Kotlin
0
7
d4a6f48fa73c0259d87934873a8ccb63b53694f3
609
poker-grinder
Apache License 2.0
app/src/main/kotlin/com/deviseworks/mcc/frontend/component/content/PlayerListTab.kt
rokuosan
465,776,797
false
{"Kotlin": 31673, "HTML": 471, "CSS": 417}
package com.deviseworks.mcc.frontend.component.content import com.deviseworks.mcc.frontend.common.API import com.deviseworks.mcc.frontend.entity.Player import csstype.Display import csstype.FlexWrap import kotlinx.browser.window import kotlinx.coroutines.MainScope import kotlinx.coroutines.await import kotlinx.coroutines.launch import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json import mui.material.Box import mui.system.sx import react.FC import react.Props import react.useEffectOnce import react.useState val PlayerListTab = FC<Props> { var playerList: List<Player> by useState(emptyList()) useEffectOnce { mainScope.launch { playerList = fetchPlayerList() } } Box{ sx{ display = Display.flex flexWrap = FlexWrap.wrap } playerList.forEachIndexed { _, player -> PlayerListItem{ data = player } } } } private val mainScope = MainScope() suspend fun fetchPlayerList(): List<Player>{ val response = window .fetch( API.PLAYER_LIST+"?offline=true" ) .await() .text() .await() return Json.decodeFromString(ListSerializer(Player.serializer()), response) // var res: HttpResponse? = null // // coroutineScope { // launch{ // val job = launch{ // res = client.get(API.PLAYER_LIST){ // headers{ // append("Access-Control-Allow-Origin", "*") // } // parameter("offline", "true") // } // } // job.join() // } // } // // val json: String = res!!.receive() // // return Json.decodeFromString(ListSerializer(Player.serializer()), json) }
0
Kotlin
0
0
5090f2cfe51d5e7926f5d408ac9fd2164fa2ecb0
1,852
mcc-frontend
MIT License
backend-integration/researchstack-adapter/src/main/kotlin/researchstack/backend/integration/adapter/outgoing/AppLogAdapter.kt
S-ResearchStack
520,365,275
false
{"Kotlin": 178868, "AIDL": 4785}
package researchstack.backend.integration.adapter.outgoing import researchstack.backend.grpc.AppLog import researchstack.backend.grpc.AppLogServiceGrpcKt.AppLogServiceCoroutineStub import researchstack.backend.integration.outport.AppLogOutPort import javax.inject.Inject class AppLogAdapter @Inject constructor( private val appLogServiceCoroutineStub: AppLogServiceCoroutineStub ) : AppLogOutPort { override suspend fun sendAppLog(appLog: AppLog): Result<Unit> = kotlin.runCatching { appLogServiceCoroutineStub.sendAppLog(appLog) } }
0
Kotlin
20
26
58b4b9b64623a7d2a0865307d490a59a7538d7cd
556
app-sdk
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/sam/CfnFunctionLogGroupSAMPTPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package io.cloudshiftdev.awscdkdsl.services.sam import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.sam.CfnFunction /** * Example: * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.sam.*; * LogGroupSAMPTProperty logGroupSAMPTProperty = LogGroupSAMPTProperty.builder() * .logGroupName("logGroupName") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-serverless-function-loggroupsampt.html) */ @CdkDslMarker public class CfnFunctionLogGroupSAMPTPropertyDsl { private val cdkBuilder: CfnFunction.LogGroupSAMPTProperty.Builder = CfnFunction.LogGroupSAMPTProperty.builder() /** @param logGroupName the value to be set. */ public fun logGroupName(logGroupName: String) { cdkBuilder.logGroupName(logGroupName) } public fun build(): CfnFunction.LogGroupSAMPTProperty = cdkBuilder.build() }
3
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,299
awscdk-dsl-kotlin
Apache License 2.0
console/src/main/java/com/jraska/console/ConsoleController.kt
jraska
46,227,952
false
null
package com.jraska.console import android.os.Handler import android.os.Looper import android.os.Message import android.text.SpannableString import android.widget.TextView import java.lang.ref.WeakReference import java.util.ArrayList internal class ConsoleController { val consoles: MutableList<WeakReference<Console>> = ArrayList() val buffer = ConsoleBuffer() private val printBufferHandler: Handler by lazy { PrintBufferHandler(this) } private val isUIThread: Boolean get() = Looper.myLooper() == Looper.getMainLooper() fun add(console: Console) { consoles.add(WeakReference(console)) } fun writeLine() { write(END_LINE) } fun writeLine(o: Any?) { buffer.append(o).append(END_LINE) scheduleBufferPrint() } fun write(spannableString: SpannableString?) { buffer.append(spannableString) scheduleBufferPrint() } fun writeLine(spannableString: SpannableString?) { buffer.append(spannableString).append(END_LINE) scheduleBufferPrint() } fun write(o: Any?) { buffer.append(o) scheduleBufferPrint() } fun clear() { buffer.clear() scheduleBufferPrint() } fun scheduleBufferPrint() { runBufferPrint() } fun size(): Int { return consoles.size } fun printTo(text: TextView) { buffer.printTo(text) } private fun runBufferPrint() { if (!isUIThread) { if (!printBufferHandler.hasMessages(PRINT_BUFFER)) { printBufferHandler.obtainMessage(PRINT_BUFFER).sendToTarget() } return } val iterator = consoles.iterator() while (iterator.hasNext()) { val console = iterator.next().get() if (console == null) { iterator.remove() } else { console.printScroll() } } } private class PrintBufferHandler(val controller: ConsoleController) : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { if (msg.what == PRINT_BUFFER) { controller.runBufferPrint() } } } companion object { val END_LINE = "\n" const val PRINT_BUFFER = 653276 } }
1
null
16
129
0af968f742d9ed928288f69829df41033c187c29
2,097
Console
Apache License 2.0
androidApp/src/main/java/gcu/production/stavlenta/android/domain/models/base/HomeModel.kt
Ilyandr
576,032,482
false
null
package gcu.production.stavlenta.android.domain.models.base import androidx.annotation.StringRes import gcu.production.stavlenta.repository.model.TapeModel internal sealed class HomeModel { object DefaultState: HomeModel() object LoadingState: HomeModel() data class SuccessLoadState(val data: List<TapeModel>): HomeModel() data class FaultLoadState(@StringRes val messageId: Int): HomeModel() }
0
Kotlin
0
1
4e797410e7482cffebdc5b988fa7819b3ebd4a77
418
StavLenta-multiplatform
MIT License
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/ConcurrentTestSuiteScheduler.kt
kotest
47,071,082
false
null
package io.kotest.engine import io.kotest.common.ExperimentalKotest import io.kotest.core.annotation.DoNotParallelize import io.kotest.core.annotation.Isolate import io.kotest.core.project.TestSuite import io.kotest.core.spec.SpecRef import io.kotest.engine.concurrency.defaultCoroutineDispatcherFactory import io.kotest.engine.concurrency.isIsolate import io.kotest.engine.interceptors.EngineContext import io.kotest.engine.listener.TestEngineListener import io.kotest.engine.spec.SpecExecutor import io.kotest.mpp.Logger import io.kotest.mpp.bestName import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit /** * A [TestSuiteScheduler] that schedules specs concurrently, up to a provided [maxConcurrent] value. * If the value is 1 then this scheduler will execute specs strictly sequentially. * * Additionally, on JVM targets, it will recognize the [Isolate] and [DoNotParallelize] * annotations to ensure those specs are never scheduled concurrently. * * @param maxConcurrent The maximum number of concurrent coroutines. */ @ExperimentalKotest internal class ConcurrentTestSuiteScheduler( private val maxConcurrent: Int, private val context: EngineContext, ) : TestSuiteScheduler { private val logger = Logger(ConcurrentTestSuiteScheduler::class) override suspend fun schedule(suite: TestSuite, listener: TestEngineListener): EngineResult { logger.log { Pair(null, "Launching ${suite.specs.size} specs") } val (sequential, concurrent) = suite.specs.partition { it.kclass.isIsolate() } logger.log { Pair(null, "Split on isIsolate: ${sequential.size} sequential ${concurrent.size} concurrent") } schedule(concurrent, listener, maxConcurrent) logger.log { Pair(null, "Concurrent specs have completed") } schedule(sequential, listener, 1) logger.log { Pair(null, "Sequential specs have completed") } return EngineResult(emptyList()) } private suspend fun schedule( specs: List<SpecRef>, listener: TestEngineListener, concurrency: Int, ) = coroutineScope { // we don't want this function to return until all specs are completed val coroutineDispatcherFactory = defaultCoroutineDispatcherFactory(context.configuration) val semaphore = Semaphore(concurrency) specs.forEach { ref -> logger.log { Pair(ref.kclass.bestName(), "Scheduling coroutine") } launch { semaphore.withPermit { logger.log { Pair(ref.kclass.bestName(), "Acquired permit") } try { val executor = SpecExecutor( listener, coroutineDispatcherFactory, context ) logger.log { Pair(ref.kclass.bestName(), "Executing ref") } executor.execute(ref) } catch (t: Throwable) { logger.log { Pair(ref.kclass.bestName(), "Unhandled error during spec execution $t") } throw t } } logger.log { Pair(ref.kclass.bestName(), "Released permit") } } } } }
98
null
648
4,435
2ce83d0f79e189c90e2d7bb3d16bd4f75dec9c2f
3,224
kotest
Apache License 2.0
modules/backend/discord/src/main/kotlin/com/lhwdev/bot/backend/discord/DiscordBackend.kt
lhwdev
412,778,971
false
{"Kotlin": 64983}
package com.lhwdev.bot.backend.discord import com.lhwdev.bot.backend.BotBackend import dev.kord.core.Kord import dev.kord.core.behavior.reply import dev.kord.core.event.interaction.InteractionCreateEvent import dev.kord.core.event.message.MessageCreateEvent import dev.kord.core.on class DiscordBackend : BotBackend { suspend fun hi() { val kord = Kord("") { enableShutdownHook = true } kord.on<MessageCreateEvent> { message.reply { } } kord.on<InteractionCreateEvent> { } } }
0
Kotlin
0
0
0f3c0ae152d4bb10e7883cb0fa6dc35fe08edcfb
510
lhwdev-bot
MIT License
inputview-transform/src/main/kotlin/com/xiaocydx/inputview/transform/transformer/TransformerOwner.kt
xiaocydx
586,406,251
false
{"Kotlin": 492620}
/* * Copyright 2023 xiaocydx * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("PackageDirectoryMismatch") package com.xiaocydx.inputview.transform import android.view.View import androidx.annotation.VisibleForTesting /** * [Transformer]所有者 * * @author xcc * @date 2024/7/24 */ interface TransformerOwner { /** * 是否包含[transformer] */ fun has(transformer: Transformer): Boolean /** * 添加[Transformer] */ fun add(transformer: Transformer) /** * 移除[add]添加的[transformer] */ fun remove(transformer: Transformer) /** * 请求重新分发调用[transformer]的函数 */ fun requestTransform(transformer: Transformer) } internal fun View.getTransformerHost(): TransformerOwner? { return getTag(R.id.tag_transform_view_transformer_host) as? TransformerOwner } internal fun View.setTransformerHost(host: TransformerOwner) { setTag(R.id.tag_transform_view_transformer_host, host) } internal fun View.viewTransform(): ViewTransformerOwner { var owner = getTag(R.id.tag_transform_view_transformer_owner) as? ViewTransformerOwner if (owner == null) { owner = ViewTransformerOwner(this) setTag(R.id.tag_transform_view_transformer_owner, owner) } return owner } internal class ViewTransformerOwner( private val view: View ) : TransformerOwner, View.OnAttachStateChangeListener { private val transformers = mutableListOf<Transformer>() private var host: TransformerOwner? = null init { view.addOnAttachStateChangeListener(this) if (view.isAttachedToWindow) onViewAttachedToWindow(view) } @VisibleForTesting fun setHost(host: TransformerOwner) { require(this.host == null) this.host = host } override fun onViewAttachedToWindow(v: View) { // attach在onPrepare()执行,此时transformers的函数还未分发调用 if (host == null) host = findHost() val host = host ?: return for (i in transformers.indices) host.add(transformers[i]) } override fun onViewDetachedFromWindow(v: View) { // detach在onPrepare()或onEnd()执行,此时transformers的函数分发调用完毕 val host = host ?: return for (i in transformers.indices) host.remove(transformers[i]) } override fun has(transformer: Transformer): Boolean { return transformers.contains(transformer) } override fun add(transformer: Transformer) { if (has(transformer)) return transformers.add(transformer) if (view.isAttachedToWindow) host?.add(transformer) } override fun remove(transformer: Transformer) { transformers.remove(transformer) host?.remove(transformer) } override fun requestTransform(transformer: Transformer) { host?.requestTransform(transformer) } private fun findHost(): TransformerOwner? { var parent = view.parent as? View while (parent != null) { val host = parent.getTransformerHost() if (host != null) break parent = parent.parent as? View } return parent?.getTransformerHost() } }
0
Kotlin
0
7
2006486734eefe98bbc3dd432bde44cac267dbee
3,627
InputView
Apache License 2.0
compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/DeclarationOrigins.kt
android
263,405,600
false
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.jvm import org.jetbrains.kotlin.ir.declarations.IrDeclarationOrigin import org.jetbrains.kotlin.ir.declarations.IrDeclarationOriginImpl interface JvmLoweredDeclarationOrigin : IrDeclarationOrigin { object CLASS_STATIC_INITIALIZER : IrDeclarationOriginImpl("CLASS_STATIC_INITIALIZER") object DEFAULT_IMPLS : IrDeclarationOriginImpl("DEFAULT_IMPLS") object DEFAULT_IMPLS_BRIDGE : IrDeclarationOriginImpl("DEFAULT_IMPLS_BRIDGE") object DEFAULT_IMPLS_BRIDGE_TO_SYNTHETIC : IrDeclarationOriginImpl("DEFAULT_IMPLS_BRIDGE_TO_SYNTHETIC", isSynthetic = true) object MULTIFILE_BRIDGE : IrDeclarationOriginImpl("MULTIFILE_BRIDGE") object FIELD_FOR_OUTER_THIS : IrDeclarationOriginImpl("FIELD_FOR_OUTER_THIS") object LAMBDA_IMPL : IrDeclarationOriginImpl("LAMBDA_IMPL") object FUNCTION_REFERENCE_IMPL : IrDeclarationOriginImpl("FUNCTION_REFERENCE_IMPL", isSynthetic = true) object SYNTHETIC_ACCESSOR : IrDeclarationOriginImpl("SYNTHETIC_ACCESSOR", isSynthetic = true) object TO_ARRAY : IrDeclarationOriginImpl("TO_ARRAY") object JVM_STATIC_WRAPPER : IrDeclarationOriginImpl("JVM_STATIC_WRAPPER") object JVM_OVERLOADS_WRAPPER : IrDeclarationOriginImpl("JVM_OVERLOADS_WRAPPER") object SYNTHETIC_METHOD_FOR_PROPERTY_ANNOTATIONS : IrDeclarationOriginImpl("SYNTHETIC_METHOD_FOR_PROPERTY_ANNOTATIONS", isSynthetic = true) object SYNTHETIC_METHOD_FOR_TYPEALIAS_ANNOTATIONS : IrDeclarationOriginImpl("SYNTHETIC_METHOD_FOR_TYPEALIAS_ANNOTATIONS", isSynthetic = true) object GENERATED_PROPERTY_REFERENCE : IrDeclarationOriginImpl("GENERATED_PROPERTY_REFERENCE", isSynthetic = true) object GENERATED_MEMBER_IN_CALLABLE_REFERENCE : IrDeclarationOriginImpl("GENERATED_MEMBER_IN_CALLABLE_REFERENCE", isSynthetic = false) object ENUM_MAPPINGS_FOR_WHEN : IrDeclarationOriginImpl("ENUM_MAPPINGS_FOR_WHEN", isSynthetic = true) object SYNTHETIC_INLINE_CLASS_MEMBER : IrDeclarationOriginImpl("SYNTHETIC_INLINE_CLASS_MEMBER", isSynthetic = true) object INLINE_CLASS_GENERATED_IMPL_METHOD : IrDeclarationOriginImpl("INLINE_CLASS_GENERATED_IMPL_METHOD") object STATIC_INLINE_CLASS_REPLACEMENT : IrDeclarationOriginImpl("STATIC_INLINE_CLASS_REPLACEMENT") object STATIC_INLINE_CLASS_CONSTRUCTOR : IrDeclarationOriginImpl("STATIC_INLINE_CLASS_CONSTRUCTOR") object GENERATED_ASSERTION_ENABLED_FIELD : IrDeclarationOriginImpl("GENERATED_ASSERTION_ENABLED_FIELD", isSynthetic = true) object GENERATED_EXTENDED_MAIN : IrDeclarationOriginImpl("GENERATED_EXTENDED_MAIN", isSynthetic = true) object SUSPEND_IMPL_STATIC_FUNCTION : IrDeclarationOriginImpl("SUSPEND_IMPL_STATIC_FUNCTION", isSynthetic = true) object INTERFACE_COMPANION_PRIVATE_INSTANCE : IrDeclarationOriginImpl("INTERFACE_COMPANION_PRIVATE_INSTANCE", isSynthetic = true) object POLYMORPHIC_SIGNATURE_INSTANTIATION : IrDeclarationOriginImpl("POLYMORPHIC_SIGNATURE_INSTANTIATION", isSynthetic = true) object ENUM_CONSTRUCTOR_SYNTHETIC_PARAMETER : IrDeclarationOriginImpl("ENUM_CONSTRUCTOR_SYNTHETIC_PARAMETER", isSynthetic = true) object OBJECT_SUPER_CONSTRUCTOR_PARAMETER : IrDeclarationOriginImpl("OBJECT_SUPER_CONSTURCTOR_PARAMETER", isSynthetic = true) object CONTINUATION_CLASS : IrDeclarationOriginImpl("CONTINUATION_CLASS") object SUSPEND_LAMBDA : IrDeclarationOriginImpl("SUSPEND_LAMBDA") object FOR_INLINE_STATE_MACHINE_TEMPLATE : IrDeclarationOriginImpl("FOR_INLINE_TEMPLATE") object FOR_INLINE_STATE_MACHINE_TEMPLATE_CAPTURES_CROSSINLINE : IrDeclarationOriginImpl("FOR_INLINE_TEMPLATE_CROSSINLINE") object CONTINUATION_CLASS_RESULT_FIELD: IrDeclarationOriginImpl("CONTINUATION_CLASS_RESULT_FIELD", isSynthetic = true) object COMPANION_PROPERTY_BACKING_FIELD : IrDeclarationOriginImpl("COMPANION_MOVED_PROPERTY_BACKING_FIELD") }
1
null
37
316
74126637a097f5e6b099a7b7a4263468ecfda144
4,058
kotlin
Apache License 2.0
voice/src/main/kotlin/com/algolia/instantsearch/voice/VoiceSpeechRecognizer.kt
algolia
139,958,370
false
null
package com.algolia.instantsearch.voice import android.content.Context import android.content.Intent import android.speech.RecognitionListener import android.speech.RecognizerIntent import android.speech.SpeechRecognizer class VoiceSpeechRecognizer( context: Context, private val maxResults: Int = 1, private val language: String? = null ) { interface StateListener { fun isListening(isListening: Boolean) } interface ResultsListener { //TODO: Document //TODO: Also see if can be vararg fun onResults(possibleTexts: Array<out String>) } private val speechRecognizer = SpeechRecognizer.createSpeechRecognizer(context) private val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).also { intent -> intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) intent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true) intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, maxResults) language?.let { intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, language) } } var stateListener: StateListener? = null fun setRecognitionListener(recognitionListener: RecognitionListener) { speechRecognizer.setRecognitionListener(recognitionListener) } fun start() { stateListener?.isListening(true) speechRecognizer.startListening(intent) } fun stop() { stateListener?.isListening(false) speechRecognizer.stopListening() } fun destroy() { try { speechRecognizer.destroy() } catch (exception: Exception) { exception.printStackTrace() } } }
2
Kotlin
28
206
96e7d9c98fe40cbcd85afa0e8e1eeb33b374063f
1,730
voice-overlay-android
MIT License
media/audio-ui/src/main/java/com/google/android/horologist/audio/ui/VolumePositionIndicator.kt
google
451,563,714
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.audio.ui import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.produceState import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.wear.compose.material.MaterialTheme import androidx.wear.compose.material.PositionIndicator import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collectLatest /** * A PositionIndicator that is tied to the system audio volume. * * Shows on the left side to match Bezel behaviour. If [displayIndicatorEvents] is non-null, the * indicator is initially hidden and only displays when that flow emits, then auto-hides after two * seconds. */ @Composable public fun VolumePositionIndicator( volumeUiState: () -> VolumeUiState, modifier: Modifier = Modifier, displayIndicatorEvents: Flow<Unit>? = null, color: Color = MaterialTheme.colors.secondary, ) { // False positive - https://issuetracker.google.com/issues/349411310 @Suppress("ProduceStateDoesNotAssignValue") val visible by produceState(displayIndicatorEvents == null, displayIndicatorEvents) { displayIndicatorEvents?.collectLatest { value = true delay(2000) value = false } } val uiState = volumeUiState() AnimatedVisibility( visible = visible, enter = fadeIn(), exit = fadeOut(), ) { PositionIndicator( modifier = modifier, // RSB indicator uses secondary colors (surface/onSurface) color = color, value = { uiState.current.toFloat() }, range = uiState.min.toFloat().rangeTo( uiState.max.toFloat(), ), ) } }
71
null
93
565
bde87db14f63338904550fc1827d0141ebe24d9a
2,596
horologist
Apache License 2.0
app/src/main/java/com/kylix/submissionbfaa_2/activities/SplashActivity.kt
KylixEza
291,975,162
false
null
package com.kylix.submissionbfaa_2.activities import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import com.kylix.submissionbfaa_2.databinding.ActivitySplashBinding class SplashActivity : AppCompatActivity() { private lateinit var splashBinding: ActivitySplashBinding private lateinit var handler: Handler override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) splashBinding = ActivitySplashBinding.inflate(layoutInflater) setContentView(splashBinding.root) handler = Handler() handler.postDelayed({ val intent = Intent(this@SplashActivity, MainActivity::class.java) startActivity(intent) finish() }, 3000) } }
0
Kotlin
1
5
5408eca132e54cdddd740aa081059f6be0529cf4
825
Submission-BFAA2-Dicoding
MIT License
src/main/kotlin/no/nav/bakveientilarbeid/http/httpClient.kt
navikt
434,142,476
false
null
package no.nav.bakveientilarbeid.http import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import no.nav.bakveientilarbeid.auth.AccessToken import java.net.URL const val consumerIdHeaderName = "Nav-Consumer-Id" const val consumerIdHeaderValue = "paw:bakveientilarbeid" suspend inline fun <reified T> HttpClient.get(url: URL, accessToken: AccessToken): HttpResponse = withContext(Dispatchers.IO) { request { url("$url") method = HttpMethod.Get header(HttpHeaders.Authorization, "Bearer ${accessToken.value}") } } suspend inline fun <reified T> HttpClient.getWithTokenX(url: URL, accessToken: AccessToken): HttpResponse = withContext(Dispatchers.IO) { request { url("$url") method = HttpMethod.Get header("TokenXAuthorization", "Bearer ${accessToken.value}") } } suspend inline fun <reified T> HttpClient.getWithConsumerId(url: URL, accessToken: AccessToken): HttpResponse = withContext(Dispatchers.IO) { request { url(url) method = HttpMethod.Get header(HttpHeaders.Authorization, "Bearer ${accessToken.value}") header(consumerIdHeaderName, consumerIdHeaderValue) } } suspend inline fun <reified T> HttpClient.postWithConsumerId(url: URL, queryParams: Parameters, accessToken: AccessToken): HttpResponse = withContext(Dispatchers.IO) { request { url(url) url { queryParams.forEach { param, _ -> parameters.append(param, queryParams[param]!!) } } method = HttpMethod.Post header(HttpHeaders.Authorization, "Bearer ${accessToken.value}") header(consumerIdHeaderName, consumerIdHeaderValue) } } suspend inline fun <reified T> HttpClient.postWithConsumerId(url: URL, requestBody: Any, accessToken: AccessToken): HttpResponse = withContext(Dispatchers.IO) { request { url(url) setBody(requestBody) method = HttpMethod.Post header(HttpHeaders.ContentType, "application/json") header(HttpHeaders.Authorization, "Bearer ${accessToken.value}") header(consumerIdHeaderName, consumerIdHeaderValue) } }
0
Kotlin
0
0
40a279221f09d863237a5d6515adc2853fbec5b6
2,288
bakveientilarbeid
MIT License
src/main/kotlin/io/mverse/kslack/api/methods/request/channels/ChannelsUnarchiveRequest.kt
mverse
161,946,116
true
{"Kotlin": 403852}
package io.mverse.kslack.api.methods.request.channels import io.mverse.kslack.api.methods.SlackApiRequest data class ChannelsUnarchiveRequest( /** * Authentication token. Requires scope: `channels:write` */ override var token: String? = null, /** * Channel to unarchive */ val channel: String? = null): SlackApiRequest
0
Kotlin
0
0
9ebf1dc13f6a3d89a03af11a83074a4d636cb071
342
jslack
MIT License
im-access/src/main/kotlin/com/qingzhu/imaccess/socketio/AckUtils.kt
nedphae
322,789,778
false
{"Kotlin": 744301, "ANTLR": 281490, "Java": 48298, "Dockerfile": 375}
package com.qingzhu.imaccess.socketio import com.corundumstudio.socketio.AckCallback import com.corundumstudio.socketio.AckRequest import com.corundumstudio.socketio.SocketIOClient import com.qingzhu.common.message.Header import com.qingzhu.common.util.JsonUtils import com.qingzhu.imaccess.domain.view.WebSocketResponse import com.qingzhu.imaccess.domain.view.WebSocketResponseWithString import kotlinx.coroutines.* import org.springframework.http.HttpStatus import java.util.concurrent.TimeoutException import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException class AckBuilder<T>( private var request: AckRequest ) { private var header: Header? = null private var httpStatus: HttpStatus = HttpStatus.OK private var body: T? = null fun header(header: Header) = apply { this.header = header } fun httpStatus(httpStatus: HttpStatus) = apply { this.httpStatus = httpStatus } fun body(body: T?) = apply { this.body = body } fun send() { if (header == null) throw IllegalArgumentException("header can`t be null.") messageAck(request, WebSocketResponse(header!!, httpStatus.value(), body)) } } /** * --------------- ack --------------- * * Reply message, use JSON null value filter */ fun <T> messageAck(request: AckRequest, webSocketResponse: WebSocketResponse<T>) { if (request.isAckRequested) { request.sendAckData(webSocketResponse) } } fun errorAck(request: AckRequest, header: Header, throwable: Throwable) { AckBuilder<String>(request).header(header) .httpStatus(HttpStatus.INTERNAL_SERVER_ERROR) .body(throwable.message).send() throwable.printStackTrace() } fun messageAck(request: AckRequest, header: Header) { AckBuilder<Unit>(request).header(header).send() } /** * --------------- sync --------------- * Attention: * this call will block your fun until it return * so don't use in batch operation */ inline fun <reified T> SocketIOClient.sendAndAwait(event: String, data: Any): WebSocketResponse<T> { val client = this return runBlocking(Dispatchers.IO) { client.syncSend(event, data) } } fun <T> CancellableContinuation<T>.resumeIfActive(value: T) { if (this.isActive) this.resume(value) } fun <T> CancellableContinuation<T>.resumeWithExceptionIfActive(exception: Throwable) { if (this.isActive) this.resumeWithException(exception) } suspend inline fun <reified T> SocketIOClient.syncSend(event: String, data: Any) = suspendCancellableCoroutine { cont: CancellableContinuation<WebSocketResponse<T>> -> this.sendWithCallback<T>(event, data, { cont.resumeWithExceptionIfActive(TimeoutException("响应超时")) }) { cont.resumeIfActive(it) } GlobalScope.launch { delay(15050) cont.resumeWithExceptionIfActive(TimeoutException("响应超时")) } } /** --------------- async --------------- */ inline fun <reified T> SocketIOClient.sendWithCallback( event: String, data: Any, crossinline onTimeout: () -> Unit = {}, crossinline onSuccess: (data: WebSocketResponse<T>) -> Unit = {} ) { this.sendEvent(event, object : AckCallback<WebSocketResponseWithString>(WebSocketResponseWithString::class.java, 15000) { override fun onSuccess(result: WebSocketResponseWithString?) { result?.let { // 先转换为 String, 然后再手动序列化 val body = result.body?.let { it1 -> JsonUtils.fromJson<T>(it1) } onSuccess(WebSocketResponse(it.header, it.code, body)) } } override fun onTimeout() { onTimeout() } }, data ) }
1
Kotlin
18
42
217b4658508763133e1a5b6a96763a14e9f6f4ad
3,727
contact-center
Apache License 2.0
allure-android/src/espresso/kotlin/ru/tinkoff/allure/CrashTestActivity.kt
davidbugayov
130,863,181
false
null
package ru.tinkoff.allure import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import rx.Observable import rx.schedulers.Schedulers class CrashTestActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_test) findViewById<Button>(R.id.crash_button).setOnClickListener { stackOverflow() } findViewById<Button>(R.id.rx_crash_button).setOnClickListener { rxCrash() } } private fun stackOverflow() { stackOverflow() } private fun rxCrash() { Observable.error<RuntimeException>(RuntimeException()) .subscribeOn(Schedulers.io()) .subscribe( /* onNext */ {}, /* onError */ {t:Throwable -> throw RuntimeException(t)}, /* onCompleted */ {}) } }
0
null
0
1
7e9e0fbb09c682cd467e21269cb660b1e0e24421
1,015
allure-android
Apache License 2.0
app/src/main/java/com/entelgy/marvel/data/model/imageformats/StandardImage.kt
Riflin
479,453,421
false
{"Kotlin": 260458}
package com.entelgy.marvel.data.model.imageformats enum class StandardImage(private val format: String): ImageFormat { Small("standard_small"), Medium("standard_medium"), Xlarge("standard_xlarge"), Fantastic("standard_fantastic"), Uncanny("standard_uncanny"), Incredible("standard_incredible"); override fun format(): String { return format } }
0
Kotlin
0
0
62f8d9e49748412d65ef9d48808867a8c89f206e
396
marvel
Apache License 2.0
kt.kt
darian-catalin-cucer
598,115,618
false
null
fun knuthMorrisPratt(text: String, pattern: String): Int { val n = text.length val m = pattern.length val lps = IntArray(m) var j = 0 var i = 0 computeLPSArray(pattern, m, lps) while (i < n) { if (pattern[j] == text[i]) { j++ i++ } if (j == m) { return i - j } else if (i < n && pattern[j] != text[i]) { if (j != 0) { j = lps[j - 1] } else { i = i + 1 } } } return -1 } private fun computeLPSArray(pattern: String, m: Int, lps: IntArray) { var len = 0 var i = 1 lps[0] = 0 while (i < m) { if (pattern[i] == pattern[len]) { len++ lps[i] = len i++ } else { if (len != 0) { len = lps[len - 1] } else { lps[i] = 0 i++ } } } }
0
Kotlin
0
0
e0733bd8986c3b71ac29161ac21f13c67c032e0e
970
kmp-algorithm
MIT License
app/src/main/java/com/adematici/kotlincoroutines/CoroutineswithContext.kt
aticiadem
340,420,090
false
null
package com.adematici.kotlincoroutines import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext fun main(){ runBlocking { launch(Dispatchers.Default) { println("Context: $coroutineContext") withContext(Dispatchers.IO){ println("Context: $coroutineContext") } } } }
1
null
2
8
26566603cb66c26b0055d3d7a000e18eef0fc593
432
KotlinCoroutines
MIT License
tilbakekreving/infrastructure/src/main/kotlin/tilbakekreving/infrastructure/repo/oppdatertKravgrunnlag/OppdatertKravgrunnlagHendelse.kt
navikt
227,366,088
false
{"Kotlin": 9035699, "Shell": 4369, "TSQL": 1233, "Dockerfile": 800}
package tilbakekreving.infrastructure.repo.oppdatertKravgrunnlag import no.nav.su.se.bakover.common.deserialize import no.nav.su.se.bakover.common.ident.NavIdentBruker import no.nav.su.se.bakover.common.serialize import no.nav.su.se.bakover.common.tid.Tidspunkt import no.nav.su.se.bakover.hendelse.domain.DefaultHendelseMetadata import no.nav.su.se.bakover.hendelse.domain.HendelseId import no.nav.su.se.bakover.hendelse.domain.Hendelsesversjon import tilbakekreving.domain.OppdatertKravgrunnlagPåTilbakekrevingHendelse import tilbakekreving.domain.TilbakekrevingsbehandlingId import java.util.UUID private data class OppdatertKravgrunnlagHendelseDbJson( val behandlingsId: UUID, val utførtAv: String, val kravgrunnlagPåSakHendelseId: String, ) fun mapTilOppdatertKravgrunnlagPåTilbakekrevingHendelse( data: String, hendelseId: HendelseId, sakId: UUID, tidligereHendelsesId: HendelseId, hendelsestidspunkt: Tidspunkt, versjon: Hendelsesversjon, meta: DefaultHendelseMetadata, ): OppdatertKravgrunnlagPåTilbakekrevingHendelse { val deserialized = deserialize<OppdatertKravgrunnlagHendelseDbJson>(data) return OppdatertKravgrunnlagPåTilbakekrevingHendelse( hendelseId = hendelseId, sakId = sakId, hendelsestidspunkt = hendelsestidspunkt, versjon = versjon, meta = meta, tidligereHendelseId = tidligereHendelsesId, id = TilbakekrevingsbehandlingId(deserialized.behandlingsId), utførtAv = NavIdentBruker.Saksbehandler(navIdent = deserialized.utførtAv), kravgrunnlagPåSakHendelseId = HendelseId.fromString(deserialized.kravgrunnlagPåSakHendelseId), ) } fun OppdatertKravgrunnlagPåTilbakekrevingHendelse.toJson(): String = OppdatertKravgrunnlagHendelseDbJson( behandlingsId = this.id.value, utførtAv = this.utførtAv.navIdent, kravgrunnlagPåSakHendelseId = this.kravgrunnlagPåSakHendelseId.toString(), ).let { serialize(it) }
2
Kotlin
1
1
9ffc57c2d6c8c7138261186e1119ad7764bc40d3
1,981
su-se-bakover
MIT License
src/main/kotlin/adventofcode/day21.kt
Kvest
163,103,813
false
null
package adventofcode import java.io.File /* r[5] = 123 seti 123 0 5 r[5] = r[5] and 456 bani 5 456 5 r[5] = if (r[5] == 72) 1 else 0 eqri 5 72 5 r[1] = r[5] + r[1] addr 5 1 1 r[1] = 0 seti 0 0 1 r[5] = 0 seti 0 3 5 r[4] = r[5] or 65536 bori 5 65536 4 r[5] = 13_284_195 seti 13284195 4 5 r[3] = r[4] and 255 bani 4 255 3 r[5] = r[5] + r[3] addr 5 3 5 r[5] = r[5] and 16_777_215 bani 5 16777215 5 r[5] = r[5] * 65899 muli 5 65899 5 r[5] = r[5] and 16777215 bani 5 16777215 5 r[3] = if (256 > r[4]) 1 else 0 gtir 256 4 3 r[1] = r[3] + r[1] addr 3 1 1 r[1]++ addi 1 1 1 r[1] = 27 seti 27 1 1 r[3] = 0 seti 0 5 3 r[2] = r[3] + 1 addi 3 1 2 r[2] = r[2] * 256 muli 2 256 2 r[2] = if (r[2] > r[4]) 1 else 0 gtrr 2 4 2 r[1] = r[2] + r[1] addr 2 1 1 r[1]++ addi 1 1 1 r[1] = 25 seti 25 2 1 r[3]++ addi 3 1 3 r[1] = 17 seti 17 1 1 r[4] = r[3] setr 3 7 4 r[1] = 7 seti 7 3 1 r[3] = if (r[5] == r[0]) 1 else 0 eqrr 5 0 3 r[1] = r[3] + r[1] addr 3 1 1 r[1] = 5 seti 5 3 1 */ fun main(args: Array<String>) { first21(File("./data/day21_1.txt").readLines()) second21() } private val IP = 1 private fun first21(data: List<String>) { var ip = 0 val registers = intArrayOf(0, 0, 0, 0, 0, 0) while (ip >=0 && ip < data.size) { val tmp = data[ip].split(" ") val a = tmp[1].toInt() val b = tmp[2].toInt() val c = tmp[3].toInt() registers[IP] = ip OPCODES[tmp[0]]?.invoke(a, b, c, registers) ip = registers[IP] + 1 if (ip == 28) { break } } println(registers.joinToString()) } private fun second21() { val target = 0 var prev = 0 var a = 0 var b = 0 var c = 0 b = c or 65536 c = 1328419 val set = HashSet<Int>(10300) repeat(Int.MAX_VALUE) { a = b and 255 c = c + a c = c and 16777215 c = c * 65899 c = c and 16777215 if (256 > b) { if (!set.contains(c)) { set.add(c) prev = c } //prev = c if (c == target) { TODO("HALT!!!") } else { b = c or 65536 c = 13284195 } } else { // r[3] = 0 // while ((r[3] + 1) * 256 <= r[4]) { // r[3]++ // } // r[4] = r[3] //converted to: b = b / 256 } } println(prev) }
0
Kotlin
0
0
d94b725575a8a5784b53e0f7eee6b7519ac59deb
2,661
aoc2018
Apache License 2.0
app/src/main/java/com/example/sampledataapp/data/Repository.kt
ehsansouri23
228,077,782
false
null
package com.example.sampledataapp.data import com.example.sampledataapp.data.model.Address import com.example.sampledataapp.network.Api class Repository(private val api: Api) : BaseRepository() { suspend fun getAddresses(): Result<List<Address>> = safeApiCall { api.getAddresses() } suspend fun addAddress(address: Address): Result<Address> = safeApiCall { api.addAddress(address) } }
0
Kotlin
0
0
03221844ea1bfda7dd0bdce59465646eb7284da8
404
sample-data-app
Apache License 2.0
bitcoincore/src/main/kotlin/io/definenulls/bitcoincore/managers/UnspentOutputProvider.kt
toEther
677,363,684
false
null
package io.definenulls.bitcoincore.managers import io.definenulls.bitcoincore.core.IStorage import io.definenulls.bitcoincore.core.PluginManager import io.definenulls.bitcoincore.models.BalanceInfo import io.definenulls.bitcoincore.storage.UnspentOutput class UnspentOutputProvider(private val storage: IStorage, private val confirmationsThreshold: Int = 6, val pluginManager: PluginManager) : IUnspentOutputProvider { override fun getSpendableUtxo(): List<UnspentOutput> { return getConfirmedUtxo().filter { pluginManager.isSpendable(it) } } fun getBalance(): BalanceInfo { val spendable = getSpendableUtxo().map { it.output.value }.sum() val unspendable = getUnspendableUtxo().map { it.output.value }.sum() return BalanceInfo(spendable, unspendable) } private fun getConfirmedUtxo(): List<UnspentOutput> { val unspentOutputs = storage.getUnspentOutputs() if (confirmationsThreshold == 0) return unspentOutputs val lastBlockHeight = storage.lastBlock()?.height ?: 0 return unspentOutputs.filter { if (it.transaction.isOutgoing) { return@filter true } val block = it.block ?: return@filter false if (block.height <= lastBlockHeight - confirmationsThreshold + 1) { return@filter true } false } } private fun getUnspendableUtxo(): List<UnspentOutput> { return getConfirmedUtxo().filter { !pluginManager.isSpendable(it) } } }
0
Kotlin
0
0
bbd7c809a027dd33c1fd393f6a53684d84dcbe14
1,590
bitcoin-kit-android_s
MIT License
app/src/main/java/com/babylon/wallet/android/presentation/wallet/WalletViewModel.kt
radixdlt
513,047,280
false
{"Kotlin": 4174674, "HTML": 215350, "Java": 18496, "Ruby": 2757, "Shell": 1962}
package com.babylon.wallet.android.presentation.wallet import androidx.lifecycle.viewModelScope import com.babylon.wallet.android.domain.common.onError import com.babylon.wallet.android.domain.common.onValue import com.babylon.wallet.android.domain.model.assets.AccountWithAssets import com.babylon.wallet.android.domain.usecases.AccountWithSecurityPrompt import com.babylon.wallet.android.domain.usecases.GetAccountsForSecurityPromptUseCase import com.babylon.wallet.android.domain.usecases.GetAccountsWithAssetsUseCase import com.babylon.wallet.android.domain.usecases.SecurityPromptType import com.babylon.wallet.android.presentation.common.OneOffEvent import com.babylon.wallet.android.presentation.common.OneOffEventHandler import com.babylon.wallet.android.presentation.common.OneOffEventHandlerImpl import com.babylon.wallet.android.presentation.common.StateViewModel import com.babylon.wallet.android.presentation.common.UiMessage import com.babylon.wallet.android.presentation.common.UiState import com.babylon.wallet.android.utils.AppEvent import com.babylon.wallet.android.utils.AppEvent.RestoredMnemonic import com.babylon.wallet.android.utils.AppEventBus import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.filterIsInstance import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import rdx.works.profile.data.model.extensions.factorSourceId import rdx.works.profile.data.model.extensions.isOlympiaAccount import rdx.works.profile.data.model.factorsources.FactorSource import rdx.works.profile.data.model.factorsources.FactorSource.FactorSourceID import rdx.works.profile.data.model.factorsources.FactorSourceKind import rdx.works.profile.data.model.pernetwork.Network import rdx.works.profile.domain.EnsureBabylonFactorSourceExistUseCase import rdx.works.profile.domain.GetProfileUseCase import rdx.works.profile.domain.accountOnCurrentNetwork import rdx.works.profile.domain.accountsOnCurrentNetwork import rdx.works.profile.domain.backup.GetBackupStateUseCase import rdx.works.profile.domain.factorSources import timber.log.Timber import javax.inject.Inject @HiltViewModel class WalletViewModel @Inject constructor( private val getAccountsWithAssetsUseCase: GetAccountsWithAssetsUseCase, private val getProfileUseCase: GetProfileUseCase, private val getAccountsForSecurityPromptUseCase: GetAccountsForSecurityPromptUseCase, private val appEventBus: AppEventBus, private val ensureBabylonFactorSourceExistUseCase: EnsureBabylonFactorSourceExistUseCase, getBackupStateUseCase: GetBackupStateUseCase ) : StateViewModel<WalletUiState>(), OneOffEventHandler<WalletEvent> by OneOffEventHandlerImpl() { override fun initialState() = WalletUiState() private val refreshFlow = MutableSharedFlow<Unit>() private val accountsFlow = combine( getProfileUseCase.accountsOnCurrentNetwork.distinctUntilChanged(), refreshFlow ) { accounts, _ -> accounts } val babylonFactorSourceDoesNotExistEvent = appEventBus.events.filterIsInstance<AppEvent.BabylonFactorSourceDoesNotExist>() init { viewModelScope.launch { if (ensureBabylonFactorSourceExistUseCase.babylonFactorSourceExist().not()) { appEventBus.sendEvent(AppEvent.BabylonFactorSourceDoesNotExist, delayMs = 500L) return@launch } } observeAccounts() observeDeviceFactorSources() observePrompts() observeProfileBackupState(getBackupStateUseCase) observeGlobalAppEvents() loadResources(withRefresh = false) } suspend fun createBabylonFactorSource(deviceBiometricAuthenticationProvider: suspend () -> Boolean) { viewModelScope.launch { if (deviceBiometricAuthenticationProvider()) { ensureBabylonFactorSourceExistUseCase() } else { // force user to authenticate until we can create Babylon Factor source appEventBus.sendEvent(AppEvent.BabylonFactorSourceDoesNotExist) } } } private fun observeAccounts() { viewModelScope.launch { accountsFlow.collect { accounts -> _state.update { state -> state.loadingResources(accounts = accounts, isRefreshing = state.isRefreshing) } getAccountsWithAssetsUseCase( accounts = accounts, isNftItemDataNeeded = false, isRefreshing = _state.value.isRefreshing ).onValue { resources -> _state.update { it.onResourcesReceived(resources) } }.onError { error -> _state.update { it.onResourcesError(error) } Timber.w(error) } } } } private fun observeDeviceFactorSources() { viewModelScope.launch { getProfileUseCase.factorSources.collect { factorSourcesList -> _state.update { state -> state.copy(factorSources = factorSourcesList) } } } } private fun observePrompts() { viewModelScope.launch { getAccountsForSecurityPromptUseCase().collect { accounts -> _state.update { it.copy(accountsNeedSecurityPrompt = accounts) } } } } private fun observeProfileBackupState(getBackupStateUseCase: GetBackupStateUseCase) { viewModelScope.launch { getBackupStateUseCase().collect { backupState -> _state.update { it.copy(isSettingsWarningVisible = backupState.isWarningVisible) } } } } private fun observeGlobalAppEvents() { viewModelScope.launch { appEventBus.events.filter { event -> event is AppEvent.RefreshResourcesNeeded || event is RestoredMnemonic }.collect { loadResources(withRefresh = it !is RestoredMnemonic) } } } private fun loadResources(withRefresh: Boolean) { _state.update { it.copy(refreshing = withRefresh) } viewModelScope.launch { refreshFlow.emit(Unit) } } fun onRefresh() { loadResources(withRefresh = true) } fun onMessageShown() { _state.update { it.copy(error = null) } } fun onApplySecuritySettings(account: Network.Account, securityPromptType: SecurityPromptType) { viewModelScope.launch { val factorSourceId = getProfileUseCase.accountOnCurrentNetwork(account.address)?.factorSourceId() as? FactorSourceID.FromHash ?: return@launch when (securityPromptType) { SecurityPromptType.NEEDS_BACKUP -> sendEvent(WalletEvent.NavigateToMnemonicBackup(factorSourceId)) SecurityPromptType.NEEDS_RESTORE -> sendEvent(WalletEvent.NavigateToMnemonicRestore(factorSourceId)) } } } } internal sealed interface WalletEvent : OneOffEvent { data class NavigateToMnemonicBackup(val factorSourceId: FactorSourceID.FromHash) : WalletEvent data class NavigateToMnemonicRestore(val factorSourceId: FactorSourceID.FromHash) : WalletEvent } data class WalletUiState( private val accountsWithResources: List<AccountWithAssets>? = null, private val loading: Boolean = true, private val refreshing: Boolean = false, private val accountsNeedSecurityPrompt: List<AccountWithSecurityPrompt> = emptyList(), private val factorSources: List<FactorSource> = emptyList(), val isSettingsWarningVisible: Boolean = false, val error: UiMessage? = null, ) : UiState { val accountResources: List<AccountWithAssets> get() = accountsWithResources.orEmpty() /** * Initial loading of the screen. */ val isLoading: Boolean get() = accountsWithResources == null && loading val isLoadingAssets: Boolean get() = accountsWithResources != null && accountsWithResources.none { it.assets != null } && loading /** * Used in pull to refresh mode. */ val isRefreshing: Boolean get() = refreshing fun securityPrompt(forAccount: Network.Account): SecurityPromptType? { val assetsForAccount = accountsWithResources?.find { it.account.address == forAccount.address }?.assets ?: return null val accountWithSecurityPrompt = accountsNeedSecurityPrompt.find { it.account.address == forAccount.address } ?: return null return if (accountWithSecurityPrompt.prompt == SecurityPromptType.NEEDS_BACKUP) { if (assetsForAccount.hasXrd()) SecurityPromptType.NEEDS_BACKUP else null } else { accountWithSecurityPrompt.prompt } } fun getTag(forAccount: Network.Account): AccountTag? { return when { !isDappDefinitionAccount(forAccount) && !isLegacyAccount(forAccount) && !isLedgerAccount(forAccount) -> null isDappDefinitionAccount(forAccount) -> AccountTag.DAPP_DEFINITION isLegacyAccount(forAccount) && isLedgerAccount(forAccount) -> AccountTag.LEDGER_LEGACY isLegacyAccount(forAccount) && !isLedgerAccount(forAccount) -> AccountTag.LEGACY_SOFTWARE !isLegacyAccount(forAccount) && isLedgerAccount(forAccount) -> AccountTag.LEDGER_BABYLON else -> null } } private fun isLegacyAccount(forAccount: Network.Account): Boolean = forAccount.isOlympiaAccount() private fun isLedgerAccount(forAccount: Network.Account): Boolean { val factorSource = factorSources.find { it.id == forAccount.factorSourceId() }?.id?.kind return factorSource == FactorSourceKind.LEDGER_HQ_HARDWARE_WALLET } private fun isDappDefinitionAccount(forAccount: Network.Account): Boolean { return accountResources.find { accountWithResources -> accountWithResources.account.address == forAccount.address }?.isDappDefinitionAccountType ?: false } fun loadingResources(accounts: List<Network.Account>, isRefreshing: Boolean): WalletUiState = copy( accountsWithResources = accounts.map { account -> AccountWithAssets( account = account, assets = accountsWithResources?.find { account == it.account }?.assets ) }, loading = true, refreshing = isRefreshing ) fun onResourcesReceived(accountsWithResources: List<AccountWithAssets>): WalletUiState = copy( accountsWithResources = accountsWithResources, loading = false, refreshing = false ) fun onResourcesError(error: Throwable?): WalletUiState = copy( error = UiMessage.ErrorMessage.from(error), loading = false, refreshing = false ) enum class AccountTag { LEDGER_BABYLON, DAPP_DEFINITION, LEDGER_LEGACY, LEGACY_SOFTWARE } }
9
Kotlin
8
6
10eee604bc12b09f4326ce6d935a2848e363d74e
11,166
babylon-wallet-android
Apache License 2.0
src/commonMain/kotlin/com/github/dwursteisen/minigdx/ecs/components/text/SequentialTextEffect.kt
minigdx
241,479,001
false
null
package com.github.dwursteisen.minigdx.ecs.components.text import com.github.dwursteisen.minigdx.Seconds class SequentialTextEffect(private val sequence: List<TextEffect>) : TextEffect { private var currentEffect = 0 override var isFinished: Boolean get() = sequence.last().isFinished set(_) = Unit override var wasUpdated: Boolean get() = sequence[currentEffect].wasUpdated set(_) = Unit override var content: String get() { return sequence.map { it.content }.joinToString("") } set(_) = Unit override fun update(delta: Seconds) { sequence[currentEffect].update(delta) if (sequence[currentEffect].isFinished) { currentEffect = (currentEffect + 1) % sequence.size } } override fun getAlteration(characterIndex: Int): Alteration { return sequence[currentEffect].getAlteration(characterIndex) } }
2
Kotlin
5
98
ca4065239c1d9e1f7f9a4d21f535e7a2f082c65a
947
minigdx
MIT License
app/src/main/java/com/dscoding/awesomeuidesign/ui/theme/Color.kt
diogosantos41
528,414,629
false
null
package com.dscoding.awesomeuidesign.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5) val GreyDark = Color(0xFF333333) val GreyLight = Color(0xFFEEEEEE) val WhiteDirty = Color(0xFFF0F3F4) val PurpleDark = Color(0xFF312b47) val Purple = Color(0xFF653ff4) val Green = Color(0xFF28B463) val GreenDark = Color(0xFF00512C) val Coral = Color(0xFFFF7F50)
0
Kotlin
0
0
4fa2312bc568109a969336c062e3949252a4931b
488
awesome-ui-design-android
MIT License
rxmedia/src/main/java/com/featzima/rxmedia/video/RxVideoCodec.kt
featzima
114,471,755
false
null
package com.featzima.rxmedia.video import android.annotation.SuppressLint import android.graphics.Bitmap import android.graphics.Rect import android.media.MediaCodec import android.media.MediaCodecInfo import android.media.MediaFormat import android.media.MediaFormat.* import android.util.Log import com.featzima.rxmedia.extensions.waitForRequested import com.featzima.rxmedia.i.CodecEvent import com.featzima.rxmedia.i.DataCodecEvent import com.featzima.rxmedia.i.FormatCodecEvent import com.featzima.rxmedia.i.IRxVideoCodec import com.featzima.rxmedia.video.internal.CodecInputSurface import com.featzima.rxmedia.video.internal.InputTextureRender import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.disposables.Disposable import io.reactivex.subjects.BehaviorSubject import org.reactivestreams.Publisher import org.reactivestreams.Subscriber import org.reactivestreams.Subscription import java.nio.ByteBuffer class RxVideoCodec( private val settings: VideoCodecSettings) : IRxVideoCodec, Disposable { private var surface: CodecInputSurface? = null private lateinit var surfaceRect: Rect private var frameRate: Int = 0 private var nbEncoded: Int = 0 private var canceled = false private val codecSubject = BehaviorSubject.create<MediaCodec>() private val inputTextureRender = InputTextureRender() override fun dispose() { canceled = true } override fun isDisposed(): Boolean { return canceled } override fun input(): Subscriber<CodecEvent<Bitmap>> = object : Subscriber<CodecEvent<Bitmap>> { private lateinit var subscription: Subscription override fun onComplete() { surface!!.release() codecSubject.value?.signalEndOfInputStream() } override fun onSubscribe(s: Subscription) { subscription = s subscription.request(1) } override fun onNext(codecEvent: CodecEvent<Bitmap>) { try { when (codecEvent) { is FormatCodecEvent -> { if (!codecEvent.mediaFormat.containsKey(KEY_WIDTH) || !codecEvent.mediaFormat.containsKey(KEY_HEIGHT) || !codecEvent.mediaFormat.containsKey(KEY_FRAME_RATE)) { throw IllegalArgumentException("MediaFormat should contain KEY_WIDTH, KEY_HEIGHT, KEY_FRAME_RATE") } val mediaFormat = codecEvent.mediaFormat.apply { setString(KEY_MIME, settings.videoMime) setInteger(MediaFormat.KEY_BIT_RATE, calcBitRate(this)) setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface) setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, settings.keyFrameInterval) } val codec = MediaCodec.createEncoderByType(settings.videoMime) codec.configure(mediaFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE) surface = CodecInputSurface(codec.createInputSurface()) surfaceRect = Rect(0, 0, codecEvent.mediaFormat.getInteger(KEY_WIDTH), codecEvent.mediaFormat.getInteger(KEY_HEIGHT)) frameRate = codecEvent.mediaFormat.getInteger(KEY_FRAME_RATE) codec.start() codecSubject.onNext(codec) } is DataCodecEvent -> { surface!!.apply { makeCurrent() inputTextureRender.drawBitmap(codecEvent.data) setPresentationTime(codecEvent.bufferInfo.presentationTimeUs * 1000) swapBuffers() codecEvent.data.recycle() } } } subscription.request(1) } catch (e: Exception) { subscription.cancel() codecSubject.onError(e) } } override fun onError(t: Throwable) { Log.e(TAG, "onError($t)") codecSubject.onError(t) } } override fun output(): Publisher<CodecEvent<ByteBuffer>> = Flowable.create<CodecEvent<ByteBuffer>>({ emitter -> loop@ while (!emitter.isCancelled) { val codec = this.codecSubject.blockingFirst() emitter.waitForRequested() val info = MediaCodec.BufferInfo() val outputBufferIndex = codec.dequeueOutputBuffer(info, TIMEOUT_USEC) @SuppressLint("SwitchIntDef") when (outputBufferIndex) { MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> { Log.d(TAG, "INFO_OUTPUT_FORMAT_CHANGED") emitter.onNext(FormatCodecEvent(mediaFormat = codec.outputFormat)) } in 0..Int.MAX_VALUE -> { val encodedData = codec.getOutputBuffer(outputBufferIndex) if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { break@loop } if (info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0) { // The codec config data was pulled out and fed to the muxer when we got // the INFO_OUTPUT_FORMAT_CHANGED status. Ignore it. Log.d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG") info.size = 0 } if (info.size != 0) { emitter.onNext(DataCodecEvent( data = encodedData, bufferInfo = info)) this.nbEncoded++ } codec.releaseOutputBuffer(outputBufferIndex, false) } } } this.codecSubject.value?.apply { stop() release() } emitter.onComplete() }, BackpressureStrategy.BUFFER) companion object { private val TAG = RxVideoCodec::class.java.simpleName private val TIMEOUT_USEC = 10000L private fun calcBitRate(mediaFormat: MediaFormat): Int { val frameRate = mediaFormat.getInteger(KEY_FRAME_RATE) val width = mediaFormat.getInteger(KEY_WIDTH) val height = mediaFormat.getInteger(KEY_HEIGHT) val bitrate = frameRate * width * height Log.v(TAG, String.format("bitrate=%5.2f[Mbps]", bitrate.toFloat() / 1024f / 1024f)) return bitrate } } }
0
Kotlin
0
5
773cea6717a923d6208892a8c799db39b7e003f3
6,810
rxmedia
Apache License 2.0
sessionkotlin/lib/src/main/kotlin/com/github/sessionkotlin/lib/dsl/exception/UndefinedRecursionVariableException.kt
sessionkotlin
467,159,660
false
{"Kotlin": 365663, "Makefile": 1801}
package com.github.sessionkotlin.lib.dsl.exception import com.github.sessionkotlin.lib.dsl.RecursionTag /** * Thrown when attempting to use recursion tag that is not defined. */ internal class UndefinedRecursionVariableException(i: RecursionTag) : SessionKotlinDSLException("Recursion variable $i undefined.")
0
Kotlin
0
1
558837e9525987c9196e00f796489c041928a50d
318
sessionkotlin
MIT License
sessionkotlin/lib/src/main/kotlin/com/github/sessionkotlin/lib/dsl/exception/UndefinedRecursionVariableException.kt
sessionkotlin
467,159,660
false
{"Kotlin": 365663, "Makefile": 1801}
package com.github.sessionkotlin.lib.dsl.exception import com.github.sessionkotlin.lib.dsl.RecursionTag /** * Thrown when attempting to use recursion tag that is not defined. */ internal class UndefinedRecursionVariableException(i: RecursionTag) : SessionKotlinDSLException("Recursion variable $i undefined.")
0
Kotlin
0
1
558837e9525987c9196e00f796489c041928a50d
318
sessionkotlin
MIT License
src/main/kotlin/com/github/mrgaabriel/ayla/commands/CommandCategory.kt
MrGaabriel
143,538,052
false
null
package com.github.mrgaabriel.ayla.commands enum class CommandCategory(val fancyName: String, val description: String, val showOnHelp: Boolean = true) { CONFIG("Configuração", "Comandos relacionados a configuração dos módulos da Ayla no seu servidor"), DEVELOPER("Desenvolvedor", "Comandos que só o desenvolvedor da Ayla pode usar", false), DISCORD("Discord", "Comandos relacionados ao Discord"), IMAGES("Imagens", "Comandos relacionados a manipulação de imagens"), MISC("Miscelânea", "Comandos que não encontraram uma categoria específica"), MUSIC("Música", "Comandos relacionados a música"), UTILS("Utilidades", "Comandos relacionados a utilidades"), NONE("Nenhuma", "Comandos que não estão em nenhuma categoria") }
20
Kotlin
1
4
51768344e6b0b53fbbb5fb298cb88dea848a5faa
752
Ayla
MIT License
src/main/kotlin/net/meilcli/klinq/internal/Grouping.kt
MeilCli
47,538,344
false
null
package net.meilcli.klinq.internal import net.meilcli.klinq.Enumerable import net.meilcli.klinq.IGrouping internal class Grouping<TKey, TElement> : Enumerable<TElement>, IGrouping<TKey, TElement> { override var key: TKey constructor(key: TKey, iterable: Iterable<TElement>) : super(iterable) { this.key = key } }
0
Kotlin
0
2
1ceed0aeb6d7646ee66a9c3b0bf9f3b743f160b3
336
KLinq
MIT License
bot/storage-mongo/target/generated-sources/kapt/compile/fr/vsct/tock/translator/I18nLabel_.kt
sycomix
141,590,702
true
{"Kotlin": 2056557, "TypeScript": 333554, "HTML": 133330, "CSS": 31450, "JavaScript": 5174, "Shell": 1585}
package fr.vsct.tock.translator import java.util.LinkedHashSet import kotlin.String import kotlin.Suppress import kotlin.collections.Collection import kotlin.reflect.KProperty1 import org.litote.kmongo.Id import org.litote.kmongo.property.KCollectionPropertyPath import org.litote.kmongo.property.KPropertyPath class I18nLabel_<T>(previous: KPropertyPath<T, *>?, property: KProperty1<*, I18nLabel?>) : KPropertyPath<T, I18nLabel?>(previous,property) { val _id: KProperty1<T, Id<I18nLabel>?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::_id) val namespace: KProperty1<T, String?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::namespace) val category: KProperty1<T, String?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::category) val i18n: KProperty1<T, LinkedHashSet<I18nLocalizedLabel>?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::i18n) val defaultLabel: KProperty1<T, String?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::defaultLabel) companion object { val _id: KProperty1<I18nLabel, Id<I18nLabel>?> get() = I18nLabel::_id val Namespace: KProperty1<I18nLabel, String?> get() = I18nLabel::namespace val Category: KProperty1<I18nLabel, String?> get() = I18nLabel::category val I18n: KProperty1<I18nLabel, LinkedHashSet<I18nLocalizedLabel>?> get() = I18nLabel::i18n val DefaultLabel: KProperty1<I18nLabel, String?> get() = I18nLabel::defaultLabel} } class I18nLabel_Col<T>( previous: KPropertyPath<T, *>?, property: KProperty1<*, Collection<I18nLabel>?>, additionalPath: String? = null ) : KCollectionPropertyPath<T, I18nLabel?>(previous,property,additionalPath) { override val arrayProjection: I18nLabel_Col<T> @Suppress("UNCHECKED_CAST") get() = I18nLabel_Col(null, this as KProperty1<*, Collection<I18nLabel>?>, "$") val _id: KProperty1<T, Id<I18nLabel>?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::_id) val namespace: KProperty1<T, String?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::namespace) val category: KProperty1<T, String?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::category) val i18n: KProperty1<T, LinkedHashSet<I18nLocalizedLabel>?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::i18n) val defaultLabel: KProperty1<T, String?> get() = org.litote.kmongo.property.KPropertyPath(this,I18nLabel::defaultLabel) }
0
Kotlin
0
0
eaf43d68e8ab475707faa44d84911db717c74885
2,689
tock
Apache License 2.0
src/main/kotlin/org/docksidestage/app/web/startup/StartupBean.kt
t-kameyama
155,081,790
true
{"Maven POM": 1, "XML": 21, "EditorConfig": 1, "Markdown": 7, "Text": 26, "Ignore List": 13, "INI": 5, "Kotlin": 75, "HTML": 37, "CSS": 6, "JavaScript": 5, "Java": 222, "Java Properties": 10, "JSON": 6, "JSON with Comments": 2, "Shell": 24, "Batchfile": 28, "SQL": 6, "Roff": 1, "Perl": 3, "Python": 1, "XSLT": 14}
package org.docksidestage.app.web.startup import org.lastaflute.web.validation.Required /** * @author iwamatsu0430 * @author jflute */ class StartupBean(@field:Required val projectPath: String)
0
Java
1
0
a1544951284d5e2ed7b46583c5175c54045c08d3
217
lastaflute-example-paradeplaza
Apache License 2.0
storage/src/main/java/com/nikitamaslov/storage/model/single/SingleForecastEntity.kt
nikitamasloff
173,980,211
false
null
package com.nikitamaslov.storage.model.single import com.nikitamaslov.storage.model.common.WeatherEntity import com.nikitamaslov.storage.model.def.TemperatureUnitEntity import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import io.realm.annotations.RealmField internal open class SingleForecastEntity() : RealmObject(), Single { @Suppress("LeakingThis") @PrimaryKey override var id: String = singleKey @RealmField(name = "currentWeather") private var _currentWeather: WeatherEntity? = null val currentWeather: WeatherEntity get() = _currentWeather!! @RealmField(name = "futureWeather") private var _futureWeather = RealmList<WeatherEntity>() val futureWeather: Set<WeatherEntity> get() = _futureWeather.toSet() @RealmField(name = "latitude") private var _latitude: Double? = null val latitude: Double get() = _latitude!! @RealmField(name = "longitude") private var _longitude: Double? = null val longitude: Double get() = _longitude!! @RealmField(name = "city") private var _city: String? = null val city: String get() = _city!! @RealmField(name = "country") private var _country: String? = null val country: String get() = _country!! @RealmField(name = "temperatureUnit") private var _temperatureUnit: TemperatureUnitEntity? = null val temperatureUnit: TemperatureUnitEntity get() = _temperatureUnit!! @RealmField(name = "year") private var _year: Int? = null val year: Int get() = this._year!! @RealmField(name = "month") private var _month: Int? = null val month: Int get() = _month!! @RealmField(name = "dayOfMonth") private var _dayOfMonth: Int? = null val dayOfMonth: Int get() = _dayOfMonth!! @RealmField(name = "hour") private var _hour: Int? = null val hour: Int get() = _hour!! @RealmField(name = "minute") private var _minute: Int? = null val minute: Int get() = _minute!! constructor( currentWeather: WeatherEntity, futureWeather: Set<WeatherEntity>, latitude: Double, longitude: Double, city: String, country: String, temperatureUnit: TemperatureUnitEntity, year: Int, month: Int, dayOfMonth: Int, hour: Int, minute: Int ) : this() { this._currentWeather = currentWeather this._futureWeather.addAll(futureWeather) this._latitude = latitude this._longitude = longitude this._city = city this._country = country this._temperatureUnit = temperatureUnit this._year = year this._month = month this._dayOfMonth = dayOfMonth this._hour = hour this._minute = minute } }
0
null
0
0
110fb59984f7f376c982b68056efed91b6247b4b
2,791
weatherr
Apache License 2.0
idea/testData/intentions/usePropertyAccessSyntax/setAsExpressionBody.kt
JakeWharton
99,388,807
false
null
// WITH_RUNTIME fun foo(thread: Thread) = thread.setName("<name>")<caret>
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
73
kotlin
Apache License 2.0
01_KOTLIN/triple7/src/main/kotlin/lambda_04/Chapter5.kt
singhtwenty2
743,251,401
false
{"Kotlin": 215510, "Java": 16634}
package lambda_04 // Higher Order Functions fun main() { /* Higher order funs : Accpets one or more functions as parameters & also can return a fun as a value it treats funs as first class objs. */ val addResult = operateOnNumbers( a = 4, b = 6 ) { x, y -> x + y } val subtractResult = operateOnNumbers( a = 4, b = 6 ) {x , y -> x - y} val multiplyResult = operateOnNumbers( a = 4, b = 6 ) {x , y -> x * y} println(addResult) println(subtractResult) println(multiplyResult) } fun operateOnNumbers( a: Int, b: Int, operation: (Int, Int) -> Int // A fun passed as a parameter ): Int { return operation(a, b) }
0
Kotlin
0
1
37cf9cd2dd890ccd96f0691e250a2573f6e9df0d
726
AndroidWithKotlinJourney
MIT License
app/src/main/java/org/wikipedia/suggestededits/SuggestedEditsTasksFragment.kt
xCBATMANx
262,012,382
false
{"INI": 2, "Shell": 7, "YAML": 1, "Gradle": 6, "Text": 2, "Markdown": 2, "Batchfile": 1, "Ignore List": 2, "XML": 561, "Java Properties": 3, "SVG": 1, "Python": 5, "Jinja": 1, "Proguard": 2, "JSON": 54, "Java": 619, "CSS": 2, "JavaScript": 3, "HTML": 1, "Kotlin": 65}
package org.wikipedia.suggestededits import android.content.Intent import android.os.Bundle import android.view.* import android.view.View.GONE import android.view.View.VISIBLE import android.widget.Toast import androidx.core.widget.NestedScrollView import androidx.fragment.app.Fragment import androidx.recyclerview.widget.LinearLayoutManager import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.fragment_suggested_edits_tasks.* import org.wikipedia.Constants import org.wikipedia.Constants.ACTIVITY_REQUEST_ADD_A_LANGUAGE import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.analytics.SuggestedEditsFunnel import org.wikipedia.auth.AccountUtil import org.wikipedia.dataclient.Service import org.wikipedia.dataclient.ServiceFactory import org.wikipedia.dataclient.WikiSite import org.wikipedia.dataclient.mwapi.MwQueryResponse import org.wikipedia.descriptions.DescriptionEditActivity.Action.* import org.wikipedia.language.LanguageSettingsInvokeSource import org.wikipedia.main.MainActivity import org.wikipedia.settings.languages.WikipediaLanguagesActivity import org.wikipedia.util.* import org.wikipedia.util.log.L import org.wikipedia.views.DefaultRecyclerAdapter import org.wikipedia.views.DefaultViewHolder import org.wikipedia.views.DrawableItemDecoration class SuggestedEditsTasksFragment : Fragment() { private lateinit var addDescriptionsTask: SuggestedEditsTask private lateinit var addImageCaptionsTask: SuggestedEditsTask private val displayedTasks = ArrayList<SuggestedEditsTask>() private val callback = TaskViewCallback() private val disposables = CompositeDisposable() private var currentTooltip: Toast? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(R.layout.fragment_suggested_edits_tasks, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupTestingButtons() contributionsStatsView.setImageDrawable(R.drawable.ic_mode_edit_white_24dp) contributionsStatsView.setOnClickListener { onUserStatClicked(contributionsStatsView) } editStreakStatsView.setDescription(resources.getString(R.string.suggested_edits_edit_streak_label_text)) editStreakStatsView.setImageDrawable(R.drawable.ic_timer_black_24dp) editStreakStatsView.setOnClickListener { onUserStatClicked(editStreakStatsView) } pageViewStatsView.setDescription(getString(R.string.suggested_edits_pageviews_label_text)) pageViewStatsView.setImageDrawable(R.drawable.ic_trending_up_black_24dp) pageViewStatsView.setOnClickListener { onUserStatClicked(pageViewStatsView) } editQualityStatsView.setDescription(getString(R.string.suggested_edits_quality_label_text)) editQualityStatsView.setOnClickListener { onUserStatClicked(editQualityStatsView) } swipeRefreshLayout.setColorSchemeResources(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.colorAccent)) swipeRefreshLayout.setOnRefreshListener { this.refreshContents() } errorView.setRetryClickListener { refreshContents() } suggestedEditsScrollView.setOnScrollChangeListener(NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ -> (requireActivity() as MainActivity).updateToolbarElevation(scrollY > 0) }) setUpTasks() tasksRecyclerView.layoutManager = LinearLayoutManager(context) tasksRecyclerView.addItemDecoration(DrawableItemDecoration(requireContext(), R.attr.list_separator_drawable, false, false)) tasksRecyclerView.adapter = RecyclerAdapter(displayedTasks) clearContents() } private fun onUserStatClicked(view: View) { when (view) { contributionsStatsView -> showContributionsStatsViewTooltip() editStreakStatsView -> showEditStreakStatsViewTooltip() pageViewStatsView -> showPageViewStatsViewTooltip() else -> showEditQualityStatsViewTooltip() } } private fun hideCurrentTooltip() { if (currentTooltip != null) { currentTooltip!!.cancel() currentTooltip = null } } private fun showContributionsStatsViewTooltip() { hideCurrentTooltip() currentTooltip = FeedbackUtil.showToastOverView(contributionsStatsView, getString(R.string.suggested_edits_contributions_stat_tooltip), Toast.LENGTH_LONG) } private fun showEditStreakStatsViewTooltip() { hideCurrentTooltip() currentTooltip = FeedbackUtil.showToastOverView(editStreakStatsView, getString(R.string.suggested_edits_edit_streak_stat_tooltip), FeedbackUtil.LENGTH_LONG) } private fun showPageViewStatsViewTooltip() { hideCurrentTooltip() currentTooltip = FeedbackUtil.showToastOverView(pageViewStatsView, getString(R.string.suggested_edits_page_views_stat_tooltip), Toast.LENGTH_LONG) } private fun showEditQualityStatsViewTooltip() { hideCurrentTooltip() currentTooltip = FeedbackUtil.showToastOverView(editQualityStatsView, getString(R.string.suggested_edits_edit_quality_stat_tooltip, SuggestedEditsUserStats.totalReverts), FeedbackUtil.LENGTH_LONG) } override fun onPause() { super.onPause() hideCurrentTooltip() SuggestedEditsFunnel.get().pause() } override fun onResume() { super.onResume() refreshContents() SuggestedEditsFunnel.get().resume() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.menu_suggested_edits_tasks, menu) ResourceUtil.setMenuItemTint(context!!, menu.findItem(R.id.menu_help), R.attr.colorAccent) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == ACTIVITY_REQUEST_ADD_A_LANGUAGE) { tasksRecyclerView.adapter!!.notifyDataSetChanged() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.menu_help -> { FeedbackUtil.showAndroidAppEditingFAQ(requireContext()) super.onOptionsItemSelected(item) } else -> super.onOptionsItemSelected(item) } } override fun onDestroy() { super.onDestroy() disposables.clear() SuggestedEditsFunnel.get().log() SuggestedEditsFunnel.reset() } private fun fetchUserContributions() { if (!AccountUtil.isLoggedIn()) { return } progressBar.visibility = VISIBLE disposables.add(SuggestedEditsUserStats.getEditCountsObservable() .subscribe({ response -> val editorTaskCounts = response.query()!!.editorTaskCounts()!! if (response.query()!!.userInfo()!!.isBlocked) { setIPBlockedStatus() } else if (!maybeSetPausedOrDisabled()) { editQualityStatsView.setGoodnessState(SuggestedEditsUserStats.getRevertSeverity()) if (editorTaskCounts.editStreak < 2) { editStreakStatsView.setTitle(if (editorTaskCounts.lastEditDate.time > 0) DateUtil.getMDYDateString(editorTaskCounts.lastEditDate) else resources.getString(R.string.suggested_edits_last_edited_never)) editStreakStatsView.setDescription(resources.getString(R.string.suggested_edits_last_edited)) } else { editStreakStatsView.setTitle(resources.getQuantityString(R.plurals.suggested_edits_edit_streak_detail_text, editorTaskCounts.editStreak, editorTaskCounts.editStreak)) editStreakStatsView.setDescription(resources.getString(R.string.suggested_edits_edit_streak_label_text)) } getPageViews() } }, { t -> L.e(t) showError(t) })) } private fun getPageViews() { val qLangMap = HashMap<String, HashSet<String>>() disposables.add(ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getUserContributions(AccountUtil.getUserName()!!) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .flatMap { response -> for (userContribution in response.query()!!.userContributions()) { var descLang = "" val strArr = userContribution.comment.split(" ") for (str in strArr) { if (str.contains("wbsetdescription")) { val descArr = str.split("|") if (descArr.size > 1) { descLang = descArr[1] break } } } if (descLang.isEmpty()) { continue } if (!qLangMap.containsKey(userContribution.title)) { qLangMap[userContribution.title] = HashSet() } qLangMap[userContribution.title]!!.add(descLang) } ServiceFactory.get(WikiSite(Service.WIKIDATA_URL)).getWikidataLabelsAndDescriptions(qLangMap.keys.joinToString("|")) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) } .flatMap { if (it.entities().isEmpty()) { return@flatMap Observable.just(0L) } val langArticleMap = HashMap<String, ArrayList<String>>() for (entityKey in it.entities().keys) { val entity = it.entities()[entityKey]!! for (qKey in qLangMap.keys) { if (qKey == entityKey) { for (lang in qLangMap[qKey]!!) { val dbName = WikiSite.forLanguageCode(lang).dbName() if (entity.sitelinks().containsKey(dbName)) { if (!langArticleMap.containsKey(lang)) { langArticleMap[lang] = ArrayList() } langArticleMap[lang]!!.add(entity.sitelinks()[dbName]!!.title) } } break } } } val observableList = ArrayList<Observable<MwQueryResponse>>() for (lang in langArticleMap.keys) { val site = WikiSite.forLanguageCode(lang) observableList.add(ServiceFactory.get(site).getPageViewsForTitles(langArticleMap[lang]!!.joinToString("|")) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread())) } Observable.zip(observableList) { resultList -> var totalPageViews = 0L for (result in resultList) { if (result is MwQueryResponse && result.query() != null) { for (page in result.query()!!.pages()!!) { for (day in page.pageViewsMap.values) { totalPageViews += day ?: 0 } } } } totalPageViews } } .subscribe({ pageViewsCount -> pageViewStatsView.setTitle(pageViewsCount.toString()) setFinalUIState() }, { t -> L.e(t) showError(t) })) } private fun refreshContents() { requireActivity().invalidateOptionsMenu() fetchUserContributions() } private fun clearContents() { swipeRefreshLayout.isRefreshing = false progressBar.visibility = GONE tasksContainer.visibility = GONE errorView.visibility = GONE disabledStatesView.visibility = GONE suggestedEditsScrollView.scrollTo(0, 0) swipeRefreshLayout.setBackgroundColor(ResourceUtil.getThemedColor(requireContext(), R.attr.main_toolbar_color)) } private fun showError(t: Throwable) { clearContents() errorView.setError(t) errorView.visibility = VISIBLE } private fun setFinalUIState() { clearContents() if (SuggestedEditsUserStats.totalEdits == 0) { contributionsStatsView.visibility = GONE editQualityStatsView.visibility = GONE editStreakStatsView.visibility = GONE pageViewStatsView.visibility = GONE onboardingImageView.visibility = VISIBLE textViewForMessage.text = StringUtil.fromHtml(getString(R.string.suggested_edits_onboarding_message, AccountUtil.getUserName())) textViewForMessage.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_primary_color)) } else { contributionsStatsView.visibility = VISIBLE editQualityStatsView.visibility = VISIBLE editStreakStatsView.visibility = VISIBLE pageViewStatsView.visibility = VISIBLE onboardingImageView.visibility = GONE contributionsStatsView.setTitle(SuggestedEditsUserStats.totalEdits.toString()) contributionsStatsView.setDescription(resources.getQuantityString(R.plurals.suggested_edits_contribution, SuggestedEditsUserStats.totalEdits)) textViewForMessage.text = getString(R.string.suggested_edits_encouragement_message, AccountUtil.getUserName()) textViewForMessage.setTextColor(ResourceUtil.getThemedColor(requireContext(), R.attr.material_theme_secondary_color)) } swipeRefreshLayout.setBackgroundColor(ResourceUtil.getThemedColor(requireContext(), R.attr.paper_color)) tasksContainer.visibility = VISIBLE } private fun setIPBlockedStatus() { clearContents() disabledStatesView.setIPBlocked() disabledStatesView.visibility = VISIBLE } private fun maybeSetPausedOrDisabled(): Boolean { val pauseEndDate = SuggestedEditsUserStats.maybePauseAndGetEndDate() if (SuggestedEditsUserStats.isDisabled()) { // Disable the whole feature. clearContents() disabledStatesView.setDisabled(getString(R.string.suggested_edits_disabled_message, AccountUtil.getUserName())) disabledStatesView.visibility = VISIBLE return true } else if (pauseEndDate != null) { clearContents() disabledStatesView.setPaused(getString(R.string.suggested_edits_paused_message, DateUtil.getShortDateString(pauseEndDate), AccountUtil.getUserName())) disabledStatesView.visibility = VISIBLE return true } disabledStatesView.visibility = GONE return false } private fun setupTestingButtons() { if (!ReleaseUtil.isPreBetaRelease()) { ipBlocked.visibility = GONE onboarding1.visibility = GONE } ipBlocked.setOnClickListener { setIPBlockedStatus() } onboarding1.setOnClickListener { SuggestedEditsUserStats.totalEdits = 0; setFinalUIState() } } private fun setUpTasks() { displayedTasks.clear() addImageCaptionsTask = SuggestedEditsTask() addImageCaptionsTask.title = getString(R.string.suggested_edits_image_captions) addImageCaptionsTask.description = getString(R.string.suggested_edits_image_captions_task_detail) addImageCaptionsTask.imageDrawable = R.drawable.ic_image_caption displayedTasks.add(addImageCaptionsTask) addDescriptionsTask = SuggestedEditsTask() addDescriptionsTask.title = getString(R.string.description_edit_tutorial_title_descriptions) addDescriptionsTask.description = getString(R.string.suggested_edits_add_descriptions_task_detail) addDescriptionsTask.imageDrawable = R.drawable.ic_article_description displayedTasks.add(addDescriptionsTask) } private inner class TaskViewCallback : SuggestedEditsTaskView.Callback { override fun onViewClick(task: SuggestedEditsTask, isTranslate: Boolean) { if (WikipediaApp.getInstance().language().appLanguageCodes.size < Constants.MIN_LANGUAGES_TO_UNLOCK_TRANSLATION && isTranslate) { showLanguagesActivity(LanguageSettingsInvokeSource.SUGGESTED_EDITS.text()) return } if (task == addDescriptionsTask) { startActivity(SuggestedEditsCardsActivity.newIntent(requireActivity(), if (isTranslate) TRANSLATE_DESCRIPTION else ADD_DESCRIPTION)) } else if (task == addImageCaptionsTask) { startActivity(SuggestedEditsCardsActivity.newIntent(requireActivity(), if (isTranslate) TRANSLATE_CAPTION else ADD_CAPTION)) } } } private fun showLanguagesActivity(invokeSource: String) { val intent = WikipediaLanguagesActivity.newIntent(requireActivity(), invokeSource) startActivityForResult(intent, ACTIVITY_REQUEST_ADD_A_LANGUAGE) } internal inner class RecyclerAdapter(tasks: List<SuggestedEditsTask>) : DefaultRecyclerAdapter<SuggestedEditsTask, SuggestedEditsTaskView>(tasks) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DefaultViewHolder<SuggestedEditsTaskView> { return DefaultViewHolder(SuggestedEditsTaskView(parent.context)) } override fun onBindViewHolder(holder: DefaultViewHolder<SuggestedEditsTaskView>, i: Int) { holder.view.setUpViews(items()[i], callback) } } companion object { fun newInstance(): SuggestedEditsTasksFragment { return SuggestedEditsTasksFragment() } } }
1
null
1
1
f2e17e204f944b47ebef4b88888c48134bc4ae99
19,222
apps-android-wikipedia
Apache License 2.0
crystal-map-connector/src/test/kotlin/ch/ergon/dope/extensions/type/stringfunction/MBPosition1Test.kt
ergon
745,483,606
false
{"Kotlin": 1598239}
package ch.ergon.dope.extensions.type.stringfunction import ch.ergon.dope.DopeQueryManager import ch.ergon.dope.extension.type.stringfunction.mbPosition1 import ch.ergon.dope.helper.ManagerDependentTest import ch.ergon.dope.helper.someCMStringField import ch.ergon.dope.helper.someString import ch.ergon.dope.helper.someStringField import ch.ergon.dope.resolvable.expression.unaliased.type.function.stringfunction.MBPosition1Expression import ch.ergon.dope.resolvable.expression.unaliased.type.toDopeType import ch.ergon.dope.toDopeType import kotlin.test.Test import kotlin.test.assertEquals class MBPosition1Test : ManagerDependentTest { override lateinit var manager: DopeQueryManager @Test fun `should support MBPosition1 with CM string CM string`() { val string1 = someCMStringField() val string2 = someCMStringField() val expected = MBPosition1Expression(string1.toDopeType(), string2.toDopeType()) val actual = mbPosition1(string1, string2) assertEquals(expected.toDopeQuery(manager), actual.toDopeQuery(manager)) } @Test fun `should support MBPosition1 with CM string type`() { val string1 = someCMStringField() val string2 = someStringField() val expected = MBPosition1Expression(string1.toDopeType(), string2) val actual = mbPosition1(string1, string2) assertEquals(expected.toDopeQuery(manager), actual.toDopeQuery(manager)) } @Test fun `should support MBPosition1 with CM string string`() { val string1 = someCMStringField() val string2 = someString() val expected = MBPosition1Expression(string1.toDopeType(), string2.toDopeType()) val actual = mbPosition1(string1, string2) assertEquals(expected.toDopeQuery(manager), actual.toDopeQuery(manager)) } @Test fun `should support MBPosition1 with string CM string`() { val string1 = someString() val string2 = someCMStringField() val expected = MBPosition1Expression(string1.toDopeType(), string2.toDopeType()) val actual = mbPosition1(string1, string2) assertEquals(expected.toDopeQuery(manager), actual.toDopeQuery(manager)) } @Test fun `should support MBPosition1 with type CM string`() { val string1 = someStringField() val string2 = someCMStringField() val expected = MBPosition1Expression(string1, string2.toDopeType()) val actual = mbPosition1(string1, string2) assertEquals(expected.toDopeQuery(manager), actual.toDopeQuery(manager)) } }
5
Kotlin
0
6
68697444eff3f46c4293438d060fb69a8f4cde9f
2,586
dope-query-builder
MIT License
model/src/test/kotlin/com/android/gradle/replicator/model/internal/ModuleAdapterTest.kt
Saiprasad16
366,004,003
false
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.gradle.replicator.model.internal import com.android.gradle.replicator.model.DependencyType import com.android.gradle.replicator.model.PluginType import com.android.gradle.replicator.model.internal.fixtures.module import com.google.common.truth.Truth import org.junit.Test internal class ModuleAdapterTest { @Test fun `test write empty module`() { Truth.assertThat(emptyModuleObject().toJson()).isEqualTo(EMPTY_MODULE) } @Test fun `test load empty module`() { val module = emptyModuleObject() val loadedModule = EMPTY_MODULE.fromJson(ModuleAdapter()) Truth.assertThat(loadedModule).isEqualTo(module) } @Test fun `test load + write empty module`() { val loadedModule = EMPTY_MODULE.fromJson(ModuleAdapter()) Truth.assertThat(loadedModule.toJson()).isEqualTo(EMPTY_MODULE) } @Test fun `test write full module`() { Truth.assertThat(fullModuleObject().toJson()).isEqualTo(FULL_MODULE) } @Test fun `test load full module`() { val module = fullModuleObject() val loadedModule = FULL_MODULE.fromJson(ModuleAdapter()) Truth.assertThat(loadedModule).isEqualTo(module) } @Test fun `test load + write full module`() { val loadedModule = FULL_MODULE.fromJson(ModuleAdapter()) Truth.assertThat(loadedModule.toJson()).isEqualTo(FULL_MODULE) } // -------------------------- /** * this should match [EMPTY_MODULE] */ private fun emptyModuleObject() = module { path = ":foo" } /** * this should match [FULL_MODULE] */ private fun fullModuleObject() = module { path = ":foo" plugins = listOf(PluginType.ANDROID_APP, PluginType.KOTLIN_ANDROID) javaSources { fileCount = 1 } kotlinSources { fileCount = 2 } dependencies = listOf( DefaultDependenciesInfo(DependencyType.MODULE, "module1", "api"), DefaultDependenciesInfo(DependencyType.MODULE, "module2", "implementation"), DefaultDependenciesInfo(DependencyType.EXTERNAL_LIBRARY, "lib:foo:1.0", "api") ) android { compileSdkVersion = "android-30" minSdkVersion = 24 targetSdkVersion = 30 buildFeatures { androidResources = true compose = true } } } } private val EMPTY_MODULE = """ { "path": ":foo", "plugins": [], "dependencies": [] } """.trimIndent() private val FULL_MODULE = """ { "path": ":foo", "plugins": [ "com.android.application", "org.jetbrains.kotlin.android" ], "javaSources": { "fileCount": 1 }, "kotlinSources": { "fileCount": 2 }, "dependencies": [ { "moduleName": "module1", "method": "api" }, { "moduleName": "module2", "method": "implementation" }, { "library": "lib:foo:1.0", "method": "api" } ], "android": { "compileSdkVersion": "android-30", "minSdkVersion": 24, "targetSdkVersion": 30, "buildFeatures": { "androidResources": true, "compose": true } } } """.trimIndent()
0
null
0
1
f011487876f47c13fe338544410b3231f834b415
4,040
project-replicator
Apache License 2.0
android-npw/src/com/android/tools/idea/npw/model/NewTemplateRenderer.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.npw.model import com.android.tools.analytics.UsageTracker import com.android.tools.analytics.withProjectId import com.android.tools.idea.templates.recipe.DefaultRecipeExecutor import com.android.tools.idea.templates.recipe.FindReferencesRecipeExecutor import com.android.tools.idea.templates.recipe.RenderingContext import com.android.tools.idea.util.ReformatUtil import com.android.tools.idea.wizard.template.FormFactor import com.android.tools.idea.wizard.template.Language import com.android.tools.idea.wizard.template.ProjectTemplateData import com.android.tools.idea.wizard.template.Recipe import com.android.tools.idea.wizard.template.RecipeExecutor import com.android.tools.idea.wizard.template.Template import com.google.common.annotations.VisibleForTesting import com.google.wireless.android.sdk.stats.AndroidStudioEvent import com.google.wireless.android.sdk.stats.AndroidStudioEvent.TemplateRenderer import com.google.wireless.android.sdk.stats.AndroidStudioEvent.TemplatesUsage import com.google.wireless.android.sdk.stats.AndroidStudioEvent.TemplatesUsage.TemplateComponent.TemplateType import com.google.wireless.android.sdk.stats.AndroidStudioEvent.TemplatesUsage.TemplateModule.BytecodeLevel import com.google.wireless.android.sdk.stats.AndroidStudioEvent.TemplatesUsage.TemplateModule.ModuleType import com.google.wireless.android.sdk.stats.KotlinSupport import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeeded import com.intellij.openapi.command.UndoConfirmationPolicy import com.intellij.openapi.command.WriteCommandAction.writeCommandAction import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.intellij.psi.PsiDocumentManager import com.intellij.psi.impl.source.PostprocessReformattingAspect import org.jetbrains.android.util.AndroidBundle.message import java.io.IOException import java.util.concurrent.atomic.AtomicBoolean import com.android.tools.idea.wizard.template.BytecodeLevel as TemplateBytecodeLevel private val log: Logger get() = logger<Template>() fun Template.render(c: RenderingContext, e: RecipeExecutor, metrics: TemplateMetrics? = null) = recipe.render(c, e, titleToTemplateRenderer(name, formFactor), metrics) fun Recipe.findReferences(c: RenderingContext) = render(c, FindReferencesRecipeExecutor(c)) fun Recipe.actuallyRender(c: RenderingContext) = render(c, DefaultRecipeExecutor(c)) fun Recipe.render(c: RenderingContext, e: RecipeExecutor): Boolean { val success = if (c.project.isInitialized) doRender(c, e) else PostprocessReformattingAspect.getInstance(c.project).disablePostprocessFormattingInside<Boolean> { doRender(c, e) } if (!c.dryRun) { ApplicationManager.getApplication().invokeAndWait { PsiDocumentManager.getInstance(c.project).commitAllDocuments() } ReformatUtil.reformatRearrangeAndSave(c.project, c.targetFiles) } return success } fun Recipe.render(c: RenderingContext, e: RecipeExecutor, loggingEvent: TemplateRenderer, metrics: TemplateMetrics? = null): Boolean { return render(c, e).also { if (!c.dryRun) { logRendering(c.projectTemplateData, c.project, loggingEvent) if (metrics != null) { logRendering(c.projectTemplateData, c.project, metrics) } } } } private fun Recipe.doRender(c: RenderingContext, e: RecipeExecutor): Boolean { try { writeCommandAction(c.project) .withName(c.commandName) .withGlobalUndo() .withUndoConfirmationPolicy(UndoConfirmationPolicy.REQUEST_CONFIRMATION) .run<IOException> { this(e, c.templateData) if (e is DefaultRecipeExecutor) { e.applyChanges() } } } catch (e: IOException) { if (c.showErrors) { invokeAndWaitIfNeeded { Messages.showErrorDialog(c.project, formatErrorMessage(c.commandName, !c.dryRun, e), "${c.commandName} Failed") } } else { throw RuntimeException(e) } return false } if (c.warnings.isEmpty()) { return true } if (!c.showWarnings) { log.warn("WARNING: " + c.warnings) return true } val result = AtomicBoolean() ApplicationManager.getApplication().invokeAndWait { val userReply = Messages.showOkCancelDialog( c.project, formatWarningMessage(c), "${c.commandName}, Warnings", "Proceed Anyway", "Cancel", Messages.getWarningIcon()) result.set(userReply == Messages.OK) } return result.get() } /** * If this is not a dry run, we may have created/changed some files and the project * may no longer compile. Let the user know about undo. */ fun formatErrorMessage(commandName: String, canCausePartialRendering: Boolean, ex: IOException): String = if (!canCausePartialRendering) ex.message ?: "Unknown IOException occurred" else """${ex.message} $commandName was only partially completed. Your project may not compile. You may want to Undo to get back to the original state. """ fun formatWarningMessage(context: RenderingContext): String { val maxWarnings = 10 val warningCount = context.warnings.size var messages: MutableList<String> = context.warnings.toMutableList() if (warningCount > maxWarnings + 1) { // +1 such that the message can say "warnings" in plural... // Guard against too many warnings (the dialog may become larger than the screen size) messages = messages.subList(0, maxWarnings) val strippedWarningsCount = warningCount - maxWarnings messages.add("And $strippedWarningsCount more warnings...") } messages.add("\nIf you proceed the resulting project may not compile or not work as intended.") return messages.joinToString("\n\n") } // TODO(qumeric): update TemplateRenderer and this method @Suppress("DEPRECATION") @VisibleForTesting fun titleToTemplateRenderer(title: String, formFactor: FormFactor): TemplateRenderer = when (title) { "" -> TemplateRenderer.UNKNOWN_TEMPLATE_RENDERER "Android Project" -> TemplateRenderer.ANDROID_PROJECT message("android.wizard.module.new.baselineprofiles.module.app") -> TemplateRenderer.BASELINE_PROFILES_MODULE message("android.wizard.module.new.benchmark.module.app") -> TemplateRenderer.BENCHMARK_LIBRARY_MODULE message("android.wizard.module.new.mobile") -> TemplateRenderer.ANDROID_MODULE message("android.wizard.module.new.java.or.kotlin.library") -> TemplateRenderer.JAVA_LIBRARY message("android.wizard.module.new.tv") -> TemplateRenderer.ANDROID_TV_MODULE message("android.wizard.module.new.dynamic.module") -> TemplateRenderer.ANDROID_INSTANT_APP_DYNAMIC_MODULE message("android.wizard.module.new.wear") -> TemplateRenderer.ANDROID_WEAR_MODULE "Basic Views Activity" -> TemplateRenderer.BASIC_ACTIVITIY "Basic Activity (Material3)" -> TemplateRenderer.BASIC_ACTIVITIY "Empty Views Activity" -> TemplateRenderer.EMPTY_ACTIVITY "Blank Activity" -> if (formFactor == FormFactor.Wear) TemplateRenderer.BLANK_WEAR_ACTIVITY else TemplateRenderer.BLANK_ACTIVITY "Login Views Activity" -> TemplateRenderer.LOGIN_ACTIVITY "Tabbed Views Activity" -> TemplateRenderer.TABBED_ACTIVITY "Scrolling Views Activity" -> TemplateRenderer.SCROLLING_ACTIVITY "Google AdMob Ads Views Activity" -> TemplateRenderer.GOOGLE_ADMOBS_ADS_ACTIVITY "Always On Wear Activity" -> TemplateRenderer.ALWAYS_ON_WEAR_ACTIVITY "Android TV Blank Activity" -> TemplateRenderer.ANDROID_TV_ACTIVITY "Android TV Blank Views Activity" -> TemplateRenderer.ANDROID_TV_ACTIVITY "Fullscreen Views Activity" -> TemplateRenderer.FULLSCREEN_ACTIVITY "Empty Activity" -> TemplateRenderer.COMPOSE_EMPTY_ACTIVITY "Empty Compose Activity (Material3)" -> TemplateRenderer.COMPOSE_EMPTY_ACTIVITY "Google Maps Views Activity" -> TemplateRenderer.GOOGLE_MAPS_ACTIVITY "Navigation Drawer Views Activity" -> TemplateRenderer.NAVIGATION_DRAWER_ACTIVITY "Settings Views Activity" -> TemplateRenderer.SETTINGS_ACTIVITY "Responsive Views Activity" -> TemplateRenderer.RESPONSIVE_ACTIVITY "Primary/Detail Views Flow" -> TemplateRenderer.MASTER_DETAIL_FLOW "Android Things Empty Activity" -> TemplateRenderer.THINGS_ACTIVITY "Messaging Service" -> TemplateRenderer.AUTOMOTIVE_MESSAGING_SERVICE "Media Service" -> TemplateRenderer.AUTOMOTIVE_MEDIA_SERVICE "Google Pay Views Activity" -> TemplateRenderer.GOOGLE_PAY_ACTIVITY "Watch Face" -> TemplateRenderer.WATCH_FACE "Empty Wear OS Compose Activity" -> TemplateRenderer.BLANK_WEAR_ACTIVITY "Google Wallet Activity" -> TemplateRenderer.GOOGLE_WALLET_ACTIVITY "Empty Wear App", "Empty Wear App With Tile And Complication" -> TemplateRenderer.BLANK_WEAR_ACTIVITY "Fullscreen Fragment" -> TemplateRenderer.FRAGMENT_FULLSCREEN "Google AdMob Ads Fragment" -> TemplateRenderer.FRAGMENT_GOOGLE_ADMOB_ADS "Google Maps Fragment" -> TemplateRenderer.FRAGMENT_GOOGLE_MAPS "Login Fragment" -> TemplateRenderer.FRAGMENT_LOGIN "Modal Bottom Sheet" -> TemplateRenderer.FRAGMENT_MODAL_BOTTOM_SHEET "Scrolling Fragment" -> TemplateRenderer.FRAGMENT_SCROLL "Settings Fragment" -> TemplateRenderer.FRAGMENT_SETTINGS "Fragment (with ViewModel)" -> TemplateRenderer.FRAGMENT_VIEWMODEL "Fragment (Blank)" -> TemplateRenderer.FRAGMENT_BLANK "Fragment (List)" -> TemplateRenderer.FRAGMENT_LIST "Assets Folder" -> TemplateRenderer.ASSETS_FOLDER "AIDL File" -> TemplateRenderer.AIDL_FILE "JNI Folder" -> TemplateRenderer.JNI_FOLDER "Java Folder" -> TemplateRenderer.JAVA_FOLDER "Service" -> TemplateRenderer.SERVICE "Broadcast Receiver" -> TemplateRenderer.BROADCAST_RECEIVER "Service (IntentService)" -> TemplateRenderer.INTENT_SERVICE "Custom View" -> TemplateRenderer.CUSTOM_VIEW "Res Folder" -> TemplateRenderer.RES_FOLDER "App Widget" -> TemplateRenderer.APP_WIDGET "Layout XML File" -> TemplateRenderer.LAYOUT_XML_FILE "Values XML File" -> TemplateRenderer.VALUES_XML_FILE else -> TemplateRenderer.CUSTOM_TEMPLATE_RENDERER } @Suppress("DEPRECATION") fun titleToTemplateType(title: String, formFactor: FormFactor): TemplateType { return when (titleToTemplateRenderer(title, formFactor)) { TemplateRenderer.UNKNOWN_TEMPLATE_RENDERER -> TemplateType.UNKNOWN_TEMPLATE // Note: These values where never added/missing from the old TemplateRenderer TemplateRenderer.CUSTOM_TEMPLATE_RENDERER -> when (title) { "Slice Provider" -> TemplateType.SLICE_PROVIDER "Fragment + ViewModel" -> TemplateType.VIEW_MODEL_ACTIVITY "Bottom Navigation Views Activity" -> TemplateType.BOTTOM_NAVIGATION_ACTIVITY "Native C++" -> TemplateType.CPP_EMPTY_ACTIVITY "Game Activity (C++)" -> TemplateType.CPP_GAME_ACTIVITY "AIDL Folder" -> TemplateType.AIDL_FOLDER "Font Folder" -> TemplateType.FONT_FOLDER "Raw Resources Folder" -> TemplateType.RAW_RESOURCES_FOLDER "Java Resources Folder" -> TemplateType.JAVA_RESOURCES_FOLDER "XML Resources Folder" -> TemplateType.XML_RESOURCES_FOLDER "RenderScript Folder" -> TemplateType.RENDER_SCRIPT_FOLDER "Content Provider" -> TemplateType.CONTENT_PROVIDER "Android Manifest File" -> TemplateType.ANDROID_MANIFEST_FILE "App Actions XML File (deprecated)" -> TemplateType.APP_ACTIONS_XML_FILE "Shortcuts XML File" -> TemplateType.SHORTCUTS_XML_FILE else -> TemplateType.CUSTOM_TEMPLATE } TemplateRenderer.EMPTY_ACTIVITY -> TemplateType.EMPTY_ACTIVITY TemplateRenderer.LAYOUT_XML_FILE -> TemplateType.LAYOUT_XML_FILE TemplateRenderer.FRAGMENT_BLANK -> TemplateType.FRAGMENT_BLANK TemplateRenderer.NAVIGATION_DRAWER_ACTIVITY -> TemplateType.NAVIGATION_DRAWER_ACTIVITY TemplateRenderer.VALUES_XML_FILE -> TemplateType.VALUES_XML_FILE TemplateRenderer.GOOGLE_MAPS_ACTIVITY -> TemplateType.GOOGLE_MAPS_ACTIVITY TemplateRenderer.LOGIN_ACTIVITY -> TemplateType.LOGIN_ACTIVITY TemplateRenderer.ASSETS_FOLDER -> TemplateType.ASSETS_FOLDER TemplateRenderer.TABBED_ACTIVITY -> TemplateType.TABBED_ACTIVITY TemplateRenderer.SCROLLING_ACTIVITY -> TemplateType.SCROLLING_ACTIVITY TemplateRenderer.FULLSCREEN_ACTIVITY -> TemplateType.FULLSCREEN_ACTIVITY TemplateRenderer.SERVICE -> TemplateType.SERVICE TemplateRenderer.SETTINGS_ACTIVITY -> TemplateType.SETTINGS_ACTIVITY TemplateRenderer.FRAGMENT_LIST -> TemplateType.FRAGMENT_LIST TemplateRenderer.MASTER_DETAIL_FLOW -> TemplateType.PRIMARY_DETAIL_FLOW_ACTIVITY TemplateRenderer.BROADCAST_RECEIVER -> TemplateType.BROADCAST_RECEIVER TemplateRenderer.AIDL_FILE -> TemplateType.AIDL_FILE TemplateRenderer.INTENT_SERVICE -> TemplateType.INTENT_SERVICE TemplateRenderer.JNI_FOLDER -> TemplateType.JNI_FOLDER TemplateRenderer.JAVA_FOLDER -> TemplateType.JAVA_FOLDER TemplateRenderer.CUSTOM_VIEW -> TemplateType.CUSTOM_VIEW TemplateRenderer.GOOGLE_ADMOBS_ADS_ACTIVITY -> TemplateType.GOOGLE_ADMOBS_ADS_ACTIVITY TemplateRenderer.RES_FOLDER -> TemplateType.RES_FOLDER TemplateRenderer.ANDROID_TV_ACTIVITY -> TemplateType.ANDROID_TV_EMPTY_ACTIVITY TemplateRenderer.BLANK_WEAR_ACTIVITY -> TemplateType.BLANK_WEAR_ACTIVITY TemplateRenderer.BASIC_ACTIVITIY -> TemplateType.BASIC_ACTIVITY TemplateRenderer.APP_WIDGET -> TemplateType.APP_WIDGET TemplateRenderer.FRAGMENT_FULLSCREEN -> TemplateType.FRAGMENT_FULLSCREEN TemplateRenderer.FRAGMENT_GOOGLE_ADMOB_ADS -> TemplateType.FRAGMENT_GOOGLE_ADMOB_ADS TemplateRenderer.FRAGMENT_GOOGLE_MAPS -> TemplateType.FRAGMENT_GOOGLE_MAPS TemplateRenderer.FRAGMENT_LOGIN -> TemplateType.FRAGMENT_LOGIN TemplateRenderer.FRAGMENT_MODAL_BOTTOM_SHEET -> TemplateType.FRAGMENT_MODAL_BOTTOM_SHEET TemplateRenderer.FRAGMENT_SCROLL -> TemplateType.FRAGMENT_SCROLL TemplateRenderer.FRAGMENT_SETTINGS -> TemplateType.FRAGMENT_SETTINGS TemplateRenderer.FRAGMENT_VIEWMODEL -> TemplateType.FRAGMENT_VIEW_MODEL TemplateRenderer.COMPOSE_EMPTY_ACTIVITY -> TemplateType.COMPOSE_EMPTY_ACTIVITY TemplateRenderer.AUTOMOTIVE_MEDIA_SERVICE -> TemplateType.AUTOMOTIVE_MEDIA_SERVICE TemplateRenderer.AUTOMOTIVE_MESSAGING_SERVICE -> TemplateType.AUTOMOTIVE_MESSAGING_SERVICE TemplateRenderer.THINGS_ACTIVITY -> TemplateType.THINGS_EMPTY_ACTIVITY TemplateRenderer.WATCH_GOOGLE_MAPS_ACTIVITY -> TemplateType.WEAR_GOOGLE_MAPS_ACTIVITY TemplateRenderer.WATCH_FACE -> TemplateType.WEAR_FACE_ACTIVITY TemplateRenderer.WEAR_OS_COMPOSE_ACTIVITY -> TemplateType.EMPTY_ACTIVITY TemplateRenderer.RESPONSIVE_ACTIVITY -> TemplateType.RESPONSIVE_ACTIVITY TemplateRenderer.GOOGLE_PAY_ACTIVITY -> TemplateType.GOOGLE_PAY_ACTIVITY TemplateRenderer.GOOGLE_WALLET_ACTIVITY -> TemplateType.GOOGLE_WALLET_ACTIVITY TemplateRenderer.BLANK_ACTIVITY, TemplateRenderer.ANDROID_MODULE, TemplateRenderer.ANDROID_PROJECT, TemplateRenderer.JAVA_LIBRARY, TemplateRenderer.ANDROID_WEAR_MODULE, TemplateRenderer.ANDROID_TV_MODULE, TemplateRenderer.ALWAYS_ON_WEAR_ACTIVITY, TemplateRenderer.ANDROID_INSTANT_APP_PROJECT, TemplateRenderer.ANDROID_INSTANT_APP_MODULE, TemplateRenderer.ANDROID_INSTANT_APP_BUNDLE_PROJECT, TemplateRenderer.ANDROID_INSTANT_APP_DYNAMIC_MODULE, TemplateRenderer.BENCHMARK_LIBRARY_MODULE, TemplateRenderer.MACROBENCHMARK_LIBRARY_MODULE, TemplateRenderer.ANDROID_LIBRARY, TemplateRenderer.DYNAMIC_FEATURE_MODULE, TemplateRenderer.INSTANT_DYNAMIC_FEATURE_MODULE, TemplateRenderer.AUTOMOTIVE_MODULE, TemplateRenderer.THINGS_MODULE, TemplateRenderer.ML_MODEL_BINDING_IMPORT_WIZARD, TemplateRenderer.ML_MODEL_BINDING_FEATURE_OFF_NOTIFICATION, TemplateRenderer.ANDROID_NATIVE_MODULE, TemplateRenderer.BASELINE_PROFILES_MODULE -> throw RuntimeException("Invalid Template Title") } } fun moduleTemplateRendererToModuleType(moduleTemplateRenderer: TemplateRenderer): ModuleType { return when (moduleTemplateRenderer) { TemplateRenderer.UNKNOWN_TEMPLATE_RENDERER -> ModuleType.NOT_APPLICABLE // Existing module, can't find what type is TemplateRenderer.ANDROID_MODULE -> ModuleType.PHONE_TABLET TemplateRenderer.ANDROID_LIBRARY -> ModuleType.ANDROID_LIBRARY TemplateRenderer.DYNAMIC_FEATURE_MODULE -> ModuleType.DYNAMIC_FEATURE TemplateRenderer.INSTANT_DYNAMIC_FEATURE_MODULE -> ModuleType.INSTANT_DYNAMIC_FEATURE TemplateRenderer.AUTOMOTIVE_MODULE -> ModuleType.AUTOMOTIVE TemplateRenderer.ANDROID_WEAR_MODULE -> ModuleType.WEAR_OS TemplateRenderer.ANDROID_TV_MODULE -> ModuleType.ANDROID_TV TemplateRenderer.THINGS_MODULE -> ModuleType.ANDROID_THINGS TemplateRenderer.JAVA_LIBRARY -> ModuleType.JAVA_OR_KOTLIN_LIBRARY TemplateRenderer.BENCHMARK_LIBRARY_MODULE -> ModuleType.BENCHMARK_LIBRARY TemplateRenderer.BASELINE_PROFILES_MODULE -> ModuleType.BASELINE_PROFILES else -> ModuleType.UNKNOWN // TODO: b/161230278 Some new modules don't render a template. Need to send the event from their Model render. // IMPORT_GRADLE = 10; IMPORT_ECLIPSE = 11; IMPORT_JAR_AAR = 12; } } fun logRendering(projectData: ProjectTemplateData, project: Project, templateRenderer: TemplateRenderer) { val aseBuilder = AndroidStudioEvent.newBuilder() .setCategory(AndroidStudioEvent.EventCategory.TEMPLATE) .setKind(AndroidStudioEvent.EventKind.TEMPLATE_RENDER) .setTemplateRenderer(templateRenderer) .setKotlinSupport( KotlinSupport.newBuilder() .setIncludeKotlinSupport(projectData.language == Language.Kotlin) .setKotlinSupportVersion(projectData.kotlinVersion)) UsageTracker.log(aseBuilder.withProjectId(project)) // Log event if user declined to add kotlin support in a new project if (templateRenderer == TemplateRenderer.ANDROID_PROJECT && projectData.language != Language.Kotlin) { UsageTracker.log(AndroidStudioEvent.newBuilder().apply { kind = AndroidStudioEvent.EventKind.KOTLIN_SUPPORT_DECLINED_EVENT this.templateRenderer = templateRenderer }.withProjectId(project)) } } fun logRendering(projectData: ProjectTemplateData, project: Project, metrics: TemplateMetrics) { val templateComponentBuilder = TemplatesUsage.TemplateComponent.newBuilder().apply { templateType = metrics.templateType wizardUiContext = metrics.wizardContext } val templateModuleBuilder = TemplatesUsage.TemplateModule.newBuilder().apply { moduleType = metrics.moduleType minSdk = metrics.minSdk if (metrics.bytecodeLevel != null) { bytecodeLevel = when (metrics.bytecodeLevel) { TemplateBytecodeLevel.L6 -> BytecodeLevel.LEVEL_6 TemplateBytecodeLevel.L7 -> BytecodeLevel.LEVEL_7 TemplateBytecodeLevel.L8 -> BytecodeLevel.LEVEL_8 } } } val templateProjectBuilder = TemplatesUsage.TemplateProject.newBuilder().apply { usesLegacySupport = metrics.useAppCompat usesBuildGradleKts = metrics.useGradleKts } val kotlinSupport = KotlinSupport.newBuilder().apply { includeKotlinSupport = projectData.language == Language.Kotlin kotlinSupportVersion = projectData.kotlinVersion } val aseBuilder = AndroidStudioEvent.newBuilder() .setCategory(AndroidStudioEvent.EventCategory.TEMPLATE) .setKind(AndroidStudioEvent.EventKind.WIZARD_TEMPLATES_USAGE) .setTemplateUsage( TemplatesUsage.newBuilder() .setTemplateComponent(templateComponentBuilder) .setTemplateModule(templateModuleBuilder) .setTemplateProject(templateProjectBuilder) .setKotlinSupport(kotlinSupport) ) UsageTracker.log(aseBuilder.withProjectId(project)) }
5
null
230
948
10110983c7e784122d94c7467e9d243aba943bf4
20,215
android
Apache License 2.0
jb/src/main/kotlin/extensions/SelectionEvent.kt
TeamCodeStream
148,423,109
false
null
package com.codestream.extensions import com.codestream.protocols.webview.EditorSelection import com.intellij.openapi.editor.event.SelectionEvent import org.eclipse.lsp4j.Range val SelectionEvent.editorSelections: List<EditorSelection> get() = newRanges.map { EditorSelection( editor.document.lspPosition(it.startOffset), editor.document.lspPosition(it.endOffset), editor.document.lspPosition(editor.caretModel.offset) ) } val SelectionEvent.lspRange: Range get() = Range( editor.document.lspPosition(newRange.startOffset), editor.document.lspPosition(newRange.endOffset) )
21
null
182
930
3989ca8f40ab33312f32887bf390262323676b5e
661
codestream
Apache License 2.0
stratum/server/src/main/kotlin/org/apache/tuweni/stratum/server/JsonRpc.kt
apache
178,461,625
false
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.tuweni.stratum.server import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.annotation.JsonProperty import org.apache.tuweni.bytes.Bytes import org.apache.tuweni.bytes.Bytes32 @JsonIgnoreProperties(ignoreUnknown = true) data class JsonRpcRequest( @JsonProperty("jsonrpc") val jsonrpc: String?, @JsonProperty("method") val method: String, @JsonProperty("params") val params: MutableList<Any> = mutableListOf(), @JsonProperty("id") val id: Long ) { fun bytes32(i: Int): Bytes32 = Bytes32.fromHexStringLenient(params[i] as String) fun bytes(i: Int): Bytes = Bytes.fromHexStringLenient(params[i] as String) } data class JsonRpcSuccessResponse( @JsonProperty("id") val id: Long, @JsonProperty("jsonrpc") val jsonrpc: String = "2.0", @JsonProperty("result") val result: Any ) data class JsonRpcSuccessResponseWithoutID( @JsonProperty("jsonrpc") val jsonrpc: String = "2.0", @JsonProperty("result") val result: Any )
6
null
78
171
0852e0b01ad126b47edae51b26e808cb73e294b1
1,796
incubator-tuweni
Apache License 2.0
beagle/src/main/kotlin/br/com/zup/beagle/android/networking/HttpMethod.kt
ZupIT
391,144,851
false
null
/* * Copyright 2020 ZUP IT SERVICOS EM TECNOLOGIA E INOVACAO SA * * 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 br.com.zup.beagle.widget.networking /** * HttpAdditionalData is used to do requests. * @param method HTTP method. * @param headers Header items for the request. * @param body Content that will be delivered with the request. */ data class HttpAdditionalData( val method: HttpMethod? = null, val headers: Map<String, String>? = null, val body: Any? = null, ) /** * Http method to indicate the desired action to be performed for a given resource. * */ enum class HttpMethod { /** * The GET method requests a representation of the specified resource. Requests using GET should only retrieve * data. */ GET, /** * The POST method is used to submit an entity to the specified resource, often causing * a change in state or side effects on the server. */ POST, /** * The PUT method replaces all current representations of the target resource with the request payload. */ PUT, /** * The DELETE method deletes the specified resource. */ DELETE, /** * The HEAD method asks for a response identical to that of a GET request, but without the response body. */ HEAD, /** * The PATCH method is used to apply partial modifications to a resource. */ PATCH, }
5
null
2
9
812a330777edd79a123495e9f678dc8f25a019f7
1,923
beagle-android
Apache License 2.0
app/src/main/java/com/eyther/lumbridge/usecase/shopping/SaveShoppingListUseCase.kt
ruialmeida51
249,223,684
false
{"Kotlin": 904675}
package com.eyther.lumbridge.usecase.shopping import com.eyther.lumbridge.domain.repository.shopping.ShoppingRepository import com.eyther.lumbridge.mapper.shopping.toDomain import com.eyther.lumbridge.model.shopping.ShoppingListUi import javax.inject.Inject class SaveShoppingListUseCase @Inject constructor( private val shoppingRepository: ShoppingRepository ) { suspend operator fun invoke(shoppingList: ShoppingListUi) { shoppingRepository.saveShoppingList(shoppingList.toDomain()) } }
6
Kotlin
0
7
5dd18b22448b2435f0238cccfc11a6826f200748
511
lumbridge-android
MIT License
feature-train/src/main/java/com/dragote/feature/train/training/domain/entity/Answers.kt
Dragote
718,160,762
false
{"Kotlin": 147679}
package com.dragote.feature.train.training.domain.entity import com.dragote.shared.country.domain.entity.Country data class Answers( val correctCountry : Country, val options: List<Country> )
0
Kotlin
0
2
59d44860a9a74bd8824e6e617f834102a3a1f7b1
201
Flapp
MIT License
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/SeatAisleReservationMedium.kt
SchweizerischeBundesbahnen
853,290,161
false
{"Kotlin": 6728512}
package ch.sbb.compose_mds.sbbicons.medium import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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 ch.sbb.compose_mds.sbbicons.MediumGroup public val MediumGroup.SeatAisleReservationMedium: ImageVector get() { if (_seatAisleReservationMedium != null) { return _seatAisleReservationMedium!! } _seatAisleReservationMedium = Builder(name = "SeatAisleReservationMedium", defaultWidth = 36.0.dp, defaultHeight = 36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(10.25f, 10.5f) arcToRelative(1.75f, 1.75f, 0.0f, true, true, 3.5f, 0.0f) arcToRelative(1.75f, 1.75f, 0.0f, false, true, -3.5f, 0.0f) moveTo(12.0f, 7.75f) arcToRelative(2.75f, 2.75f, 0.0f, true, false, 0.0f, 5.5f) arcToRelative(2.75f, 2.75f, 0.0f, false, false, 0.0f, -5.5f) moveToRelative(-5.72f, 5.17f) lineToRelative(6.0f, 16.5f) lineToRelative(0.12f, 0.33f) lineTo(24.0f, 29.75f) verticalLineToRelative(-1.0f) lineTo(13.1f, 28.75f) lineTo(7.22f, 12.58f) close() moveTo(13.965f, 15.25f) horizontalLineToRelative(-0.015f) curveToRelative(-1.334f, 0.01f, -2.233f, 1.328f, -1.791f, 2.572f) verticalLineToRelative(0.004f) lineToRelative(3.12f, 8.595f) lineToRelative(0.12f, 0.329f) horizontalLineToRelative(9.186f) curveToRelative(0.365f, 0.0f, 0.711f, 0.206f, 0.882f, 0.538f) lineToRelative(2.575f, 5.912f) lineToRelative(0.916f, -0.4f) lineToRelative(-2.58f, -5.925f) lineToRelative(-0.005f, -0.012f) lineToRelative(-0.006f, -0.012f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, -1.782f, -1.101f) horizontalLineToRelative(-1.168f) lineToRelative(-5.75f, -4.312f) lineToRelative(-1.84f, -4.889f) verticalLineToRelative(-0.003f) arcToRelative(2.01f, 2.01f, 0.0f, false, false, -1.862f, -1.296f) moveToRelative(-0.008f, 1.0f) arcToRelative(0.92f, 0.92f, 0.0f, false, false, -0.856f, 1.236f) verticalLineToRelative(0.002f) lineToRelative(3.0f, 8.262f) horizontalLineToRelative(5.649f) lineToRelative(-4.8f, -3.6f) lineToRelative(-0.117f, -0.087f) lineToRelative(-0.051f, -0.137f) lineToRelative(-1.89f, -5.023f) arcToRelative(1.01f, 1.01f, 0.0f, false, false, -0.934f, -0.653f) } } .build() return _seatAisleReservationMedium!! } private var _seatAisleReservationMedium: ImageVector? = null
0
Kotlin
0
1
090a66a40e1e5a44d4da6209659287a68cae835d
3,631
mds-android-compose
MIT License
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/medium/SeatAisleReservationMedium.kt
SchweizerischeBundesbahnen
853,290,161
false
{"Kotlin": 6728512}
package ch.sbb.compose_mds.sbbicons.medium import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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 ch.sbb.compose_mds.sbbicons.MediumGroup public val MediumGroup.SeatAisleReservationMedium: ImageVector get() { if (_seatAisleReservationMedium != null) { return _seatAisleReservationMedium!! } _seatAisleReservationMedium = Builder(name = "SeatAisleReservationMedium", defaultWidth = 36.0.dp, defaultHeight = 36.0.dp, viewportWidth = 36.0f, viewportHeight = 36.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(10.25f, 10.5f) arcToRelative(1.75f, 1.75f, 0.0f, true, true, 3.5f, 0.0f) arcToRelative(1.75f, 1.75f, 0.0f, false, true, -3.5f, 0.0f) moveTo(12.0f, 7.75f) arcToRelative(2.75f, 2.75f, 0.0f, true, false, 0.0f, 5.5f) arcToRelative(2.75f, 2.75f, 0.0f, false, false, 0.0f, -5.5f) moveToRelative(-5.72f, 5.17f) lineToRelative(6.0f, 16.5f) lineToRelative(0.12f, 0.33f) lineTo(24.0f, 29.75f) verticalLineToRelative(-1.0f) lineTo(13.1f, 28.75f) lineTo(7.22f, 12.58f) close() moveTo(13.965f, 15.25f) horizontalLineToRelative(-0.015f) curveToRelative(-1.334f, 0.01f, -2.233f, 1.328f, -1.791f, 2.572f) verticalLineToRelative(0.004f) lineToRelative(3.12f, 8.595f) lineToRelative(0.12f, 0.329f) horizontalLineToRelative(9.186f) curveToRelative(0.365f, 0.0f, 0.711f, 0.206f, 0.882f, 0.538f) lineToRelative(2.575f, 5.912f) lineToRelative(0.916f, -0.4f) lineToRelative(-2.58f, -5.925f) lineToRelative(-0.005f, -0.012f) lineToRelative(-0.006f, -0.012f) arcToRelative(2.0f, 2.0f, 0.0f, false, false, -1.782f, -1.101f) horizontalLineToRelative(-1.168f) lineToRelative(-5.75f, -4.312f) lineToRelative(-1.84f, -4.889f) verticalLineToRelative(-0.003f) arcToRelative(2.01f, 2.01f, 0.0f, false, false, -1.862f, -1.296f) moveToRelative(-0.008f, 1.0f) arcToRelative(0.92f, 0.92f, 0.0f, false, false, -0.856f, 1.236f) verticalLineToRelative(0.002f) lineToRelative(3.0f, 8.262f) horizontalLineToRelative(5.649f) lineToRelative(-4.8f, -3.6f) lineToRelative(-0.117f, -0.087f) lineToRelative(-0.051f, -0.137f) lineToRelative(-1.89f, -5.023f) arcToRelative(1.01f, 1.01f, 0.0f, false, false, -0.934f, -0.653f) } } .build() return _seatAisleReservationMedium!! } private var _seatAisleReservationMedium: ImageVector? = null
0
Kotlin
0
1
090a66a40e1e5a44d4da6209659287a68cae835d
3,631
mds-android-compose
MIT License
aboutlibraries/src/main/java/com/mikepenz/aboutlibraries/ui/LibsSupportFragment.kt
mikepenz
19,025,014
false
null
package com.mikepenz.aboutlibraries.ui import android.os.Bundle import android.util.Log import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Filter import android.widget.Filterable import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.lifecycleScope import androidx.lifecycle.whenStarted import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.mikepenz.aboutlibraries.Libs import com.mikepenz.aboutlibraries.LibsBuilder import com.mikepenz.aboutlibraries.LibsConfiguration import com.mikepenz.aboutlibraries.R import com.mikepenz.aboutlibraries.ui.item.LibraryItem import com.mikepenz.aboutlibraries.ui.item.SimpleLibraryItem import com.mikepenz.aboutlibraries.util.doOnApplySystemWindowInsets import com.mikepenz.aboutlibraries.util.withContext import com.mikepenz.aboutlibraries.viewmodel.LibsViewModel import com.mikepenz.aboutlibraries.viewmodel.LibsViewModelFactory import com.mikepenz.fastadapter.FastAdapter import com.mikepenz.fastadapter.GenericItem import com.mikepenz.fastadapter.adapters.ItemAdapter import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * [Fragment] listing the libraries used by this project. * * Retrieves the [LibsBuilder] via the 'data' passed as argument. */ open class LibsSupportFragment : Fragment(), Filterable { private val itemAdapter: ItemAdapter<GenericItem> = ItemAdapter() private val adapter: FastAdapter<GenericItem> = FastAdapter.with(itemAdapter) private val viewModel by activityViewModels<LibsViewModel> { LibsViewModelFactory( requireContext().applicationContext, arguments?.getSerializable("data") as? LibsBuilder ?: run { Log.i("AboutLibraries", "Fallback to default configuration, due to missing argument") LibsBuilder() }, Libs.Builder().withContext(requireContext()) ) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { var view = inflater.inflate(R.layout.fragment_opensource, container, false) //allows to modify the view before creating view = LibsConfiguration.uiListener?.preOnCreateView(view) ?: view // init CardView val recyclerView: RecyclerView = if (view.id == R.id.cardListView) { view as RecyclerView } else { view.findViewById(R.id.cardListView) as RecyclerView } recyclerView.layoutManager = LinearLayoutManager(context) recyclerView.itemAnimator = LibsConfiguration.itemAnimator ?: DefaultItemAnimator() recyclerView.adapter = adapter //allows to modify the view after creating view = LibsConfiguration.uiListener?.postOnCreateView(view) ?: view recyclerView.doOnApplySystemWindowInsets(Gravity.BOTTOM, Gravity.START, Gravity.END) itemAdapter.itemFilter.filterPredicate = fun(item, constraint): Boolean { // Don't do any filtering if constraint is null/blank if (constraint.isNullOrBlank()) { return true } return when (item) { is LibraryItem -> item.library.name.contains(constraint, ignoreCase = true) is SimpleLibraryItem -> item.library.name.contains(constraint, ignoreCase = true) else -> false } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.whenStarted { withContext(Dispatchers.Main) { viewModel.listItems.flowOn(Dispatchers.Main).collect { itemAdapter.set(it) } } } } return view } override fun getFilter(): Filter = itemAdapter.itemFilter }
6
null
419
3,604
e8a4fe3aa5b963205c986d1e0f768ca96ede3c86
4,118
AboutLibraries
Apache License 2.0
src/main/kotlin/org/imyuyu/idea/plugins/filesync/ui/config/ConfigPanel.kt
imyuyu
495,438,091
false
{"Kotlin": 164280}
package org.imyuyu.idea.plugins.filesync.ui.config import com.intellij.ide.plugins.PluginManagerCore import com.intellij.openapi.extensions.PluginId import com.intellij.openapi.project.Project import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.ui.components.JBTabbedPane import org.imyuyu.idea.plugins.filesync.FileSyncPlugin import org.imyuyu.idea.plugins.filesync.model.Config import org.imyuyu.idea.plugins.filesync.utils.ConfigPathsManager import org.imyuyu.idea.plugins.filesync.ui.config.panes.GeneralPane import org.imyuyu.idea.plugins.filesync.ui.config.panes.IConfigPane import org.imyuyu.idea.plugins.filesync.ui.config.panes.LogPane import org.imyuyu.idea.plugins.filesync.ui.config.panes.TargetsPane import java.awt.BorderLayout import java.awt.Component import java.util.* import javax.swing.JButton import javax.swing.JPanel /** * Configuration panel */ class ConfigPanel(plugin: FileSyncPlugin) : JPanel() { val currentProject: Project private val configPanes: Array<IConfigPane> init { configPanes = arrayOf( TargetsPane(plugin.pathManager), GeneralPane(plugin.project, plugin.pathManager), LogPane() ) buildUI(plugin.pathManager) currentProject = plugin.project } fun isModified(config: Config): Boolean { for (configPane in configPanes) { if (configPane.isModified(config)) { return true } } return false } fun reset(config: Config) { for (configPane in configPanes) { configPane.reset(config) } } fun apply(config: Config) { for (configPane in configPanes) { configPane.apply(config) } } private fun buildUI(pathsManager: ConfigPathsManager) { val pnHeader = createHeaderPanel() val mainPane = JBTabbedPane() for (configPane in configPanes) { configPane.buildUI(pathsManager) mainPane.addTab(configPane.title, configPane as Component) } layout = BorderLayout() add(pnHeader, BorderLayout.NORTH) add(mainPane, BorderLayout.CENTER) } private fun createHeaderPanel(): JPanel { val pnImportExport: JPanel = JBPanel<JBPanel<*>>() pnImportExport.add(JButton(ActionsHolder.ImportAction(this))) pnImportExport.add(JButton(ActionsHolder.ExportAction(this))) val panel = JPanel(BorderLayout()) panel.add(pnImportExport, BorderLayout.CENTER) panel.add( JBLabel( "version " + Objects.requireNonNull(PluginManagerCore.getPlugin(PluginId.getId(FileSyncPlugin.PLUGIN_NAME)))?.version ), BorderLayout.EAST ) return panel } }
0
Kotlin
0
0
167b23f3850fdd6d4831b38a71af154b95767c8b
2,855
FileSyncPlugin
MIT License
api/src/main/kotlin/org/jetbrains/kotlinx/dl/api/core/layer/reshaping/AbstractUpSampling.kt
JetBrains
249,948,572
false
null
/* * Copyright 2021-2022 JetBrains s.r.o. and Kotlin Deep Learning project contributors. All Rights Reserved. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.kotlinx.dl.api.core.layer.reshaping import org.jetbrains.kotlinx.dl.api.core.layer.Layer import org.tensorflow.Operand import org.tensorflow.op.Ops /** * Abstract UpSampling layer used as the base layer for all the upsampling layers. * * @property [sizeInternal] UpSampling size factors; currently, they are not used in the implementation * of this abstract class and each subclassed layer uses its own copy of the upsampling size factors. * @property [interpolationInternal] Interpolation method used for filling values (only applicable to 2D data * for the moment). */ public abstract class AbstractUpSampling( public val sizeInternal: IntArray, public val interpolationInternal: InterpolationMethod, name: String, ) : Layer(name) { override val hasActivation: Boolean get() = false override fun build(tf: Ops, input: Operand<Float>, isTraining: Operand<Boolean>, numberOfLosses: Operand<Float>? ): Operand<Float> { return upSample(tf, input) } /** * The actual implementation of upsampling operation which each subclassed layer needs to * implement. This method will then be called from [build] method to upsample the input tensor. */ protected abstract fun upSample(tf: Ops, input: Operand<Float>): Operand<Float> } /** * Repeat elements of a given tensor [value] for [repeats] times along the given [axis]. * * For example, if the given tensor is equal to `[1, 2, 3]`, `repeats=2` and `axis=0`, * the output of this function would be `[1, 1, 2, 2, 3, 3]`. */ internal fun repeat(tf: Ops, value: Operand<Float>, repeats: Int, axis: Int): Operand<Float> { val inputShape = value.asOutput().shape() val splits = tf.split(tf.constant(axis), value, inputShape.size(axis)) val multiples = tf.constant( IntArray(inputShape.numDimensions()) { if (it == axis) repeats else 1 } ) val repeated = splits.map { tf.tile(it, multiples) } // The following check is due to the fact that `tf.concat` raises an error // if only one tensor is given as its input. if (repeated.size == 1) return repeated[0] return tf.concat(repeated, tf.constant(axis)) } /** * Type of interpolation method. */ public enum class InterpolationMethod(internal val methodName: String) { /** * Nearest neighbor interpolation. * See: [https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation] */ NEAREST("nearest"), /** * Bilinear interpolation. * See: [https://en.wikipedia.org/wiki/Bilinear_interpolation] */ BILINEAR("bilinear"), /** * Bicubic interpolation. * See: [https://en.wikipedia.org/wiki/Bicubic_interpolation] */ BICUBIC("bicubic"), }
81
Kotlin
79
806
efaa1ebdf7bf9a131826d3ded42e1eb178e4fd19
3,040
KotlinDL
Apache License 2.0
feature/system/src/main/java/io/github/droidkaigi/confsched2020/system/ui/viewmodel/SystemViewModel.kt
DroidKaigi
202,978,106
false
null
package io.github.droidkaigi.confsched2020.system.ui.viewmodel import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.provider.CalendarContract import androidx.core.app.ShareCompat import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import com.soywiz.klock.DateTime import io.github.droidkaigi.confsched2020.ext.toNonNullSingleEvent import io.github.droidkaigi.confsched2020.model.AppError import io.github.droidkaigi.confsched2020.model.AppError.ExternalIntegrationError.NoCalendarIntegrationFoundException import timber.log.Timber import timber.log.debug import javax.inject.Inject class SystemViewModel @Inject constructor() : ViewModel() { private val mutableErrorLiveData = MutableLiveData<AppError?>() val errorLiveData: LiveData<AppError> get() = mutableErrorLiveData.toNonNullSingleEvent() fun onError(error: AppError) { mutableErrorLiveData.value = error } fun sendEventToCalendar( activity: Activity, title: String, location: String, startDateTime: DateTime, endDateTime: DateTime ) { val intent = Intent(Intent.ACTION_INSERT) .setData(CalendarContract.Events.CONTENT_URI) .putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, startDateTime.unixMillisLong) .putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endDateTime.unixMillisLong) .putExtra(CalendarContract.Events.TITLE, "[$location] $title") .putExtra(CalendarContract.Events.EVENT_LOCATION, location) try { activity.startActivity(intent) } catch (e: ActivityNotFoundException) { Timber.debug(e) { "Fail startActivity" } onError(NoCalendarIntegrationFoundException(e)) } } fun shareURL( activity: Activity, url: String ) { try { ShareCompat.IntentBuilder.from(activity) .setText(url) .setType("text/plain") .startChooser() } catch (e: Exception) { Timber.debug(e) { "Fail startActivity" } } } fun navigateToAccessMap(activity: Activity) { val intent = Intent( Intent.ACTION_VIEW, Uri.parse("geo:35.6219252,139.7190626?q=TOCビル") ) if (intent.resolveActivity(activity.packageManager) != null) { activity.startActivity(intent) } } }
46
null
331
785
4c5533e4611d4bf6007284dd1f61db2fc92eb0ae
2,552
conference-app-2020
Apache License 2.0
app/src/main/java/com/gaurav/budgetplanner/features/expensetracker/presentation/Adapters/RecordAdapter.kt
gaurav822
631,181,621
false
null
package com.gaurav.budgetplanner.features.expensetracker.presentation.Adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.gaurav.budgetplanner.R import com.gaurav.budgetplanner.Utils.Utils import com.gaurav.budgetplanner.Views.Components.IconMapper import com.gaurav.budgetplanner.databinding.ItemEachRecordBinding import com.gaurav.budgetplanner.features.expensetracker.domain.model.Account import com.gaurav.budgetplanner.features.expensetracker.domain.util.TransactionType class RecordAdapter(private val currency:String): RecyclerView.Adapter<RecordAdapter.MyViewHolder>() { private var allRecords = emptyList<Account>() private var sum:Int = 0 var onItemClick : ((Account) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val view = ItemEachRecordBinding.inflate(LayoutInflater.from(parent.context), parent, false) return MyViewHolder(view) } override fun getItemCount(): Int { return allRecords.size } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: MyViewHolder, position: Int) { val eachItem = allRecords[position] holder.binding.categoryTitle.text = eachItem.category holder.binding.tvCurrencySymbol.text =currency holder.binding.tvAmount.text = eachItem.amount Glide.with(holder.binding.categoryTitle.context) .asBitmap() .load(IconMapper.getIconByName(eachItem.category)) .into(holder.binding.imgCategory) holder.binding.tvPercent.text = Utils.calculatePercentage(allRecords.map { it.amount.toInt() }.toList(),position).toString() + "%" holder.itemView.setOnClickListener { onItemClick?.invoke(eachItem) } } class MyViewHolder(b:ItemEachRecordBinding): RecyclerView.ViewHolder(b.root){ var binding: ItemEachRecordBinding = b } @SuppressLint("NotifyDataSetChanged") fun updateList(data:List<Account>){ sum = 0 this.allRecords = data for(i in data){ sum+= i.amount.toInt() } notifyDataSetChanged() } }
0
Kotlin
0
0
0c4e874bb3eb80ffc9054fe105d8d594fdec627f
2,329
Budget-Planner
MIT License
responses/src/commonMain/kotlin/ru/krindra/vkkt/responses/ads/AdsGetUploadURLResponse.kt
krindra
780,080,411
false
{"Kotlin": 1336107}
package ru.krindra.vkkt.responses.ads import ru.krindra.vkkt.objects.ads.* typealias AdsGetUploadURLResponse = String
0
Kotlin
0
1
58407ea02fc9d971f86702f3b822b33df65dd3be
120
VKKT
MIT License
app/src/main/java/com/android_algo/presentation/randomwalk/RandomWalkViewModel.kt
julianczaja
399,513,595
false
null
package com.android_algo.presentation.randomwalk import androidx.lifecycle.ViewModel class RandomWalkViewModel : ViewModel() { // TODO: Implement the ViewModel }
0
Kotlin
1
1
de94518a3eb4440d56779c5106c669feb0a26167
167
android_algo
MIT License
kevs-rabbitmq/src/jvmMain/kotlin/io/kevs/station/rabbitmq/subscriber/EventSubscriberSpecification.kt
MikiLoz92
502,142,453
false
null
package io.kevs.station.rabbitmq.subscriber import kotlin.reflect.KClass /** * A class that is populated with all relevant information of an [EventSubscriber] in order for you to provide other * relevant elements that are required for Kevs to function. */ data class EventSubscriberSpecification( val clazz: KClass<out EventSubscriber<*>>, val consumerCount: Int, )
0
Kotlin
0
0
861b0e117c6af98311983d6623882534ff32cebd
379
kevs
MIT License
app/app/src/main/java/com/example/genshin_wiki/repository/dungeon_resource/DungeonResourceNetworkRepository.kt
SlavaPerryAyeKruchkovenko
600,055,723
false
null
package com.example.genshin_wiki.repository.dungeon_resource import com.example.genshin_wiki.data.responses.DungeonResourceListResponse import com.example.genshin_wiki.networks.RetrofitBuilder import com.example.genshin_wiki.networks.repositories.IDungeonResourceNetworkRepository import retrofit2.Response class DungeonResourceNetworkRepository : IDungeonResourceNetworkRepository { override suspend fun getResources(dayOfWeek: String): Response<DungeonResourceListResponse> { return RetrofitBuilder.resourceApi.getResources(dayOfWeek) } }
0
Kotlin
0
0
644286da5dbd69b586ff8761e75ad80ede7a0cdf
558
Genshin_Wiki
MIT License
library/src/main/java/com/magical/location/MagicalLocationManager.kt
raedev
558,713,495
false
{"Kotlin": 59040}
package com.magical.location import android.annotation.SuppressLint import android.content.Context import android.location.Location import android.location.LocationManager import com.magical.location.LocationPermission.isPermissionGranted import com.magical.location.internal.Log /** * 位置信息上下文 * @author RAE * @date 2022/10/28 * @copyright Copyright (c) https://github.com/raedev All rights reserved. */ @Suppress("MemberVisibilityCanBePrivate") object MagicalLocationManager { /** 位置广播Action,查看[LocationBroadcastReceiver] */ internal const val ACTION_LOCATION_CHANGED: String = "com.magical.location.ACTION_LOCATION_CHANGED" /** 位置广播位置信息,查看[LocationBroadcastReceiver] */ internal const val EXTRA_LOCATION: String = "EXTRA_LOCATION" /** 是否开启调试,默认False */ var debug: Boolean = BuildConfig.DEBUG set(value) { field = value Log.debug = value } /** 当前应用程序最后一次的位置信息 */ var location: Location? = null internal set /** 当前位置配置项 */ val options: LocationOptions = LocationOptions() /** * 获取最后一次位置信息 */ @SuppressLint("MissingPermission") fun getLastLocation(context: Context): Location? { val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager if (!isPermissionGranted(context)) return null // 根据时间来获取最新的位置 val locations = mutableListOf(this.location) locations.add(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)) locations.add(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)) locations.add(locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)) var result: Location? = null locations.forEach { val item = it ?: return@forEach if (result == null) result = item if (item.time > result!!.time) result = item } return result } }
1
Kotlin
0
2
ad3b54f7959dd1253da00990b02b08d332d94ee3
1,971
magical-location-client
Apache License 2.0
shared/src/commonTest/kotlin/com/inspiredandroid/braincup/Tests.kt
SimonSchubert
189,719,690
false
null
package com.inspiredandroid.braincup import com.inspiredandroid.braincup.api.UserStorage import com.inspiredandroid.braincup.games.* import com.inspiredandroid.braincup.games.tools.Calculator import kotlin.test.Test import kotlin.test.assertEquals class Tests { @Test fun calculator() { assertEquals(3.0, Calculator.calculate("1+2")) assertEquals(3.9f, Calculator.calculate("1.5+2.4").toFloat()) assertEquals(3.0, Calculator.calculate("2--1")) assertEquals(-1.0, Calculator.calculate("-2+1")) assertEquals(-30.0, Calculator.calculate("20-50")) assertEquals(25.0, Calculator.calculate("(1+2)*5+12-4/(10/5)")) assertEquals(2.0, Calculator.calculate("2*(10-(5+4))")) assertEquals(4.0, Calculator.calculate(" 2 + 2 ")) assertEquals(4.0, Calculator.calculate("2+( 2 )")) assertEquals(0.0, Calculator.calculate("2+(")) assertEquals(0.0, Calculator.calculate("2+)")) assertEquals(0.0, Calculator.calculate("2+)(")) assertEquals(0.0, Calculator.calculate("2+())")) assertEquals(0.0, Calculator.calculate("2+(()")) assertEquals(0.0, Calculator.calculate("&#1-5@")) } @Test fun extensionFunctions() { assertEquals("", " ".removeWhitespaces()) assertEquals("123", " 1 2 3 ".removeWhitespaces()) assertEquals("Hello Kotlin World!", "Hello World!".addString(" Kotlin", 5)) assertEquals("121", "11".addString("2", 1)) } @Test fun storage() { val storage = UserStorage() storage.putScore(GameType.CHAIN_CALCULATION.getId(), 99) // assertEquals(99, storage.getHighScore(GameType.CHAIN_CALCULATION.getId())) } @Test fun fractionCalculation() { val game = FractionCalculationGame() game.nextRound() assertEquals(game.solution(), Calculator.calculate(game.calculation).toInt().toString()) } @Test fun chainCalculation() { val game = ChainCalculationGame() game.nextRound() assertEquals(game.solution(), Calculator.calculate(game.calculation).toInt().toString()) } @Test fun mentalCalculation() { val game = MentalCalculationGame() game.nextRound() assertEquals(game.solution(), Calculator.calculate(game.calculation).toInt().toString()) } @Test fun heightComparison() { val game = HeightComparisonGame() game.nextRound() var highestResult = -1 var highestIndex = -1 game.answers.forEachIndexed { index, s -> if(Calculator.calculate(s) > highestResult) { highestIndex = index+1 highestResult = Calculator.calculate(s).toInt() } } assertEquals(game.solution(), highestIndex.toString()) } @Test fun colorConfusion() { val game = ColorConfusionGame() game.nextRound() var points = 0 if(game.answerShape == game.displayedShape) { points += game.shapePoints } if(game.answerColor == game.displayedColor) { points += game.colorPoints } assertEquals(game.points(), points.toString()) } @Test fun sherlockCalculation() { val game = SherlockCalculationGame() game.nextRound() } }
2
null
7
145
2339863e22d95744dcd74fc7a3b5997e392ec1b3
3,338
Braincup
Apache License 2.0
backend/src/test/kotlin/ch/uzh/ifi/seal/DTOs/ScheduleDTOTest.kt
sealuzh
112,313,865
false
null
package ch.uzh.ifi.seal.DTOs import ch.uzh.ifi.seal.business_logic.findOverlappingEvents import ch.uzh.ifi.seal.domain_classes.* import org.junit.Assert.assertEquals import org.junit.Test import org.optaplanner.core.api.score.buildin.hardsoft.HardSoftScore import java.time.LocalDate import java.time.LocalTime /** * Testing the creation of the DTO for the schedule in a proper way */ class ScheduleDTOTest { @Test fun ScheduleToDTO() { // prepare val today = LocalDate.now() val schedule = Schedule(today, LocalTime.of(9, 0), LocalTime.of(19, 0)) schedule.calendarEvents = mutableListOf(newEvent(today, "10:00", "11:00"), newEvent(today, "12:40", "13:00"), newEvent(today, "15:00", "18:00")) val task = Task("something", 30, TaskDifficulty.REGULAR, TaskImportance.MEDIUM, User()) .apply { id = 1 } val assignedTask = AssignedTask(LocalTime.NOON, task) schedule.assignedTasks = mutableListOf(assignedTask) schedule.score = HardSoftScore.valueOf(0, 100) // do val dto = schedule.toDTO() val taskDto = assignedTask.toDTO() // verify assertEquals(LocalTime.parse("09:00"), dto.startOfDay) assertEquals(LocalTime.parse("19:00"), dto.endOfDay) assertEquals(0, dto.hardScore) assertEquals(100, dto.softScore) assertEquals(assignedTask, schedule.assignedTasks.first()) assertEquals(taskDto.id, dto.tasks.first().id) } private fun newEvent(today: LocalDate, from: String, to: String) = CalendarEvent("id", today, LocalTime.parse(from), "", LocalTime.parse(to), User()) @Test fun `transform assigned tasks overlapping with events to TaskDTO`() { // prepare val events = listOf(event(9, 15, 10, 0), event(10, 30, 11, 0), event(15, 0, 16, 15)) val shortTask = task(15) val mediumTask = task(90) val longTask = task(120) val assignedTasks = listOf(AssignedTask(LocalTime.parse("09:00"), shortTask), AssignedTask(LocalTime.parse("10:00"), mediumTask), AssignedTask(LocalTime.parse("14:15"), longTask)) // do val dtoList = dtoNotOverlappingWithEvents(assignedTasks, events) println(findOverlappingEvents(assignedTask = AssignedTask(LocalTime.parse("09:00"), shortTask), events = events)) dtoList.forEach { println(it) } // verify assert(dtoList.size == 5) assert(dtoList.find { it.id == 90 && it.startingTime.toString() == "10:00"} != null) assert(dtoList.find { it.id == 120 && it.startingTime.toString() == "16:15"} != null) // no tasks scheduled when event starts assert(dtoList.find { it.startingTime.toString() == "09:15"} == null) assert(dtoList.find { it.startingTime.toString() == "10:30"} == null) assert(dtoList.find { it.startingTime.toString() == "15:00"} == null) } private fun task(duration: Int) = Task("", duration, TaskDifficulty.REGULAR, TaskImportance.LOW, User()).apply { id = duration } private fun event(startHour: Int, startMin: Int, endHour: Int, endMin: Int) = CalendarEvent(null, LocalTime.of(startHour, startMin), LocalTime.of(endHour, endMin), "") }
0
Kotlin
1
5
43c949b8d12c75edd72b4f055ba36cd025d5f6ff
3,235
DayO
MIT License
src/main/kotlin/csense/idea/base/bll/kotlin/KtThrowExpression.kt
csense-oss
226,373,994
false
{"Kotlin": 152974}
@file:Suppress("unused") package csense.idea.base.bll.kotlin import csense.idea.base.bll.psiWrapper.`class`.* import csense.idea.base.bll.psiWrapper.`class`.operations.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.types.* fun KtThrowExpression.resolveThrownTypeOrNull(): KtPsiClass? { return tryResolveViaExpressionType() ?: this.thrownExpression?.resolveFirstClassType2() ?: KtPsiClass.getKotlinThrowable(project) ?: KtPsiClass.getJavaThrowable(project) } fun KtThrowExpression.tryResolveViaExpressionType(): KtPsiClass? { val resolvedExpressionType: KotlinType = thrownExpression?.resolveExpressionType() ?: return null val fqName: String = resolvedExpressionType.fqNameAsString() ?: return null return KtPsiClass.resolveByKotlin(fqName = fqName, project = project) ?: KtPsiClass.resolveByJava(fqName = fqName, project = project) }
0
Kotlin
0
0
f819f9497145d10e25e015fe9db4634a7c73798c
905
idea-kotlin-shared-base
MIT License
src/main/kotlin/us/jwf/aoc2017/Day04Passphrases.kt
jasonwyatt
318,073,137
false
null
package us.jwf.aoc2017 import java.io.Reader import us.jwf.aoc.Day /** * AoC 2017 - Day 4 */ class Day04Passphrases : Day<Int, Int> { override suspend fun executePart1(input: Reader): Int { return input.readLines().count { it.noDuplicates() } } override suspend fun executePart2(input: Reader): Int { return input.readLines().count { it.noAnagrams() } } fun String.noDuplicates(): Boolean { return !split("\\s+".toRegex()) .asSequence() .runningFold(mutableMapOf<String, Int>()) { map, word -> map[word] = (map[word] ?: 0) + 1 map } .any { it.values.any { v -> v > 1 } } } fun String.noAnagrams(): Boolean { return !split("\\s+".toRegex()) .asSequence() .map { it.toCharArray().sorted().toString() } .runningFold(mutableMapOf<String, Int>()) { map, word -> map[word] = (map[word] ?: 0) + 1 map } .any { it.values.any { v -> v > 1 } } } }
0
Kotlin
0
0
0c92a62ba324aaa1f21d70b0f9f5d1a2c52e6868
963
AdventOfCode-Kotlin
Apache License 2.0
dokka-runners/dokka-gradle-plugin/src/main/kotlin/formats/DokkaPublication.kt
Kotlin
21,763,603
false
{"Kotlin": 4076594, "CSS": 63880, "JavaScript": 39656, "TypeScript": 16774, "SCSS": 8881, "HTML": 6860, "FreeMarker": 4120, "Shell": 3948, "Java": 1147}
/* * Copyright 2014-2024 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.dokka.gradle.formats import org.gradle.api.Named import org.gradle.api.file.ConfigurableFileCollection import org.gradle.api.file.DirectoryProperty import org.gradle.api.plugins.ExtensionAware import org.gradle.api.provider.Property import org.jetbrains.dokka.gradle.internal.DokkaInternalApi import org.jetbrains.dokka.gradle.internal.DokkaPluginParametersContainer import org.jetbrains.dokka.gradle.internal.adding import java.io.Serializable import javax.inject.Inject /** * A [DokkaPublication] controls the output running the Dokka Generator. * * The output format (for example, HTML) is determined by the Dokka Plugins that are present. * * Each Dokka Publication has its own set of Gradle tasks and [org.gradle.api.artifacts.Configuration]s. */ abstract class DokkaPublication @DokkaInternalApi @Inject constructor( val formatName: String, /** * Configurations for Dokka Generator Plugins. Must be provided from * [org.jetbrains.dokka.gradle.DokkaExtension.pluginsConfiguration]. */ pluginsConfiguration: DokkaPluginParametersContainer, ) : Named, Serializable, ExtensionAware { /** Configurations for Dokka Generator Plugins. */ val pluginsConfiguration: DokkaPluginParametersContainer = extensions.adding("pluginsConfiguration", pluginsConfiguration) override fun getName(): String = formatName abstract val enabled: Property<Boolean> abstract val moduleName: Property<String> abstract val moduleVersion: Property<String> /** Output directory for the finished Dokka publication. */ abstract val outputDirectory: DirectoryProperty abstract val cacheRoot: DirectoryProperty abstract val offlineMode: Property<Boolean> abstract val failOnWarning: Property<Boolean> abstract val suppressObviousFunctions: Property<Boolean> abstract val includes: ConfigurableFileCollection abstract val suppressInheritedMembers: Property<Boolean> // TODO probably not needed any more, since Dokka Generator now runs in an isolated JVM process abstract val finalizeCoroutines: Property<Boolean> /** Output directory for the partial Dokka module. */ internal abstract val moduleOutputDirectory: DirectoryProperty }
671
Kotlin
409
3,434
ec28b78ee5b137ee989cd0203ef108b2a2ac4811
2,363
dokka
Apache License 2.0
app/src/main/java/com/codepath/apps/twitterclone/ScrollAwareFABBehavior.kt
quocannguyen
470,449,852
false
{"Kotlin": 64385}
package com.codepath.apps.twitterclone import android.content.Context import android.util.AttributeSet import android.view.View import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.core.view.ViewCompat import com.google.android.material.floatingactionbutton.FloatingActionButton import com.google.android.material.floatingactionbutton.FloatingActionButton.OnVisibilityChangedListener class ScrollAwareFABBehavior(context: Context, attributeSet: AttributeSet) : FloatingActionButton.Behavior(context, attributeSet) { override fun onStartNestedScroll( coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, directTargetChild: View, target: View, axes: Int, type: Int ): Boolean { // return (axes == ViewCompat.SCROLL_AXIS_VERTICAL) || // super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type) return super.onStartNestedScroll(coordinatorLayout, child, directTargetChild, target, axes, type) } override fun onNestedScroll( coordinatorLayout: CoordinatorLayout, child: FloatingActionButton, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int, dyUnconsumed: Int, type: Int, consumed: IntArray ) { super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type, consumed) // if (dyConsumed > 0 && child.visibility == View.VISIBLE) { // child.hide(object : OnVisibilityChangedListener() { // override fun onHidden(floatingActionButon: FloatingActionButton) { // super.onHidden(floatingActionButon) // floatingActionButon.visibility = View.INVISIBLE // } // }) // } else if (dyConsumed < 0 && child.visibility != View.VISIBLE) { // child.show() // } } }
1
Kotlin
0
0
f6585274130d18d0b710225e9a4a5c2fdd946aaf
1,992
TwitterClone_RestClientTemplate
Apache License 2.0
app/src/main/java/uk/nhs/nhsx/sonar/android/app/registration/TokenRetriever.kt
nhsx
261,523,644
false
null
/* * Copyright © 2020 NHSX. All rights reserved. */ package uk.nhs.nhsx.sonar.android.app.registration import com.google.firebase.iid.FirebaseInstanceId import timber.log.Timber import javax.inject.Inject import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine typealias Token = String interface TokenRetriever { suspend fun retrieveToken(): Token } class FirebaseTokenRetriever @Inject constructor() : TokenRetriever { override suspend fun retrieveToken(): Token = suspendCoroutine { cont -> FirebaseInstanceId.getInstance().instanceId .addOnCompleteListener { task -> try { if (!task.isSuccessful) { Timber.w(task.exception, "getInstanceId failed") cont.resumeWithException( task.exception ?: RuntimeException("Cannot retrieve Firebase Id") ) return@addOnCompleteListener } val token = task.result?.token!! cont.resume(token) } catch (exception: Exception) { // Can fail even if the status isSuccessful // https://stackoverflow.com/questions/60698622/java-io-ioexception-fis-auth-error-in-android-firebase Timber.w(exception, "getInstanceId failed") cont.resumeWithException(exception) } } } }
0
Kotlin
146
793
ebcb3221b89333d9f555592aebc934d06608d784
1,630
COVID-19-app-Android-BETA
MIT License
core-starter/src/main/kotlin/com/labijie/application/localization/LocalizationMessageSource.kt
hongque-pro
309,874,586
false
{"Kotlin": 1044723, "Java": 72766}
package com.labijie.application.localization import com.labijie.application.service.ILocalizationService import org.slf4j.LoggerFactory import org.springframework.context.* import org.springframework.context.support.MessageSourceAccessor import java.util.* /** * @author Anders Xiao * @date 2023-12-06 */ class LocalizationMessageSource(private val loader: ResourceBundleMessagesLoader) : MessageSource, ApplicationContextAware { companion object { private val logger = LoggerFactory.getLogger(LocalizationMessageSource::class.java) } private lateinit var applicationContext: ApplicationContext private var localizationService: ILocalizationService? = null fun preloadMessages(vararg locales: Locale) { localizationService?.let { svc-> locales.forEach { val properties = loader.loadAllMessages(it) svc.setMessages(properties, it) } } } fun loadResourceBundle(vararg paths: String) { val set = loader.basenameSet set.addAll(paths) } private fun Collection<MessageSource>.getMessage(code: String, locale: Locale): String? { this.forEach { val msg = it.getMessage(code, null, null, locale) if(msg != null){ return@getMessage msg } } return null } override fun getMessage(code: String, args: Array<out Any>?, defaultMessage: String?, locale: Locale): String? { val svc = this.localizationService ?: return defaultMessage var msg = svc.getMessage(code, locale) if(msg == null) { msg = (loader as MessageSource).getMessage(code, null, defaultMessage, locale) svc.setMessage(code, msg ?: "", locale, false) logger.info("New localization message added: $code (${locale.toLanguageTag()})") } if(msg == null) { return null } return if (args.isNullOrEmpty()) msg else String.format(msg, *args) } override fun getMessage(code: String, args: Array<out Any>?, locale: Locale): String { return getMessage(code, args, null, locale) ?: throw NoSuchMessageException(code, locale) } override fun getMessage(resolvable: MessageSourceResolvable, locale: Locale): String { val args = resolvable.arguments resolvable.codes?.forEach { val msg = getMessage(it, args, null, locale) if(!msg.isNullOrBlank()){ return@getMessage msg } } return resolvable.defaultMessage ?: throw NoSuchMessageException(resolvable.codes?.firstOrNull() ?: "", locale) } override fun setApplicationContext(applicationContext: ApplicationContext) { this.applicationContext = applicationContext this.localizationService = applicationContext.getBeanProvider(ILocalizationService::class.java).ifAvailable } }
0
Kotlin
0
8
33a2bdacbd3012343f51617ecfccd096e403db5f
2,940
application-framework
Apache License 2.0
shared/src/jvmMain/kotlin/com/prof18/feedflow/shared/domain/opml/OpmlOutput.kt
prof18
600,257,020
false
{"Kotlin": 746513, "HTML": 182777, "Swift": 163455, "SCSS": 161629, "CSS": 16810, "Shell": 2392, "JavaScript": 1214}
package com.prof18.feedflow.shared.domain.opml import java.io.File actual data class OpmlOutput( val file: File, )
27
Kotlin
18
332
60c15c24c157e46625e05158c5d048d4ca4b7217
121
feed-flow
Apache License 2.0
snapshots/sample/app/src/main/kotlin/com/emergetools/snapshots/sample/MainActivity.kt
EmergeTools
645,957,551
false
{"Kotlin": 255570}
package com.emergetools.snapshots.sample import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.Column import com.emergetools.snapshots.sample.ui.Greeting import com.emergetools.snapshots.sample.ui.TextRowWithIcon class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Column { Greeting("Snapshots sample") TextRowWithIcon( titleText = "TextRow title", subtitleText = "TextRow subtitle" ) } } } }
3
Kotlin
1
9
8174b9c6e2d7791e01363aabd4d287736bfa38c4
661
emerge-android
Apache License 2.0
appholder/src/androidTest/java/com/android/mdl/app/selfsigned/SelfSignedScreenStateTest.kt
openwallet-foundation-labs
248,844,077
false
null
package com.android.mdl.app.selfsigned import androidx.lifecycle.SavedStateHandle import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.platform.app.InstrumentationRegistry import com.android.identity.android.securearea.AndroidKeystoreSecureArea import com.android.identity.android.storage.AndroidStorageEngine import com.android.identity.securearea.SecureAreaRepository import com.android.identity.securearea.SoftwareSecureArea import com.android.identity.wallet.document.DocumentColor import com.android.identity.wallet.document.DocumentType import com.android.identity.wallet.selfsigned.AddSelfSignedScreenState import com.android.identity.wallet.selfsigned.AddSelfSignedViewModel import com.android.identity.wallet.util.PreferencesHelper import com.android.identity.wallet.util.ProvisioningUtil import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class SelfSignedScreenStateTest { private val savedStateHandle = SavedStateHandle() private lateinit var repository: SecureAreaRepository @Before fun setUp() { val context = InstrumentationRegistry.getInstrumentation().targetContext repository = ProvisioningUtil.getInstance(context).secureAreaRepository val storageDir = PreferencesHelper.getKeystoreBackedStorageLocation(context) val storageEngine = AndroidStorageEngine.Builder(context, storageDir).build() val androidKeystoreSecureArea = AndroidKeystoreSecureArea(context, storageEngine) val softwareSecureArea = SoftwareSecureArea(storageEngine) repository.addImplementation(androidKeystoreSecureArea) repository.addImplementation(softwareSecureArea) } @Test fun defaultScreenState() { val viewModel = AddSelfSignedViewModel(savedStateHandle) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState()) } @Test fun updateDocumentType() { val personalId = DocumentType.EUPID val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateDocumentType(personalId) assertThat(viewModel.screenState.value).isEqualTo( AddSelfSignedScreenState(documentType = personalId, documentName = "EU Personal ID") ) } @Test fun updateDocumentName() { val newName = ":irrelevant:" val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateDocumentName(newName) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState(documentName = newName)) } @Test fun updateDocumentTypeAfterNameUpdate() { val registration = DocumentType.MVR val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateDocumentName(":irrelevant:") viewModel.updateDocumentType(registration) assertThat(viewModel.screenState.value).isEqualTo( AddSelfSignedScreenState( documentType = registration, documentName = "Vehicle Registration" ) ) } @Test fun updateCardArt() { val blue = DocumentColor.Blue val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateCardArt(blue) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState(cardArt = blue)) } @Test fun updateValidityInDays() { val newValue = 15 val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateValidityInDays(newValue) assertThat(viewModel.screenState.value.validityInDays) .isEqualTo(newValue) } @Test fun updateValidityInDaysBelowMinValidityDays() { val defaultMinValidity = 10 val belowMinValidity = 9 val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateValidityInDays(defaultMinValidity) viewModel.updateValidityInDays(belowMinValidity) assertThat(viewModel.screenState.value.validityInDays) .isEqualTo(defaultMinValidity) } @Test fun updateMinValidityInDays() { val newMinValidity = 15 val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateMinValidityInDays(newMinValidity) assertThat(viewModel.screenState.value.minValidityInDays) .isEqualTo(newMinValidity) } @Test fun updateMinValidityInDaysAboveValidityInDays() { val defaultValidityInDays = 30 val minValidityInDays = defaultValidityInDays + 5 val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateMinValidityInDays(minValidityInDays) assertThat(viewModel.screenState.value.validityInDays) .isEqualTo(minValidityInDays) } @Test fun updateNumberOfMso() { val msoCount = 2 val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateNumberOfMso(msoCount) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState(numberOfMso = msoCount)) } @Test fun updateNumberOfMsoInvalidValue() { val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateNumberOfMso(1) viewModel.updateNumberOfMso(0) viewModel.updateNumberOfMso(-1) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState(numberOfMso = 1)) } @Test fun updateMaxUseOfMso() { val maxMsoUsages = 3 val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateMaxUseOfMso(maxMsoUsages) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState(maxUseOfMso = maxMsoUsages)) } @Test fun updateMaxUseOfMsoInvalidValue() { val viewModel = AddSelfSignedViewModel(savedStateHandle) viewModel.updateMaxUseOfMso(1) viewModel.updateMaxUseOfMso(0) viewModel.updateMaxUseOfMso(-1) assertThat(viewModel.screenState.value) .isEqualTo(AddSelfSignedScreenState(maxUseOfMso = 1)) } }
99
null
83
163
e6bf25766985521b9a39d4ed7999f22d57064db5
6,249
identity-credential
Apache License 2.0
app/src/main/java/com/masterplus/trdictionary/features/category/presentation/components/SubCategoryItem.kt
Ramazan713
634,957,286
false
{"Kotlin": 833205}
package com.masterplus.trdictionary.features.category.presentation.components import androidx.annotation.DrawableRes import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.masterplus.trdictionary.R @Composable fun SubCategoryItem( title: String, @DrawableRes resourceId: Int, onClicked: ()->Unit, modifier: Modifier = Modifier, margins: PaddingValues = PaddingValues(vertical = 8.dp), paddings: PaddingValues = PaddingValues(vertical = 16.dp, horizontal = 12.dp) ){ val shape = MaterialTheme.shapes.medium Card( modifier .padding(margins) .clip(shape) .clickable { onClicked() }, shape = shape, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.secondaryContainer ), border = BorderStroke(1.dp,MaterialTheme.colorScheme.outlineVariant) ) { Row( modifier = modifier .padding(paddings), verticalAlignment = Alignment.CenterVertically ){ Icon( painter = painterResource(resourceId), contentDescription = title, modifier = Modifier.size(40.dp) ) Text( title, modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyLarge ) } } } @Preview(showBackground = true) @Composable fun SubCategoryItemPreview() { SubCategoryItem( title = "testX", onClicked = {}, resourceId = R.drawable.ic_baseline_all_inclusive_24 ) }
0
Kotlin
0
1
c60dfcf2d238fec26918b89e65d5f5075d2d3b68
2,697
Turkce-ve-Osmanlica-Sozluk
Apache License 2.0
widgets-ktx/src/main/java/com/corphish/widgets/ktx/dialogs/MessageAlertDialog.kt
corphish
230,289,421
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 8, "Proguard": 2, "XML": 35, "JSON": 1, "Java": 1, "Kotlin": 25, "INI": 1}
/* * * Copyright (C) 2020 <NAME> <<EMAIL>> * * 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.corphish.widgets.ktx.dialogs import android.content.Context import android.content.res.ColorStateList import android.graphics.Color import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.core.content.res.ResourcesCompat import androidx.core.widget.doOnTextChanged import com.corphish.widgets.ktx.R import com.google.android.material.button.MaterialButton import com.google.android.material.textfield.TextInputEditText import com.google.android.material.textfield.TextInputLayout class EditTextAlertDialog(context: Context) : BaseAlertDialog(context) { /** * Title of this dialog. */ var titleString = "" @StringRes var titleResId = 0 /** * Message of this dialog. */ var messageString = "" @StringRes var messageResId = 0 /** * Positive button handling. */ var positiveButtonProperties = ButtonProperties() /** * Negative button handling. */ var negativeButtonProperties = ButtonProperties() /** * Neutral button handling. */ var neutralButtonProperties = ButtonProperties() /** * Edit text handler */ var editTextInitialText = "" var editTextHandling: (TextInputLayout, CharSequence?, Int, Int, Int) -> Unit = { _, _, _, _, _ -> } override fun show() { // Inflate specific view val view = LayoutInflater.from(context).inflate(R.layout.layout_alert_edit_text, null) // Hook views val title = view.findViewById<TextView>(R.id.alertTitle) val message = view.findViewById<TextView>(R.id.alertMessage) val positiveButton = view.findViewById<MaterialButton>(R.id.positiveButton) val negativeButton = view.findViewById<MaterialButton>(R.id.negativeButton) val neutralButton = view.findViewById<MaterialButton>(R.id.neutralButton) val editTextLayout = view.findViewById<TextInputLayout>(R.id.editTextLayout) val editText = view.findViewById<TextInputEditText>(R.id.editText) if (titleResId == 0) { title.text = titleString } else { title.setText(titleResId) } if (messageResId == 0) { message.text = messageString } else { message.setText(messageResId) } if (positiveButtonProperties.buttonTitle.isNotEmpty() || positiveButtonProperties.buttonTitleResId != 0) { positiveButton.visibility = View.VISIBLE if (positiveButtonProperties.buttonTitleResId == 0) { positiveButton.text = positiveButtonProperties.buttonTitle } else { positiveButton.setText(positiveButtonProperties.buttonTitleResId) } positiveButton.setOnClickListener { positiveButtonProperties.buttonAction(editTextLayout, editText.editableText.toString()) if (positiveButtonProperties.dismissDialogOnButtonClick) { dismissDialog() } } if (positiveButtonProperties.buttonIcon != 0) { positiveButton.setIconResource(positiveButtonProperties.buttonIcon) } if (positiveButtonProperties.useCustomButtonColor) { val color = getButtonColorFromProperty(positiveButtonProperties) positiveButton.setBackgroundColor(color) } } if (negativeButtonProperties.buttonTitle.isNotEmpty() || negativeButtonProperties.buttonTitleResId != 0) { negativeButton.visibility = View.VISIBLE if (negativeButtonProperties.buttonTitleResId == 0) { negativeButton.text = negativeButtonProperties.buttonTitle } else { negativeButton.setText(negativeButtonProperties.buttonTitleResId) } negativeButton.setOnClickListener { negativeButtonProperties.buttonAction(editTextLayout, editText.editableText.toString()) if (negativeButtonProperties.dismissDialogOnButtonClick) { dismissDialog() } } if (negativeButtonProperties.buttonIcon != 0) { negativeButton.setIconResource(negativeButtonProperties.buttonIcon) } if (negativeButtonProperties.useCustomButtonColor) { val color = getButtonColorFromProperty(negativeButtonProperties) negativeButton.strokeColor = ColorStateList.valueOf(color) negativeButton.setTextColor(color) negativeButton.iconTint = ColorStateList.valueOf(color) } } if (neutralButtonProperties.buttonTitle.isNotEmpty() || neutralButtonProperties.buttonTitleResId != 0) { neutralButton.visibility = View.VISIBLE if (neutralButtonProperties.buttonTitleResId == 0) { neutralButton.text = neutralButtonProperties.buttonTitle } else { neutralButton.setText(neutralButtonProperties.buttonTitleResId) } neutralButton.setOnClickListener { neutralButtonProperties.buttonAction(editTextLayout, editText.editableText.toString()) if (neutralButtonProperties.dismissDialogOnButtonClick) { dismissDialog() } } if (neutralButtonProperties.buttonIcon != 0) { neutralButton.setIconResource(neutralButtonProperties.buttonIcon) } if (neutralButtonProperties.useCustomButtonColor) { val color = getButtonColorFromProperty(neutralButtonProperties) neutralButton.setBackgroundColor(color) } } if (editTextInitialText.isNotEmpty()) { editText.setText(editTextInitialText) } editText.doOnTextChanged { text, start, before, count -> editTextHandling(editTextLayout, text, start, before, count) } super.contentView = view super.show() } /** * Gets button color from button properties. * * @param buttonProperties Button Properties. */ private fun getButtonColorFromProperty(buttonProperties: ButtonProperties) = if (buttonProperties.buttonColorResId == 0) { if (buttonProperties.buttonColor == Int.MIN_VALUE) { Color.parseColor(buttonProperties.buttonColorHex) } else { buttonProperties.buttonColor } } else { ResourcesCompat.getColor(context.resources, buttonProperties.buttonColorResId, context.theme) } /** * Button properties data class. */ data class ButtonProperties( /** * Button title. */ val buttonTitle: String = "", /** * Button title resource id. * This preferred over string. */ @StringRes val buttonTitleResId: Int = 0, /** * Action to be performed when this button is clicked. */ val buttonAction: (TextInputLayout, String) -> Unit = { _, _ -> }, /** * Behavior which defines whether dialog is dismissed * when this button is clicked. */ val dismissDialogOnButtonClick: Boolean = false, /** * Button icon. */ @DrawableRes val buttonIcon: Int = 0, /** * Boolean indicating whether custom button color * must be used or not. */ val useCustomButtonColor: Boolean = false, /** * Color resource id for button color. * This preferred over the rest 2 color properties. */ @ColorRes val buttonColorResId: Int = 0, /** * Color integer value for button color. * This is preferred over hex value. */ @ColorInt val buttonColor: Int = Int.MIN_VALUE, /** * Button ccc hex value. */ val buttonColorHex: String = "#000000" ) }
0
Kotlin
1
0
f1aebd6e7a71709ed12f07d9f65565ddcbbb5426
8,877
widgets-ktx
Apache License 2.0
app/src/main/java/dev/patrickgold/florisboard/setup/SetupActivity.kt
hamedsj
373,000,589
false
null
package dev.patrickgold.florisboard.setup import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import android.view.inputmethod.InputMethodManager import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.viewpager2.adapter.FragmentStateAdapter import dev.patrickgold.florisboard.R import dev.patrickgold.florisboard.databinding.SetupActivityBinding import dev.patrickgold.florisboard.ime.core.PrefHelper import dev.patrickgold.florisboard.settings.SettingsMainActivity class SetupActivity : AppCompatActivity() { companion object { const val EXTRA_SHOW_SINGLE_STEP = "EXTRA_SHOW_SINGLE_STEP" } private lateinit var adapter: ViewPagerAdapter private lateinit var binding: SetupActivityBinding lateinit var imm: InputMethodManager lateinit var prefs: PrefHelper private var shouldFinish: Boolean = false private var shouldLaunchSettings: Boolean = true override fun onCreate(savedInstanceState: Bundle?) { prefs = PrefHelper(this) prefs.initDefaultPreferences() imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager val mode = when (prefs.advanced.settingsTheme) { "light" -> AppCompatDelegate.MODE_NIGHT_NO "dark" -> AppCompatDelegate.MODE_NIGHT_YES "auto" -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM else -> AppCompatDelegate.MODE_NIGHT_UNSPECIFIED } AppCompatDelegate.setDefaultNightMode(mode) super.onCreate(savedInstanceState) binding = SetupActivityBinding.inflate(layoutInflater) setContentView(binding.root) // NOTE: using findViewById() instead of view binding because the binding does not include // a reference to the included layout... val toolbar = findViewById<Toolbar>(R.id.toolbar) setSupportActionBar(toolbar) adapter = ViewPagerAdapter(this) adapter.addFragment(WelcomeFragment(), resources.getString(R.string.setup__welcome__title)) adapter.addFragment(EnableImeFragment(), resources.getString(R.string.setup__enable_ime__title)) adapter.addFragment(MakeDefaultFragment(), resources.getString(R.string.setup__make_default__title)) adapter.addFragment(FinishFragment(), resources.getString(R.string.setup__finish__title)) binding.viewPager.isUserInputEnabled = false binding.viewPager.adapter = adapter binding.progressBar.max = adapter.itemCount - 1 binding.prevButton.setOnClickListener { loadPage(binding.viewPager.currentItem - 1) } binding.cancelButton.setOnClickListener { finish() } binding.nextButton.setOnClickListener { loadPage(binding.viewPager.currentItem + 1) } binding.finishButton.setOnClickListener { prefs.internal.isImeSetUp = true launchSettingsAndSetFinishFlag() } binding.okButton.setOnClickListener { finish() } val extraShowSingleStep = intent.getIntExtra(EXTRA_SHOW_SINGLE_STEP, -1) if (extraShowSingleStep >= 0) { shouldLaunchSettings = false loadPage(extraShowSingleStep, true) } else { loadPage(Step.WELCOME) } } override fun onResume() { super.onResume() if (shouldFinish) { if (!isFinishing) { finish() } return } if (prefs.internal.isImeSetUp && shouldLaunchSettings) { launchSettingsAndSetFinishFlag() } } override fun onWindowFocusChanged(hasFocus: Boolean) { val fragment = adapter.createFragment(binding.viewPager.currentItem) if (fragment is EventListener) { fragment.onWindowFocusChanged(hasFocus) } } private fun launchSettingsAndSetFinishFlag() { Intent(this, SettingsMainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED or Intent.FLAG_ACTIVITY_CLEAR_TOP startActivity(this) } shouldFinish = true } private fun loadPage(pageIndex: Int, isSingleStepOnly: Boolean = false) { binding.prevButton.isEnabled = pageIndex > 0 && !isSingleStepOnly binding.cancelButton.isEnabled = isSingleStepOnly binding.progressBar.progress = pageIndex binding.progressBar.visibility = if (isSingleStepOnly) { View.INVISIBLE } else { View.VISIBLE } val isLast = pageIndex + 1 == adapter.itemCount binding.negativeButtonViewFlipper.displayedChild = if (isSingleStepOnly) { 1 } else { 0 } binding.positiveButtonViewFlipper.displayedChild = if (isSingleStepOnly) { 2 } else { if (isLast) { 1 } else { 0 } } changePositiveButtonState(false) supportActionBar?.title = adapter.getPageTitle(pageIndex) binding.viewPager.currentItem = pageIndex } fun changePositiveButtonState(enabled: Boolean) { binding.nextButton.isEnabled = enabled binding.finishButton.isEnabled = enabled binding.okButton.isEnabled = enabled } object Step { const val WELCOME = 0 const val ENABLE_IME = 1 const val MAKE_DEFAULT = 2 const val FINISH = 3 } interface EventListener { fun onWindowFocusChanged(hasFocus: Boolean) {} } private class ViewPagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) { private val fragments: MutableList<Fragment> = mutableListOf() private val titles: MutableList<String> = mutableListOf() override fun getItemCount(): Int { return fragments.size } fun addFragment(fragment: Fragment, title: String) { fragments.add(fragment) titles.add(title) } override fun createFragment(position: Int): Fragment { return fragments[position] } fun getPageTitle(position: Int): CharSequence? { return titles[position] } } }
0
null
0
1
671ff1d8b40f631aa68af30f47348608593fe891
6,365
florisboard
Apache License 2.0
src/commonMain/kotlin/effect/CountdownText.kt
VANTAGAMES
665,892,334
false
null
package effect import State import korlibs.io.async.* import korlibs.io.lang.* import korlibs.korge.view.* import korlibs.math.interpolation.* import korlibs.time.* fun State.countdownText() { val count = 4 (1..count).forEach { num -> txtWithFilter(if (num == count) "시작!" else " ${count - num} ") { alpha = 1f visible = false showUpThis( this, startCode = { launchImmediately(currentCoroutineContext) { hitSound.play() } }, startTime = ((num).seconds) * bpmToSec - initialNote.seconds*bpmToSec + max(0.seconds, offsetToSec.seconds), period = bpmToSec.seconds/3 ) { hideIt(this, period = bpmToSec.seconds/3) { removeFromParent() } } } } } fun State.hideIt(view: View, period: TimeSpan = 0.7.seconds, easing: Easing = Easing.EASE_OUT, ay: Double = 100.0 * period.seconds, callback: () -> Unit): Cancellable { view.run { val originY = pos.y var elapsed = 0.seconds zIndex = 10f lateinit var listener: Cancellable listener = onEvent(UpdateEvent) { if (isPaused) return@onEvent elapsed += it.deltaTime if (elapsed >= period) { visible = false listener.cancel() callback() } else { val i = (elapsed / period) alpha = 1 - kotlin.math.min(1f, kotlin.math.max(0f, easing.invoke(i))) positionY(originY + (1 - alpha) * ay) } } return listener } } fun State.showUpThis( view: View, startCode: () -> Unit = {}, startTime: TimeSpan = 0.seconds, period: TimeSpan = 0.7.seconds, easing: Easing = Easing.EASE_IN, isUp: Boolean = false, callback: () -> Unit, ): CloseableCancellable = view.run { val originY = pos.y zIndex = 10f var listener: CloseableCancellable? = null var span = 0.seconds var isStarted = false val code: (TimeSpan) -> Unit = code@{ if (isPaused) return@code span += it if (startTime > span) return@code if (!isStarted) { isStarted = true startCode.invoke() } if (span >= period) { callback() listener?.cancel() } else { var i = (span / period) if (!isUp) i = 1 - i alpha = 1 - kotlin.math.min(1f, kotlin.math.max(0f, easing.invoke(i))) positionY(originY - (1 - alpha) * 100*period.seconds) } if (!visible) visible = true } listener = onEvent(UpdateEvent) { if (isPaused) return@onEvent code(it.deltaTime) } code(0.seconds) return listener }
6
Kotlin
0
3
e9d5ee444646f99d43e25474d296c3393744ae17
2,927
metronKt
MIT License
feature/premieres/src/main/java/tech/dalapenko/premieres/di/PremieresModule.kt
dalapenko
739,864,810
false
{"Kotlin": 55397}
package tech.dalapenko.premieres.di import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ViewModelComponent import tech.dalapenko.premieres.model.repository.PremiereRepository import tech.dalapenko.premieres.model.repository.PremiereRepositoryImpl @Module @InstallIn(ViewModelComponent::class) interface PremieresModule { @Binds fun bindPremiereRepository(repository: PremiereRepositoryImpl): PremiereRepository }
0
Kotlin
0
0
db9e1fbb158681aabccfe9315ed63dfe7b73a20c
479
kinosearch
Apache License 2.0
aoc-2022/src/main/kotlin/aoc/aoc14.kts
triathematician
576,590,518
false
null
import aoc.AocParser.Companion.parselines import aoc.AocRunner import aoc.util.Coord import aoc.print val day = 14 val testInput = """ 498,4 -> 498,6 -> 496,6 503,4 -> 502,4 -> 502,9 -> 494,9 """.parselines.map { it.split("->").map { it.trim().split(",").let { it[0].toInt() to it[1].toInt() } }} val input = """ 502,19 -> 507,19 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 507,117 -> 521,117 -> 521,116 517,34 -> 522,34 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 503,34 -> 508,34 501,15 -> 506,15 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 513,113 -> 513,114 -> 527,114 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 530,150 -> 535,150 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 510,34 -> 515,34 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 524,34 -> 529,34 498,46 -> 502,46 510,46 -> 514,46 509,19 -> 514,19 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 497,13 -> 502,13 504,46 -> 508,46 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 507,43 -> 511,43 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 506,31 -> 511,31 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 507,117 -> 521,117 -> 521,116 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 534,152 -> 539,152 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 495,19 -> 500,19 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 527,152 -> 532,152 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 533,148 -> 538,148 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 516,46 -> 520,46 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 501,119 -> 501,120 -> 512,120 -> 512,119 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 512,25 -> 517,25 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 513,31 -> 518,31 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 520,31 -> 525,31 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 482,21 -> 482,22 -> 490,22 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 498,17 -> 503,17 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 513,43 -> 517,43 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 505,17 -> 510,17 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 509,28 -> 514,28 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 537,150 -> 542,150 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 501,43 -> 505,43 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 501,119 -> 501,120 -> 512,120 -> 512,119 507,37 -> 511,37 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 501,119 -> 501,120 -> 512,120 -> 512,119 510,40 -> 514,40 488,19 -> 493,19 482,21 -> 482,22 -> 490,22 494,15 -> 499,15 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 513,97 -> 513,89 -> 513,97 -> 515,97 -> 515,94 -> 515,97 -> 517,97 -> 517,94 -> 517,97 -> 519,97 -> 519,93 -> 519,97 -> 521,97 -> 521,88 -> 521,97 -> 523,97 -> 523,94 -> 523,97 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 504,40 -> 508,40 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 516,28 -> 521,28 545,155 -> 545,157 -> 541,157 -> 541,160 -> 556,160 -> 556,157 -> 550,157 -> 550,155 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 491,17 -> 496,17 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 526,133 -> 526,131 -> 526,133 -> 528,133 -> 528,129 -> 528,133 -> 530,133 -> 530,129 -> 530,133 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 497,72 -> 497,63 -> 497,72 -> 499,72 -> 499,65 -> 499,72 -> 501,72 -> 501,71 -> 501,72 -> 503,72 -> 503,67 -> 503,72 -> 505,72 -> 505,63 -> 505,72 -> 507,72 -> 507,71 -> 507,72 -> 509,72 -> 509,70 -> 509,72 -> 511,72 -> 511,69 -> 511,72 523,100 -> 523,104 -> 519,104 -> 519,111 -> 528,111 -> 528,104 -> 526,104 -> 526,100 513,113 -> 513,114 -> 527,114 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 510,75 -> 510,78 -> 505,78 -> 505,84 -> 518,84 -> 518,78 -> 515,78 -> 515,75 488,59 -> 488,51 -> 488,59 -> 490,59 -> 490,52 -> 490,59 -> 492,59 -> 492,55 -> 492,59 -> 494,59 -> 494,52 -> 494,59 -> 496,59 -> 496,50 -> 496,59 -> 498,59 -> 498,58 -> 498,59 -> 500,59 -> 500,56 -> 500,59 -> 502,59 -> 502,56 -> 502,59 -> 504,59 -> 504,57 -> 504,59 541,152 -> 546,152 523,136 -> 523,138 -> 518,138 -> 518,145 -> 535,145 -> 535,138 -> 528,138 -> 528,136 """.parselines.map { it.split("->").map { it.trim().split(",").let { it[0].toInt() to it[1].toInt() } }} // test case val tsandSource = 500 to 0 val trockGrid = testInput.toRockGrid(tsandSource) trockGrid.print trockGrid.pourSand() trockGrid.print val trockGrid2 = testInput.toRockGrid(tsandSource, floor = true) trockGrid2.print trockGrid2.pourSand() trockGrid2.print val testResult = trockGrid.count('o') val testResult2 = trockGrid2.count('o') fun List<List<Coord>>.toRockGrid(source: Coord, floor: Boolean = false): RockGrid { val minx = minOf { it.minOf { it.first }}.coerceAtMost(source.first) val miny = minOf { it.minOf { it.second }}.coerceAtMost(source.second) val maxx = maxOf { it.maxOf { it.first }}.coerceAtLeast(source.first) val maxy = maxOf { it.maxOf { it.second }}.coerceAtLeast(source.second) val grid = RockGrid(minx-1..maxx+1, miny-1..maxy+1, source, floor) forEach { path -> path.drop(1).forEachIndexed { i, pair -> val prev = path[i] if (prev.first == pair.first) { range(prev.second, pair.second).forEach { grid.rock(pair.first, it) } } else if (prev.second == pair.second) { range(prev.first, pair.first).forEach { grid.rock(it, pair.second) } } } } return grid } fun range(a: Int, b: Int) = if (a > b) b..a else a..b class RockGrid(xr: IntRange, yr: IntRange, val source: Coord, floor: Boolean) { var xvals: IntRange var yvals: IntRange init { if (floor) { yvals = yr.first..yr.last+1 val ht = yvals.last - yvals.first val minx = xr.first.coerceAtMost(source.first - ht) val maxx = xr.last.coerceAtLeast(source.first + ht) xvals = minx..maxx } else { xvals = xr yvals = yr } } val minx: Int = xvals.first val miny: Int = yvals.first val grid = yvals.map { xvals.map { '.' }.toMutableList() } init { grid[source.second-miny][source.first-minx] = '+' if (floor) { xvals.forEach { rock(it, yvals.last) } } } fun rock(x: Int, y: Int) { grid[y-miny][x-minx] = '#' } fun sand(x: Int, y: Int) { grid[y-miny][x-minx] = 'o' } fun count(c: Char) = grid.sumOf { it.count { it == c } } fun airat(x: Int, y: Int) = grid[y-miny][x-minx] in arrayOf('.','+') fun pourSand() { var res: Boolean do { res = pourGrainOfSand() // this.print } while (res) } fun pourGrainOfSand(from: Coord = source): Boolean { if (!airat(from.first, from.second)) return false // location of first rock or obstruction below val down = (from.second..yvals.last).firstOrNull { !airat(from.first, it) } ?: return false if (airat(from.first-1, down)) pourGrainOfSand(from.first-1 to down).let { if (!it) return false } else if (airat(from.first+1, down)) pourGrainOfSand(from.first+1 to down).let { if (!it) return false } else sand(from.first, down-1) return true } override fun toString() = grid.joinToString("\n") { String(it.toCharArray()) } } // part 1 val sandSource = 500 to 0 val rockGrid = input.toRockGrid(sandSource) rockGrid.pourSand() val answer1 = rockGrid.count('o') answer1.print // part 2 val rockGrid2 = input.toRockGrid(sandSource, floor = true) rockGrid2.pourSand() val answer2 = rockGrid2.count('o') answer2.print // print results AocRunner(day, info = { listOf("Leaderboard: 10:33/13:54", "Answers: 901/24589") }, test = { "$testResult, $testResult2" }, part1 = { answer1 }, part2 = { answer2 } ).run()
0
Kotlin
0
0
c9d7309132e592c18aacda08b47baa0bdfc08c87
23,512
advent-of-code
Apache License 2.0
app/src/main/java/com/waydroid/settings/fragments/SettingsFragment.kt
waydroid
419,857,449
false
{"Kotlin": 16891}
package com.waydroid.settings.fragments import android.annotation.SuppressLint import android.content.ComponentName import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.SeekBarPreference import androidx.preference.SwitchPreferenceCompat import com.waydroid.settings.R import java.lang.reflect.InvocationTargetException class SettingsFragment : PreferenceFragmentCompat() { override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.main_preference, rootKey) switch(findPreference<Preference>(getString(R.string.key_switch_multi_windows_mode)) as SwitchPreferenceCompat, PROPERTY_WD_MULTI_WINDOWS_KEY) switch(findPreference<Preference>(getString(R.string.key_switch_invert_colors)) as SwitchPreferenceCompat, PROPERTY_WD_INVERT_COLORS_KEY) switch(findPreference<Preference>(getString(R.string.key_switch_enable_never_sleep)) as SwitchPreferenceCompat, PROPERTY_WD_NEVER_SLEEP_KEY) seekBar(findPreference<Preference>(getString(R.string.key_seekbar_height_padding)) as SeekBarPreference, PROPERTY_WD_HEIGHT_PADDING_KEY) seekBar(findPreference<Preference>(getString(R.string.key_seekbar_width_padding)) as SeekBarPreference, PROPERTY_WD_WIDTH_PADDING_KEY) seekBar(findPreference<Preference>(getString(R.string.key_seekbar_display_width)) as SeekBarPreference, PROPERTY_WD_DISPLAY_WIDTH_KEY) seekBar(findPreference<Preference>(getString(R.string.key_seekbar_wd_width)) as SeekBarPreference, PROPERTY_WD_WIDTH_KEY) } private fun switch(switchPreferenceCompat: SwitchPreferenceCompat, property: String) { switchPreferenceCompat.apply { isChecked = getBooleanSystemProperties(property) onPreferenceClickListener = Preference.OnPreferenceClickListener { preference: Preference -> setProperty(property, (preference as SwitchPreferenceCompat) .isChecked.toString()) true } } } private fun seekBar(seekBarPreference: SeekBarPreference, property: String) { seekBarPreference.apply { value = getIntSystemProperties(property) onPreferenceChangeListener = Preference.OnPreferenceChangeListener { _, newValue -> setProperty(property, newValue.toString()) true } } } private fun enableWayDroidSystemUI(enable: Boolean) { Log.d(TAG, "enable WayDroid SystemUI $enable") setSystemProperties(PROPERTY_BD_SYSTEMUI_KEY, enable.toString()) val context: Context? = activity if (context != null) { val packageName = context.packageName val intent = Intent("com.android.systemui.action.RESTART") .setData(Uri.parse("package://$packageName")) val cn = ComponentName( "com.android.systemui", "com.android.systemui.SysuiRestartReceiver" ) intent.component = cn context.sendBroadcast(intent) } } private fun setProperty(mode: String, value: String) { Log.d(TAG, "$mode $value") setSystemProperties(mode, value) } private fun setSystemProperties(key: String, value: String) { try { @SuppressLint("PrivateApi") val clazz = Class.forName(SYSTEM_PROPERTIES_CLASS_NAME) val setMethod = clazz.getMethod("set", String::class.java, String::class.java) setMethod.invoke(null, key, value) } catch (e: ClassNotFoundException) { Log.d(TAG, "Failed to set value $value for $key") } catch (e: NoSuchMethodException) { Log.d(TAG, "Failed to set value $value for $key") } catch (e: IllegalAccessException) { Log.d(TAG, "Failed to set value $value for $key") } catch (e: InvocationTargetException) { Log.d(TAG, "Failed to set value $value for $key") } } private fun getBooleanSystemProperties(key: String): Boolean { try { @SuppressLint("PrivateApi") val clazz = Class.forName(SYSTEM_PROPERTIES_CLASS_NAME) val setMethod = clazz.getMethod( "getBoolean", String::class.java, Boolean::class.javaPrimitiveType ) return setMethod.invoke(null, key, true) as Boolean } catch (e: ClassNotFoundException) { Log.d(TAG, "Failed to get value for $key") } catch (e: NoSuchMethodException) { Log.d(TAG, "Failed to get value for $key") } catch (e: IllegalAccessException) { Log.d(TAG, "Failed to get value for $key") } catch (e: InvocationTargetException) { Log.d(TAG, "Failed to get value for $key") } return true } private fun getIntSystemProperties(key: String): Int { try { @SuppressLint("PrivateApi") val clazz = Class.forName(SYSTEM_PROPERTIES_CLASS_NAME) val setMethod = clazz.getMethod( "getInt", String::class.java, Int::class.javaPrimitiveType ) return setMethod.invoke(null, key, 0) as Int } catch (e: ClassNotFoundException) { Log.d(TAG, "Failed to get value for $key") } catch (e: NoSuchMethodException) { Log.d(TAG, "Failed to get value for $key") } catch (e: IllegalAccessException) { Log.d(TAG, "Failed to get value for $key") } catch (e: InvocationTargetException) { Log.d(TAG, "Failed to get value for $key") } return 0 } companion object { private const val TAG = "WDSettingsFragment" private const val SYSTEM_PROPERTIES_CLASS_NAME = "android.os.SystemProperties" private const val PROPERTY_BD_SYSTEMUI_KEY = "persist.sys.systemuiplugin.enabled" private const val PROPERTY_WD_MULTI_WINDOWS_KEY = "persist.waydroid.multi_windows" private const val PROPERTY_WD_INVERT_COLORS_KEY = "persist.waydroid.invert_colors" private const val PROPERTY_WD_HEIGHT_PADDING_KEY = "persist.waydroid.height_padding" private const val PROPERTY_WD_WIDTH_PADDING_KEY = "persist.waydroid.width_padding" private const val PROPERTY_WD_DISPLAY_WIDTH_KEY = "waydroid.display_width" private const val PROPERTY_WD_WIDTH_KEY = "persist.waydroid.width" private const val PROPERTY_WD_NEVER_SLEEP_KEY = "persist.waydroid.suspend" } }
0
Kotlin
2
1
778f3ef9c9f44f1b6811ed69f3b8c97f3069ddec
6,935
android_vendor_packages_apps_WaydroidSettings
Apache License 2.0
domain/src/main/java/com/tirgei/domain/models/Episode.kt
tirgei
362,710,268
false
null
package com.tirgei.domain.models /** * Model class for show episodes */ data class Episode( val id: Int, val name: String, val airDate: String, val episode: String, val url: String, val characters: List<Character> )
0
Kotlin
0
1
bcd982386c09c470da51c960ab38b4bdcc6a357f
243
rick-and-morty
The Unlicense
src/test/kotlin/org/motivepick/web/TaskListServiceImplIntegrationTest.kt
motivepick
143,636,614
false
{"Kotlin": 96083, "Dockerfile": 433}
package org.motivepick.web import com.github.springtestdbunit.annotation.DatabaseOperation.DELETE_ALL import com.github.springtestdbunit.annotation.DatabaseSetup import com.github.springtestdbunit.annotation.DatabaseTearDown import com.github.springtestdbunit.annotation.DbUnitConfiguration import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.motivepick.IntegrationTest import org.motivepick.domain.entity.TaskListType import org.motivepick.repository.TaskListRepository import org.motivepick.service.TaskListService import org.springframework.beans.factory.annotation.Autowired import org.springframework.security.core.context.SecurityContextHolder import org.springframework.test.context.junit.jupiter.SpringExtension import java.util.concurrent.CountDownLatch import kotlin.concurrent.thread @Disabled @ExtendWith(SpringExtension::class) @IntegrationTest(1234567890L) @DatabaseSetup("/dbunit/tasks.xml") @DatabaseTearDown("/dbunit/tasks.xml", type = DELETE_ALL) @DbUnitConfiguration(databaseConnection = ["dbUnitDatabaseConnection"]) class TaskListServiceImplIntegrationTest { @Autowired private lateinit var taskListRepository: TaskListRepository @Autowired private lateinit var instanceUnderTest: TaskListService @Test fun `should move task to same list be idempotent`() { val mainThreadSecurityContext = SecurityContextHolder.getContext() val latch = CountDownLatch(1) val thread0 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.moveTask(TaskListType.INBOX, 0, TaskListType.INBOX, 0, 0, latch) latch.countDown() } val thread1 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.moveTask(TaskListType.INBOX, 0, TaskListType.INBOX, 0, 1, latch) } thread0.join() thread1.join() val orderedIds = taskListRepository.findByUserAccountIdAndType(1234567890L.toString(), TaskListType.INBOX)!!.orderedIds assertThat(orderedIds).isEqualTo(listOf(2L)) } @Test fun `should move task to different list be idempotent`() { val mainThreadSecurityContext = SecurityContextHolder.getContext() val latch = CountDownLatch(1) val thread0 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.moveTask(TaskListType.INBOX, 0, TaskListType.CLOSED, 0, 0, latch) latch.countDown() } val thread1 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.moveTask(TaskListType.INBOX, 0, TaskListType.CLOSED, 0, 1, latch) } thread0.join() thread1.join() val orderedIds = taskListRepository.findByUserAccountIdAndType(1234567890L.toString(), TaskListType.CLOSED)!!.orderedIds assertThat(orderedIds).isEqualTo(listOf(2L, 3L)) } @Test fun `should close task be idempotent`() { val mainThreadSecurityContext = SecurityContextHolder.getContext() val latch = CountDownLatch(1) val thread0 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.closeTask(2, 0, latch) latch.countDown() } val thread1 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.closeTask(2, 1, latch) } thread0.join() thread1.join() val orderedIds = taskListRepository.findByUserAccountIdAndType(1234567890L.toString(), TaskListType.CLOSED)!!.orderedIds assertThat(orderedIds).isEqualTo(listOf(2L, 3L)) } @Test fun `should reopen task be idempotent`() { val mainThreadSecurityContext = SecurityContextHolder.getContext() val latch = CountDownLatch(1) val thread0 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.reopenTask(3, 0, latch) latch.countDown() } val thread1 = thread { SecurityContextHolder.setContext(mainThreadSecurityContext) instanceUnderTest.reopenTask(3, 1, latch) } thread0.join() thread1.join() val orderedIds = taskListRepository.findByUserAccountIdAndType(1234567890L.toString(), TaskListType.INBOX)!!.orderedIds assertThat(orderedIds).isEqualTo(listOf(3L, 2L)) } }
4
Kotlin
0
0
71d4214e21d2931b7753484784975fa84a3440e2
4,647
motive-back-end
MIT License
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/aps/CfnWorkspaceLoggingConfigurationPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.aps import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.aps.CfnWorkspace /** * The LoggingConfiguration attribute sets the logging configuration for the workspace. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.aps.*; * LoggingConfigurationProperty loggingConfigurationProperty = * LoggingConfigurationProperty.builder() * .logGroupArn("logGroupArn") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-aps-workspace-loggingconfiguration.html) */ @CdkDslMarker public class CfnWorkspaceLoggingConfigurationPropertyDsl { private val cdkBuilder: CfnWorkspace.LoggingConfigurationProperty.Builder = CfnWorkspace.LoggingConfigurationProperty.builder() /** * @param logGroupArn The Amazon Resource Name (ARN) of the CloudWatch log group the logs are * emitted to. */ public fun logGroupArn(logGroupArn: String) { cdkBuilder.logGroupArn(logGroupArn) } public fun build(): CfnWorkspace.LoggingConfigurationProperty = cdkBuilder.build() }
4
null
0
3
c59c6292cf08f0fc3280d61e7f8cff813a608a62
1,449
awscdk-dsl-kotlin
Apache License 2.0
Controls/src/commonMain/kotlin/io/nacular/doodle/controls/list/MutableList.kt
nacular
108,631,782
false
null
package io.nacular.doodle.controls.list import io.nacular.doodle.controls.EditOperation import io.nacular.doodle.controls.IndexedItem import io.nacular.doodle.controls.ItemVisualizer import io.nacular.doodle.controls.ListModel import io.nacular.doodle.controls.MutableListModel import io.nacular.doodle.controls.SelectionModel import io.nacular.doodle.controls.ViewVisualizer import io.nacular.doodle.controls.mutableListModelOf import io.nacular.doodle.core.View import io.nacular.doodle.utils.Editable import io.nacular.doodle.utils.PropertyObservers import io.nacular.doodle.utils.PropertyObserversImpl import io.nacular.doodle.utils.SortOrder import io.nacular.doodle.utils.SortOrder.Ascending import io.nacular.doodle.utils.SortOrder.Descending import io.nacular.doodle.utils.observable public interface ListEditor<T> { public fun edit(list: MutableList<T, *>, row: T, index: Int, current: View): EditOperation<T> } public inline fun <T> listEditor(crossinline block: (list: MutableList<T, *>, row: T, index: Int, current: View) -> EditOperation<T>): ListEditor<T> = object: ListEditor<T> { override fun edit(list: MutableList<T, *>, row: T, index: Int, current: View): EditOperation<T> = block(list, row, index, current) } /** * A [DynamicList] component that renders a mutable list of items of type [T] using a [ListBehavior]. Items are obtained via * the [model] and selection is managed via the optional [selectionModel]. Large ("infinite") lists are supported * efficiently, since List recycles the Views generated to render its rows. * * MutableList does not provide scrolling internally, so it should be embedded in a [ScrollPanel][io.nacular.doodle.controls.panels.ScrollPanel] or similar component if needed. * * @param model that holds the data for this List * @param itemVisualizer that maps [T] to [View] for each item in the List * @param selectionModel that manages the List's selection state * @param fitContent determines whether the List scales to fit it's rows width and total height * @param scrollCache determining how many "hidden" rows are rendered above and below the List's view-port. A value of 0 means * only visible rows are rendered, but quick scrolling is more likely to show blank areas. */ public open class MutableList<T, M: MutableListModel<T>>( model : M, itemVisualizer: ItemVisualizer<T, IndexedItem>? = null, selectionModel: SelectionModel<Int>? = null, fitContent : Boolean = true, scrollCache : Int = 10): DynamicList<T, M>(model, itemVisualizer, selectionModel, fitContent, scrollCache), Editable { /** * Indicates whether the list is currently being edited. */ public val editing: Boolean get() = editingRow != null /** * Controls whether and how the list can be edited. The list will not be editable without an editor specified. */ public var editor: ListEditor<T>? = null /** Notifies changes to [sortOrder] */ public val sortingChanged: PropertyObservers<MutableList<T, M>, SortOrder?> by lazy { PropertyObserversImpl<MutableList<T, M>, SortOrder?>(this) } /** current sorting for the list default is ```null```. */ public var sortOrder: SortOrder? by observable(null, sortingChanged as PropertyObserversImpl<MutableList<T, M>, SortOrder?>) private set private var editingRow = null as Int? set(new) { field = new?.also { selectionModel?.replaceAll(setOf(it)) } } private var editOperation = null as EditOperation<T>? /** * Sets the value at [index] in the underlying [model]. This will result in changes to the list as well if the * Model accepts the change. */ public operator fun set(index: Int, value: T) { if (value == model.set(index, value)) { // This is the case that the "new" value is the same as what was there // so need to explicitly update since the model won't fire a change update(children, index) } } public fun add (value : T ): Unit = model.add (value ) public fun add (index : Int, values: T ): Unit = model.add (index, values) public fun remove (value : T ): Unit = model.remove (value ) public fun removeAt (index : Int ): T? = model.removeAt (index ) public fun addAll (values: Collection<T> ): Unit = model.addAll (values ) public fun addAll (index : Int, values: Collection<T>): Unit = model.addAll (index, values) public fun removeAll(values: Collection<T> ): Unit = model.removeAll(values ) public fun retainAll(values: Collection<T> ): Unit = model.retainAll(values ) public fun clear ( ): Unit = model.clear() /** * Initiates editing of the list at the given [index]. This will cancel any other edit operation and * begin a new one if an [editor] is present. */ public fun startEditing(index: Int) { cancelEditing() editor?.let { model[index]?.let { row -> val i = index % children.size editingRow = index editOperation = it.edit(this, row, index, children[i]).also { it()?.let { children[i] = it } layout(children[i], row, index) } } } } /** * Indicates that editing is now complete. The current edit operation is terminated and its result is incorporated * into the list. */ public override fun completeEditing() { editOperation?.let { operation -> editingRow?.let { index -> val result = operation.complete() ?: return cleanupEditing() this[index] = result } } } /** * Cancels the current edit operation and discards its result. */ public override fun cancelEditing() { // FIXME: Cancel editing on selection/focus change cleanupEditing()?.let { update(children, it) } } /** * Sorts the list with the given comparator. This causes the underlying [model] to also be sorted. */ public fun sort(with: Comparator<T>) { model.sortWith(with) sortOrder = Ascending } /** * Sorts the list (descending) with the given comparator. This causes the underlying [model] to also be sorted. */ public fun sortDescending(with: Comparator<T>) { model.sortWithDescending(with) sortOrder = Descending } private fun cleanupEditing(): Int? { editOperation?.cancel() val result = editingRow editOperation = null editingRow = null return result } public companion object { public operator fun invoke( progression : IntProgression, itemVisualizer: ItemVisualizer<Int, IndexedItem>, selectionModel: SelectionModel<Int>? = null, fitContent : Boolean = true, scrollCache : Int = 10): MutableList<Int, MutableListModel<Int>> = MutableList(progression.toMutableList(), itemVisualizer, selectionModel, fitContent, scrollCache) public inline operator fun <reified T> invoke( values : kotlin.collections.List<T>, itemVisualizer: ItemVisualizer<T, IndexedItem>, selectionModel: SelectionModel<Int>? = null, fitContent : Boolean = true, scrollCache : Int = 10): MutableList<T, MutableListModel<T>> = MutableList(mutableListModelOf(*values.toTypedArray()), itemVisualizer, selectionModel, fitContent, scrollCache) public operator fun invoke( values : kotlin.collections.List<View>, selectionModel: SelectionModel<Int>? = null, fitContent : Boolean = true, scrollCache : Int = 10): List<View, ListModel<View>> = MutableList(mutableListModelOf(*values.toTypedArray()), ViewVisualizer, selectionModel, fitContent, scrollCache) public operator fun <T, M: MutableListModel<T>>invoke( model : M, itemVisualizer: ItemVisualizer<T, IndexedItem>? = null, selectionModel: SelectionModel<Int>? = null, fitContent : Boolean = true, scrollCache : Int = 10): MutableList<T, M> = MutableList(model, itemVisualizer, selectionModel, fitContent, scrollCache) } }
3
null
26
613
f7414d4c30cdd7632992071234223653e52b978c
8,962
doodle
MIT License
src/main/kotlin/org.domaintbn.sommd.core/musical/Duration.kt
user00e00
163,682,297
false
null
package org.domaintbn.sommd.core.musical class Duration(val mt: MusicTime, val isSilent: Boolean = false) { constructor(num: Int, den: Int, isSilent: Boolean) : this(MusicTime(num, den), isSilent) }
0
Kotlin
2
0
60c6784e53eb38894272f74616c9484019cc3ab4
203
sommd
MIT License
android/FindingFalcone/app/src/main/java/com/pradyotprakash/findingfalcone/app/pages/splash/view/SplachView.kt
pradyotprksh
385,586,594
false
{"Kotlin": 2932498, "Dart": 1066884, "Python": 319755, "Rust": 180589, "Swift": 149003, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354}
package com.pradyotprakash.findingfalcone.app.pages.splash.view import androidx.compose.animation.AnimatedVisibility import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.pradyotprakash.findingfalcone.app.localization.TR import com.pradyotprakash.findingfalcone.app.localization.Translation import com.pradyotprakash.findingfalcone.app.pages.splash.viewmodel.SplashViewModel import com.pradyotprakash.findingfalcone.app.utils.Assets @Composable fun SplashView( splashViewModel: SplashViewModel = hiltViewModel() ) { LaunchedEffect(true) { splashViewModel.startJourney() } Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize(), ) { AnimatedVisibility(visible = true) { Image( painter = painterResource(id = Assets.AppIcon.resourceId), contentDescription = Assets.AppIcon.imageDescription ) } Box(modifier = Modifier.height(10.dp)) Text( text = Translation.getString(TR.appName), style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.ExtraBold ) } }
0
Kotlin
11
24
a31e612a63e1dc42ed4cf2f50db90b8613fb5177
1,918
development_learning
MIT License
workflows/src/main/kotlin/com/r3/corda/lib/tokens/workflows/flows/evolvable/CreateEvolvableTokensFlow.kt
corda
160,397,060
false
{"Kotlin": 673352, "Java": 18696, "Dockerfile": 2031}
package com.r3.corda.lib.tokens.workflows.flows.evolvable import co.paralleluniverse.fibers.Suspendable import com.r3.corda.lib.tokens.contracts.states.EvolvableTokenType import com.r3.corda.lib.tokens.workflows.internal.flows.finality.ObserverAwareFinalityFlow import net.corda.core.contracts.TransactionState import net.corda.core.flows.CollectSignaturesFlow import net.corda.core.flows.FlowLogic import net.corda.core.flows.FlowSession import net.corda.core.identity.AbstractParty import net.corda.core.identity.Party import net.corda.core.serialization.CordaSerializable import net.corda.core.transactions.SignedTransaction import net.corda.core.transactions.TransactionBuilder /** * Inline sub-flow for creating multiple tokens of evolvable token type. This is just a simple flow for now. */ class CreateEvolvableTokensFlow @JvmOverloads constructor( val transactionStates: List<TransactionState<EvolvableTokenType>>, val participantSessions: List<FlowSession>, val observerSessions: List<FlowSession> = emptyList() ) : FlowLogic<SignedTransaction>() { @JvmOverloads constructor(transactionState: TransactionState<EvolvableTokenType>, participantSessions: List<FlowSession>, observerSessions: List<FlowSession> = emptyList()) : this(listOf(transactionState), participantSessions, observerSessions) @CordaSerializable data class Notification(val signatureRequired: Boolean = false) private val evolvableTokens = transactionStates.map { it.data } @Suspendable override fun call(): SignedTransaction { checkLinearIds(transactionStates) // TODO what about... preferred notary checkSameNotary() val transactionBuilder = TransactionBuilder(transactionStates.first().notary) // todo // Create a transaction which updates the ledger with the new evolvable tokens. transactionStates.forEach { addCreateEvolvableToken(transactionBuilder, it) } // Sign the transaction proposal val ptx: SignedTransaction = serviceHub.signInitialTransaction(transactionBuilder) // Gather signatures from other maintainers // Check that we have sessions with all maitainers but not with ourselves val otherMaintainerSessions = participantSessions.filter { it.counterparty in evolvableTokens.otherMaintainers(ourIdentity) } otherMaintainerSessions.forEach { it.send(Notification(signatureRequired = true)) } val stx = subFlow(CollectSignaturesFlow( partiallySignedTx = ptx, sessionsToCollectFrom = otherMaintainerSessions )) // Finalise with all participants, including maintainers, participants, and subscribers (via distribution list) val wellKnownObserverSessions = participantSessions.filter { it.counterparty in wellKnownObservers } val allObserverSessions = (wellKnownObserverSessions + observerSessions).toSet() allObserverSessions.forEach { it.send(Notification(signatureRequired = false)) } return subFlow(ObserverAwareFinalityFlow(signedTransaction = stx, allSessions = otherMaintainerSessions + allObserverSessions)) } private fun checkLinearIds(transactionStates: List<TransactionState<EvolvableTokenType>>) { check(transactionStates.map { it.data.linearId }.toSet().size == transactionStates.size) { "Shouldn't create evolvable tokens with the same linearId." } } private fun checkSameNotary() { check(transactionStates.map { it.notary }.toSet().size == 1) { "All states should have the same notary" } } // TODO Refactor it more. private val otherObservers get(): Set<AbstractParty> { return evolvableTokens.participants().minus(evolvableTokens.maintainers()).minus(this.ourIdentity) } private val wellKnownObservers get(): List<Party> { return otherObservers.map { serviceHub.identityService.wellKnownPartyFromAnonymous(it)!! } } }
38
Kotlin
77
80
749483f691c2c6ca56d9caacdd73a9e6319a969e
4,047
token-sdk
Apache License 2.0
HacoCmsClient/src/main/java/com/hacocms/sdk/response/ApiMetaResponse.kt
hacocms
560,726,757
false
{"Kotlin": 25808}
package com.hacocms.sdk.response data class ApiMetaResponse( val total: Int, val limit: Int, val offset: Int )
0
Kotlin
0
2
d67dd6bf021f3a38b8b8b531486ed938a948a47a
124
hacocms-jvm-sdk
MIT License
app/src/main/java/io/wookey/wallet/support/extensions/SharedPreferencesExt.kt
WooKeyWallet
176,637,569
false
null
package io.wookey.wallet.support.extensions import android.content.Context import android.content.SharedPreferences import io.wookey.wallet.App fun sharedPreferences(name: String = "default") = App.instance.getSharedPreferences(name, Context.MODE_PRIVATE) ?: throw IllegalStateException("SharedPreferences initialized failed") fun SharedPreferences.edit(action: SharedPreferences.Editor.() -> Unit) { edit().apply { action() }.apply() } fun SharedPreferences.putString(key: String, value: String) { edit { putString(key, value) } } fun SharedPreferences.putInt(key: String, value: Int) { edit { putInt(key, value) } } fun SharedPreferences.putBoolean(key: String, value: Boolean) { edit { putBoolean(key, value) } } fun SharedPreferences.putFloat(key: String, value: Float) { edit { putFloat(key, value) } } fun SharedPreferences.putLong(key: String, value: Long) { edit { putLong(key, value) } } fun SharedPreferences.putStringSet(key: String, value: Set<String>) { edit { putStringSet(key, value) } } fun SharedPreferences.remove(key: String) { edit { remove(key) } } fun SharedPreferences.clear() { edit { clear() } }
6
null
20
23
93d0d6a4743e95ab2455bb6ae24b2cc6b616bd90
1,187
monero-wallet-android-app
MIT License
app/src/main/java/com/ifanr/tangzhi/repository/baas/impl/BaasRepositoryImpl.kt
cyrushine
224,551,311
false
{"Kotlin": 673925, "Java": 59856, "Python": 795}
package com.ifanr.tangzhi.repository.baas.impl import android.content.Context import androidx.paging.PagedList import com.google.gson.reflect.TypeToken import com.ifanr.tangzhi.Const import com.ifanr.tangzhi.Event import com.ifanr.tangzhi.EventBus import com.ifanr.tangzhi.R import com.ifanr.tangzhi.exceptions.BaaSException import com.ifanr.tangzhi.exceptions.NeedSignInException import com.ifanr.tangzhi.exceptions.UniqueRuleException import com.ifanr.tangzhi.ext.* import com.ifanr.tangzhi.model.* import com.ifanr.tangzhi.repository.baas.BaasRepository import com.ifanr.tangzhi.repository.baas.SettingRepository import com.ifanr.tangzhi.repository.baas.Tables import com.ifanr.tangzhi.repository.baas.datasource.* import com.ifanr.tangzhi.ui.widgets.CommentSwitch import com.ifanr.tangzhi.util.AppGson import com.ifanr.tangzhi.util.uuid import com.minapp.android.sdk.BaaS import com.minapp.android.sdk.auth.Auth import com.minapp.android.sdk.auth.model.SignInByPhoneRequest import com.minapp.android.sdk.auth.model.UpdateUserReq import com.minapp.android.sdk.content.Contents import com.minapp.android.sdk.database.Record import com.minapp.android.sdk.database.query.Query import com.minapp.android.sdk.database.query.Where import com.minapp.android.sdk.storage.CloudFile import com.minapp.android.sdk.storage.Storage import io.reactivex.Completable import io.reactivex.Single import io.reactivex.schedulers.Schedulers import java.io.File import java.util.concurrent.TimeUnit import java.util.concurrent.locks.ReentrantLock import javax.inject.Inject class BaasRepositoryImpl @Inject constructor( private val bus: EventBus, private val ctx: Context, private val setting: SettingRepository ): BaasRepository { companion object { private const val TAG = "BaasRepositoryImpl" } // 标签颜色列表 private val productTagThemes = listOf( "#FDEDEC", "#F4ECF6", "#EBF5FA", "#E8F8F5", "#EAF7EF", "#FEF5E8", "#FBEEE7", "#F2F4F4", "#F9DBD9", "#E7DBEE", "#D6EAF7", "#D2F2EB", "#D5EEE0", "#FDEAD2", "#F6DDCE", "#E5E8E8", "#F7F5DD", "#ECE9D2", "#F9F1D4", "#F2EBE6", "#EFEFF5", "#EFF1EB", "#EFECF1", "#EDF4F8") override fun getContentById(id: String): Single<BaasContent> = Single.fromCallable { BaasContent(Contents.content(id)) } override fun getProductReviewCount(productId: String): Single<Long> = Single.fromCallable { var where = Where().apply { equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_TYPE, Comment.TYPE_REVIEW) } // 自己可以看到待审核的内容 if (signedIn()) { where = Where.and( where, Where.or( Where().apply { equalTo(Record.CREATED_BY, userId()?.toLong()) equalTo(Comment.COL_STATUS, BaseModel.STATUS_PENDING) }, Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } ) ) } else { where = Where.and( where, Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } ) } val query = Query().apply { put(where) } Tables.comment.count(query).toLong() } override fun reportComment(id: String): Completable = Completable.fromAction { assertSignIn() val resp = BaaS.invokeCloudFunc("reportComment", id, true) if (resp.code != 0) { val errMsg = runCatching { AppGson.toJson(resp.error) }.getOrNull() throw Exception("invoke baas cloud func fail, reportComment($id), $errMsg") } } override fun relatedProducts(ids: List<String>): Single<List<Product>> = Tables.product.query( clz = Product::class.java, page = -1, where = Where().apply { containedIn(Record.ID, ids) equalTo(Product.COL_STATUS, BaseModel.STATUS_APPROVED) equalTo(Product.COL_TYPE, Product.TYPE_HARDWARE) } ).map { it.data } override fun timelineList(): Single<PagedList<Timeline>> = Single.fromCallable { assertSignIn() pagedList(dataSource = TimelineDataSource(this)) } override fun followsList(): Single<PagedList<Product>> = Single.fromCallable { assertSignIn() pagedList(dataSource = FollowsDataSource(this)) } override fun systemMessageList(): Single<PagedList<Message>> = Single.fromCallable { assertSignIn() pagedList(dataSource = SystemMessageDataSource(this)) } override fun messageList(): Single<PagedList<Message>> = Single.fromCallable { assertSignIn() pagedList(dataSource = MessageDataSource(this)) } override fun verifySmsCode(phone: String, code: String): Completable = Completable.fromAction { if (!BaaS.verifySmsCode(phone, code)) throw Exception(ctx.getString(R.string.incorrect_sms_code)) } override fun currentUserWithoutData(): UserProfile? { val currentUser = Auth.currentUserWithoutData() return if (currentUser != null) UserProfile(user = currentUser) else currentUser } override fun signInAnonymous(): Completable = Completable.fromAction { Auth.signInAnonymous() } override fun updateUserPhone(phone: String): Completable = Completable.fromAction { val currentUser = Auth.currentUser() ?: throw NeedSignInException() currentUser.updateUser(UpdateUserReq().apply { this.phone = phone }) currentUser.put(UserProfile.COL_PHONE, phone) currentUser.save() bus.post(Event.UserPhoneChanged(phone = phone)) } override fun signInByEmail(email: String, pwd: String): Completable = Completable.fromAction { Auth.signInByEmail(email, pwd) } override fun signInByPhone(phone: String, smsCode: String): Completable = Completable.fromAction { Auth.signInByPhone(SignInByPhoneRequest(phone, smsCode)) } override fun sendSmsCode(phone: String): Completable = Completable.fromAction { if (!BaaS.sendSmsCode(phone)) throw BaaSException("status != ok") } /** * 通用的查询 [Tables.comment] 表的方法 * 增加了点赞字段的支持 */ private fun queryProductComment( page: Int = 0, pageSize: Int = Const.PAGE_SIZE, where: Where? = null, query: Query? = null ): Single<Page<Comment>> { // 自己可以看到待审核的内容 val w: Where if (signedIn()) { w = Where.and( where, Where.or( Where().apply { equalTo(Record.CREATED_BY, userId()?.toLong()) equalTo(Comment.COL_STATUS, BaseModel.STATUS_PENDING) }, Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } ) ) } else { w = Where.and( where, Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } ) } return Tables.comment.query( clz = Comment::class.java, page = page, pageSize = pageSize, where = w, query = query ).doOnSuccess { setVoteProperty(it.data) } } override fun myProductReview(productId: String): Single<Comment> = Single.fromCallable { assertSignIn() queryProductComment( page = 0, pageSize = 1, where = Where().apply { equalTo(Comment.COL_TYPE, Comment.TYPE_REVIEW) equalTo(Comment.COL_PRODUCT, productId) equalTo(Record.CREATED_BY, userId()?.toLong()) notEqualTo(Comment.COL_STATUS, BaseModel.STATUS_DELETED) } ).blockingGet().data.first() } override fun sendComment( productId: String, rootId: String, content: String, parentId: String?, replyId: String?, replyTo: Long? ): Single<Comment> = Single.fromCallable { assertSignIn() productId.assertNotEmpty("productId") rootId.assertNotEmpty("rootId") content.assertNotEmpty("content") val comment = Tables.comment.createRecord().apply { put(Comment.COL_TYPE, Comment.TYPE_COMMENT) put(Comment.COL_PRODUCT, productId) put(Comment.COL_ROOT_ID, rootId) put(Comment.COL_CONTENT, content) if (!parentId.isNullOrEmpty()) { put(Comment.COL_PARENT_ID, parentId) } if (!replyId.isNullOrEmpty()) { put(Comment.COL_REPLY_ID, replyId) } if (replyTo != null && replyTo > 0) { put(Comment.COL_REPLY_TO, replyTo) } }.save().let { Tables.comment.getById<Comment>(it.id!!, listOf(Record.CREATED_BY, Comment.COL_REPLY_TO)).blockingGet()!! } bus.post(Event.CommentCreated(comment)) comment } override fun isProductTagExist(productId: String, content: String): Single<Boolean> = Single.fromCallable { Tables.comment.count(Query().put(Where().apply { equalTo(Comment.COL_TYPE, Comment.TYPE_TAG) equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_CONTENT, content) equalTo(Comment.COL_CREATED_BY_USER, true) })) > 0 } override fun createProductTag(productId: String, content: String): Single<Comment> = Single.fromCallable { assertSignIn() val safeContent = content.trim() if (safeContent.isEmpty()) throw IllegalStateException("标签不能为空") if (isProductTagExist(productId = productId, content = safeContent).blockingGet()) throw UniqueRuleException("产品标签「$safeContent」已存在") Tables.comment.createRecord().apply { put(Comment.COL_TYPE, Comment.TYPE_TAG) put(Comment.COL_PRODUCT, productId) put(Comment.COL_CONTENT, safeContent) put(Comment.COL_THEME, productTagThemes.random()) put(Comment.COL_CREATED_BY_USER, true) }.save().let { Comment(it) } } override fun loadCommentVotes(ids: List<String>): Single<List<VoteLog>> = Single.fromCallable { val userId = userId() if (userId.isNullOrEmpty() || ids.isEmpty()) return@fromCallable emptyList<VoteLog>() val where = Where().apply { equalTo(Record.CREATED_BY, userId.toLong()) equalTo(VoteLog.COL_TYPE, VoteLog.TYPE_COMMENT) equalTo(VoteLog.COL_IS_POSITIVE, true) containedIn(VoteLog.COL_SUBJECT_ID, ids) } Tables.voteLog.query(VoteLog::class.java, page = 0, pageSize = ids.size, where = where) .blockingGet().data } override fun voteForComment(id: String): Completable = Completable.fromAction { assertSignIn() if (loadCommentVotes(listOf(id)).blockingGet().isEmpty()) { Tables.voteLog.createRecord().apply { put(VoteLog.COL_TYPE, VoteLog.TYPE_COMMENT) put(VoteLog.COL_SUBJECT_ID, id) put(VoteLog.COL_IS_POSITIVE, true) put(Record.CREATED_BY, userId()?.toLong()) }.save() } } override fun removeVoteForComment(id: String): Completable = Completable.fromAction { val voteId = loadCommentVotes(listOf(id)).blockingGet().firstOrNull()?.id if (!voteId.isNullOrEmpty()) Tables.voteLog.fetchWithoutData(voteId).delete() } override fun isProductFollowed(productId: String): Single<Boolean> = Single.fromCallable { val userId = userId() if (userId.isNullOrEmpty()) { return@fromCallable false } val where = Where().apply { equalTo(Favorite.COL_TYPE, Favorite.TYPE_HARDWARE) equalTo(Favorite.COL_ACTION, Favorite.ACTION_FOLLOW) equalTo(Favorite.COL_SUBJECT_ID, productId) equalTo(Record.CREATED_BY, userId.toLong()) } Tables.favorite.count(Query().apply { put(where) }) > 0 } override fun followProduct(productId: String): Completable = Completable.fromAction { assertSignIn() if (!isProductFollowed(productId).blockingGet()) { Tables.favorite.createRecord().apply { put(Favorite.COL_TYPE, Favorite.TYPE_HARDWARE) put(Favorite.COL_ACTION, Favorite.ACTION_FOLLOW) put(Favorite.COL_SUBJECT_ID, productId) }.save() bus.post(Event.FollowEvent(productId = productId, follow = true)) } } override fun unFollowProduct(productId: String): Completable = Completable.fromAction { assertSignIn() val where = Where().apply { equalTo(Record.CREATED_BY, userId()?.toLong()) equalTo(Favorite.COL_TYPE, Favorite.TYPE_HARDWARE) equalTo(Favorite.COL_ACTION, Favorite.ACTION_FOLLOW) equalTo(Favorite.COL_SUBJECT_ID, productId) } Tables.favorite.query(Query().apply { put(where) }).objects?.firstOrNull()?.delete() bus.post(Event.FollowEvent(productId = productId, follow = false)) } override fun sendReview( productId: String, productName: String, content: String, rating: Float, images: List<String> ): Single<Comment> = Single.fromCallable { val imageUrls = images.map { try { if (it.startsWith(prefix = "/", ignoreCase = true)) uploadCommentImage(it).blockingGet() else it } catch (e: Exception) { throw Exception("上传图片失败($it)", e) } } val existing = runCatching { myProductReview(productId).blockingGet() }.getOrNull() // 创建一条新点评 if (existing == null) { val create = Tables.comment.createRecord().apply { put(Comment.COL_TYPE, Comment.TYPE_REVIEW) put(Comment.COL_PRODUCT, productId) put(Comment.COL_TITLE, productName) put(Comment.COL_CONTENT, content) put(Comment.COL_RATING, rating) put(Comment.COL_IMAGE, imageUrls.toTypedArray()) }.save().let { Comment(it) } bus.post(Event.ReviewCreated(create)) create } else { // 更新点评 Tables.comment.fetchWithoutData(existing.id).apply { put(Comment.COL_CONTENT, content) put(Comment.COL_RATING, rating) put(Comment.COL_IMAGE, imageUrls.toTypedArray()) }.save() existing.images = images existing.content = content existing.rating = rating bus.post(Event.ReviewChanged(existing)) existing } } /** * 上传评论里的图片 * @param path file://... * @return 服务器路径 */ private fun uploadCommentImage(path: String): Single<String> = Single.fromCallable { val file = File(path) Storage.uploadFile(file.name, "5c80b90a6383972c4a611291", file.readBytes()).path } override fun pointLogList(type: String?): Single<PagedList<PointLog>> = Single.fromCallable { val userId = currentUserId() ?: throw NeedSignInException() pagedList(dataSource = PointLogDataSource( ctx = ctx, userId = userId, type = type )) } override fun loadPagedPointLog(page: Int, type: String?): Single<Page<PointLog>> { val userId = currentUserId() return if (userId == null) { Single.just(Page()) } else { Tables.pointLog.query( clz = PointLog::class.java, page = page, pageSize = Const.PAGE_SIZE, where = Where().apply { equalTo(Record.CREATED_BY, userId) if (type != null) { equalTo(PointLog.COL_TYPE, type) } } ).map { it.data.forEach { } it } } } private fun currentUserId(): Long? = Auth.currentUserWithoutData()?.userId override fun uploadUserAvatar(fileName: String, data: ByteArray): Single<CloudFile> = Single.fromCallable { Storage.uploadFile(fileName, "5dce53687e806526fb8b6c2b", data) } override fun updateProfile(update: UserProfile): Completable = Completable.fromCallable { val dao = Auth.currentUserWithoutData() ?: throw NeedSignInException() dao.put(UserProfile.COL_DISPLAY_AVATAR, update.displayAvatar) dao.put(UserProfile.COL_DISPLAY_NAME, update.displayName) dao.put(UserProfile.COL_MOTTO, update.motto) dao.put(UserProfile.COL_PROFESSION, update.profession) dao.put(UserProfile.COL_PHONE, update.phone) dao.put(UserProfile.COL_BANNER, update.banner) dao.save() bus.post(Event.ProfileChanged) } override fun signOut() { Auth.logout() bus.post(Event.SignOut) } override fun signedIn(): Boolean = Auth.signedIn() override fun loadUserProfile(): Single<UserProfile> = Single.fromCallable { val user = Auth.currentUser() if (user != null) UserProfile(user) else null } override fun searchHint(key: String): Single<List<Product>> = Tables.product.query<Product>( page = 0, pageSize = 10, query = Query().apply { var where = Where.or( Where().apply { contains(Product.COL_NAME, key) }, Where().apply { contains(Product.COL_BRIEF, key) }) where = Where.or(where, Where().apply { contains(Product.COL_DESCRIPTION, key) }) where = Where.or(where, Where().apply { arrayContains(Product.COL_CATEGORY, listOf(key)) }) where = Where.and(where, Where().apply { equalTo(Product.COL_TYPE, Product.TYPE_HARDWARE) equalTo(Product.COL_STATUS, BaseModel.STATUS_APPROVED) }) put(where) orderBy(listOf("-${Product.COL_REVIEW_COUNT}", "-${Record.UPDATED_AT}", "-${Product.COL_PRIORITY}", "-${Product.COL_RATING}")) } ).map { it.data } override fun search(key: String): Single<PagedList<Product>> = Single.fromCallable { addSearchLog(key).subscribeOn(Schedulers.io()).subscribe() pagedList( SearchDataSource( key ) ) } override fun loadSearchLog(): Single<List<SearchLog>> { val id = currentUserId() return if (id != null) { Tables.searchLog.query<SearchLog>( page = 0, pageSize = 100, where = Where().apply { equalTo(SearchLog.COL_STATUS, BaseModel.STATUS_APPROVED) equalTo(Record.CREATED_BY, id) } ).map { it.data } } else { Single.just(emptyList()) } } /** * 增加一条搜索历史 */ private fun addSearchLog(key: String): Completable = Completable.fromCallable { val id = currentUserId() if (id != null) { val exist = Tables.searchLog.count(Query().put(Where().apply { equalTo(Record.CREATED_BY, id) equalTo(SearchLog.COL_KEY, key) equalTo(SearchLog.COL_STATUS, BaseModel.STATUS_APPROVED) })) > 0 if (!exist) { Tables.searchLog.createRecord().apply { put(SearchLog.COL_KEY, key) put(SearchLog.COL_STATUS, BaseModel.STATUS_APPROVED) }.save() } } } override fun cleanSearchLog(): Completable = Completable.fromCallable { val userId = currentUserId() if (userId != null) { val query = Query().put(Where().apply { equalTo(SearchLog.COL_STATUS, BaseModel.STATUS_APPROVED) equalTo(Record.CREATED_BY, userId) }) val update = Tables.searchLog.createRecord().apply { put(SearchLog.COL_STATUS, BaseModel.STATUS_DELETED) } Tables.searchLog.batchUpdate(query, update) } } override fun latestProduct(): Single<List<Product>> = Tables.product.query<Product>( page = 0, pageSize = 20, where = Where().apply { equalTo(Product.COL_TYPE, Product.TYPE_HARDWARE) equalTo(Product.COL_STATUS, BaseModel.STATUS_APPROVED) }, query = Query().apply { orderBy("-${Product.COL_RELEASED_AT}") } ).map { it.data } override fun loadPagedChildComment( productId: String, reviewId: String, parentId: String, offset: Int ): Single<PageByOffset<Comment>> { val baseCondition = Where().apply { equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_ROOT_ID, reviewId) equalTo(Comment.COL_TYPE, Comment.TYPE_COMMENT) equalTo(Comment.COL_PARENT_ID, parentId) } val profileCondition = if (signedIn()) Where.or( Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_PENDING) equalTo(Record.CREATED_BY, currentUserId()) }, Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } ) else Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } return Tables.comment.queryByOffset( clz = Comment::class.java, offset = offset, where = Where.and(baseCondition, profileCondition), query = Query().apply { orderBy(Record.CREATED_AT) expand(listOf(Comment.COL_REPLY_TO, Record.CREATED_BY)) }) .doOnSuccess { setVoteProperty(it.data) } } override fun loadPagedComment( productId: String, reviewId: String, page: Int, pageSize: Int ): Single<Page<Comment>> = Single.fromCallable { // 查询一级评论 val commonCondition = Where().apply { equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_ROOT_ID, reviewId) equalTo(Comment.COL_TYPE, Comment.TYPE_COMMENT) isNull(Comment.COL_PARENT_ID) } var signInCondition = Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } if (signedIn()) { signInCondition = Where.or(signInCondition, Where().apply { equalTo(Record.CREATED_BY, userId()?.toLong()) notEqualTo(Comment.COL_STATUS, BaseModel.STATUS_DELETED) }) } val comments = Tables.comment.query( Comment::class.java, page = page, pageSize = pageSize, where = Where.and(commonCondition, signInCondition), query = Query().apply { orderBy("-${Comment.COL_UPVOTE},-${Record.CREATED_AT}") expand(Record.CREATED_BY) } ).blockingGet() // 批量拉取二级评论 if (comments.data.isNotEmpty()) { val baseCondition = Where().apply { equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_ROOT_ID, reviewId) equalTo(Comment.COL_TYPE, Comment.TYPE_COMMENT) containedIn(Comment.COL_PARENT_ID, comments.data.map { it.id }) } val profileCondition = if (signedIn()) Where.or( Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_PENDING) equalTo(Record.CREATED_BY, currentUserId()) }, Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } ) else Where().apply { equalTo(Comment.COL_STATUS, BaseModel.STATUS_APPROVED) } val children = Tables.comment.query( Comment::class.java, page = 0, pageSize = comments.data.size * 10, where = Where.and(baseCondition, profileCondition), query = Query().apply { orderBy(Record.CREATED_AT) expand(listOf(Record.CREATED_BY, Comment.COL_REPLY_TO)) } ).blockingGet().data comments.data.forEach { parent -> children.find { it.parentId == parent.id }?.also { firstChild -> parent.children = listOf(firstChild, Comment(id = uuid(), loading = false)) } } } comments }.doOnSuccess { setVoteProperty(it.data) } override fun getReviewById(reviewId: String): Single<Comment> = Single.fromCallable { queryProductComment( page = 0, pageSize = 1, where = Where().apply { equalTo(Record.ID, reviewId) }, query = Query().apply { expand(listOf(Record.CREATED_BY)) } ).blockingGet().data.first() } override fun loadAllTags(productId: String): Single<List<Comment>> = queryProductComment( page = 0, pageSize = 999, where = Where().apply { equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_TYPE, Comment.TYPE_TAG) }, query = Query().apply { orderBy("-${Comment.COL_UPVOTE}", "-${Record.UPDATED_AT}") }) .map { it.data } override fun loadPagedReviews( productId: String, page: Int, pageSize: Int, orderBy: CommentSwitch.Type? ): Single<Page<Comment>> = queryProductComment( page = page, pageSize = pageSize, where = Where().apply { equalTo(Comment.COL_PRODUCT, productId) equalTo(Comment.COL_TYPE, Comment.TYPE_REVIEW) isNotNull(Comment.COL_CONTENT) notEqualTo(Comment.COL_CONTENT, "") if (orderBy == CommentSwitch.Type.EDITOR_CHOICE) equalTo(Comment.COL_RECOMMENDED, true) }, query = Query().apply { expand(Record.CREATED_BY) when (orderBy) { CommentSwitch.Type.HOTTEST -> orderBy("-${Comment.COL_UPVOTE}") CommentSwitch.Type.LATEST -> orderBy("-${Record.CREATED_AT}") } } ) override fun productList(productId: String): Single<PagedList<ProductList>> = Single.fromCallable { pagedList(dataSource = ProductListDataSource( productId ) ) } override fun getProductsByIds(ids: List<String>): Single<List<Product>> = Tables.product.getByIds(ids) override fun getProductById(id: String): Single<Product> = Tables.product.getById(id) override fun getProductListByProductId( productId: String, page: Int, pageSize: Int ): Single<Page<ProductList>> = Tables.itemList.query ( clz = ProductList::class.java, page = page, pageSize = pageSize, where = Where().apply { containedIn(ProductList.COL_ITEMS, listOf(productId)) equalTo(ProductList.COL_STATUS, BaseModel.STATUS_APPROVED) }) override fun getProductParamsById(paramId: String): Single<ProductParams> { val request: Single<ProductParams> = Tables.productParam.getById(paramId) return request.map { var groups = it.value // 隐藏参数 val hiddens = setting.hiddenProductParams().blockingGet() groups = groups.filter { !hiddens.contains(it.key) } // 第一级参数名称映射 val mapping = setting.productParamMapping().blockingGet() groups = groups.map { val mappingKey = mapping[it.key] if (mappingKey != null) it.copy(key = mappingKey) else it } // 第二级参数名称映射 groups = groups.map { it.copy(children = it.children.map { val mappingKey = mapping[it.key] if (mappingKey != null) it.copy(key = mappingKey) else it }) } it.copy(value = groups) } } @Throws(NeedSignInException::class) private fun assertSignIn() { if (!signedIn()) throw NeedSignInException() } override fun currentUser(): Single<UserProfile> = Single.fromCallable { Auth.currentUser() ?: throw NeedSignInException() }.map { UserProfile(user = it) } /** * 查询并设置评论的点赞状态 */ private fun setVoteProperty(comments: List<Comment>) { if (signedIn() && comments.isNotEmpty()) { try { val flatList = comments.flatMap { it.children + it } val votes = loadCommentVotes(flatList.map { it.id }).blockingGet() flatList.forEach { review -> review.voted = votes.any { it.subjectId == review.id && it.isPositive } } } catch (e: Exception) {} } } }
0
Kotlin
0
0
ab9a7a2eba7f53eca918e084da9d9907f7997cee
30,135
tangzhi_android
Apache License 2.0
HTTPShortcuts/framework/src/main/kotlin/ch/rmy/android/framework/extensions/ContextExtensions.kt
Waboodoo
34,525,124
false
null
package ch.rmy.android.framework.extensions import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.res.Configuration import android.widget.Toast import androidx.annotation.StringRes import androidx.core.net.toUri import androidx.fragment.app.Fragment import ch.rmy.android.http_shortcuts.R fun Context.showToast(message: String, long: Boolean = false) { Toast.makeText(this, message, if (long) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show() } fun Context.showToast(@StringRes message: Int, long: Boolean = false) { Toast.makeText(this, message, if (long) Toast.LENGTH_LONG else Toast.LENGTH_SHORT).show() } fun Context.openURL(url: String) { try { Intent(Intent.ACTION_VIEW, url.toUri()) .startActivity(this) } catch (e: ActivityNotFoundException) { showToast(R.string.error_not_supported) } } fun Fragment.openURL(url: String) { try { Intent(Intent.ACTION_VIEW, url.toUri()) .startActivity(this) } catch (e: ActivityNotFoundException) { showSnackbar(R.string.error_not_supported) } } fun Context.isDarkThemeEnabled() = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK == Configuration.UI_MODE_NIGHT_YES
36
null
94
645
c78059462ad78d382bc12ff56cd0432b5fa78c96
1,302
HTTP-Shortcuts
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Bank.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.Bank: ImageVector get() { if (_bank != null) { return _bank!! } _bank = Builder(name = "Bank", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(0.0f, 22.0f) horizontalLineToRelative(24.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(-24.0f) close() moveTo(24.0f, 7.909f) verticalLineToRelative(2.091f) horizontalLineToRelative(-3.0f) verticalLineToRelative(8.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(2.0f) horizontalLineToRelative(-22.0f) verticalLineToRelative(-2.0f) horizontalLineToRelative(2.0f) verticalLineToRelative(-8.0f) horizontalLineToRelative(-3.0f) verticalLineToRelative(-2.091f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 1.563f, -2.634f) lineToRelative(9.0f, -4.909f) arcToRelative(2.993f, 2.993f, 0.0f, false, true, 2.874f, 0.0f) lineToRelative(9.0f, 4.909f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 1.563f, 2.634f) close() moveTo(5.0f, 18.0f) horizontalLineToRelative(3.0f) verticalLineToRelative(-8.0f) horizontalLineToRelative(-3.0f) close() moveTo(10.0f, 10.0f) verticalLineToRelative(8.0f) horizontalLineToRelative(4.0f) verticalLineToRelative(-8.0f) close() moveTo(19.0f, 10.0f) horizontalLineToRelative(-3.0f) verticalLineToRelative(8.0f) horizontalLineToRelative(3.0f) close() moveTo(22.0f, 7.909f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.521f, -0.878f) lineToRelative(-9.0f, -4.909f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.958f, 0.0f) lineToRelative(-9.0f, 4.909f) arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.521f, 0.878f) verticalLineToRelative(0.091f) horizontalLineToRelative(20.0f) close() } } .build() return _bank!! } private var _bank: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,384
icons
MIT License
src/main/kotlin/com/iman/bnpl/actor/http/user/api/AuthController.kt
imancn
849,339,456
false
{"Kotlin": 88023}
package com.iman.bnpl.actor.http.user.api import com.iman.bnpl.actor.http.user.payload.response.JwtResponse import com.iman.bnpl.actor.http.user.payload.response.RefreshTokenResponse import com.iman.bnpl.application.advice.* import com.iman.bnpl.application.shared.util.Auth import com.iman.bnpl.domain.user.data.repository.UserRepository import com.iman.bnpl.application.security.service.JwtService import com.iman.bnpl.domain.user.services.RefreshTokenService import com.iman.bnpl.domain.user.data.model.Role import com.iman.bnpl.domain.user.data.model.UserDetailsImpl import com.iman.bnpl.domain.user.data.model.UserEntity import com.iman.bnpl.domain.user.services.OtpTokenService import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.Pattern import jakarta.validation.constraints.Size import org.springframework.security.access.prepost.PreAuthorize import org.springframework.security.authentication.AuthenticationManager import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.core.authority.SimpleGrantedAuthority import org.springframework.security.core.context.SecurityContextHolder import org.springframework.security.crypto.password.PasswordEncoder import org.springframework.validation.annotation.Validated import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/api/auth/v1") @Validated class AuthController( val authenticationManager: AuthenticationManager, val userRepository: UserRepository, val refreshTokenService: RefreshTokenService, val encoder: PasswordEncoder, val jwtService: JwtService, private val otpTokenService: OtpTokenService, ) { @PostMapping("/sign-in") fun signInUser( @RequestParam @NotBlank @Pattern(regexp = "\\b9\\d{9}") phoneNumber: String, @RequestParam @NotBlank password: String ): JwtResponse { val user = userRepository.findByPhoneNumberAndDeleted(phoneNumber).orElseThrow { AccessDeniedException("Invalid credentials") } val authentication = authenticationManager.authenticate( UsernamePasswordAuthenticationToken(user.id, password) ) SecurityContextHolder.getContext().authentication = authentication val jwt = jwtService.generateJwtToken(authentication.principal as UserDetailsImpl) val userDetails = authentication.principal as UserDetailsImpl val refreshToken = refreshTokenService.createRefreshToken(userDetails.id) return JwtResponse( jwt, refreshToken.id ?: "", userDetails.phoneNumber ) } @PostMapping("/sign-in/otp/verify") fun verifyOtpToSignInUser( @RequestParam @NotBlank @Pattern(regexp = "\\b9\\d{9}") phoneNumber: String, @RequestParam @NotBlank otp: String ): JwtResponse { val user = userRepository.findByPhoneNumberAndDeleted(phoneNumber).orElseThrow { UnprocessableException("You are not registered") } otpTokenService.validateOtpTokenForLogin(user.id ?: "", otp) val userDetails = UserDetailsImpl( user.id ?: "", user.phoneNumber, user.password, user.roles.map { role -> SimpleGrantedAuthority(role.name)}, user.deleted ) val jwt = jwtService.generateJwtToken(userDetails) val refreshToken = refreshTokenService.createRefreshToken(userDetails.id) return JwtResponse( jwt, refreshToken.id ?: "", userDetails.phoneNumber ) } @PostMapping("/sign-in/otp/request") fun requestOtpToSignInUserUser( @RequestParam @NotBlank @Pattern(regexp = "\\b9\\d{9}") phoneNumber: String, ) { val user = userRepository.findByPhoneNumberAndDeleted(phoneNumber).orElseThrow { UnprocessableException("You are not registered") } otpTokenService.sendOtp(user.id ?: "", phoneNumber) } @PostMapping("/customer/signup") fun registerStudent( @RequestParam @NotBlank fullName: String, @RequestParam @NotBlank @Pattern(regexp = "\\b9\\d{9}") phoneNumber: String, @RequestParam @Size(min = 6, max = 40) password: String?, ) { if (!Regex("\\b9\\d{9}").containsMatchIn(phoneNumber)) throw InvalidInputException("Invalid phone number") val user = userRepository.findByPhoneNumberAndDeleted(phoneNumber).let { if (!it.isPresent) { userRepository.save( UserEntity( id = null, fullName = fullName, phoneNumber = phoneNumber, password = password?.let{ password -> encoder.encode(password) }, roles = setOf(Role.ROLE_CUSTOMER) ) ) } else it.get() } otpTokenService.sendOtp(user.id ?: "", phoneNumber) } @PostMapping("/refresh-token") fun refreshToken( @RequestParam @NotBlank refreshToken: String, ): RefreshTokenResponse { return refreshTokenService.findByToken(refreshToken).map { val token = jwtService.generateTokenFromUserId(it.userId) val newRefreshToken = refreshTokenService.createRefreshToken(it.userId) refreshTokenService.deleteById(refreshToken) RefreshTokenResponse(token, newRefreshToken.id ?: "") }.orElseThrow { RefreshTokenException("Your Session has been expired") } } @PostMapping("/change-password") @PreAuthorize("hasAnyRole('ADMIN')") fun changePassword( @RequestParam @Size(min = 6, max = 40) @NotBlank oldPassword: String, @RequestParam @Size(min = 6, max = 40) @NotBlank newPassword: String ): String { val user = userRepository.findByIdAndDeleted(Auth.userId()).orElseThrow { NotFoundException("User Not Found") } if (user.password == encoder.encode(oldPassword)) user.password = encoder.encode(newPassword) else throw InvalidInputException("Old Password is not correct.") return "Your password has been changed." } @PostMapping("/sign-out") fun signOutUser(): String { refreshTokenService.deleteByUserId(Auth.userId()) return "User signed out successfully" } }
0
Kotlin
0
0
88fa9b9c349e2a7aeefff0af7ffd7b00730f0fe1
6,397
bnpl
Apache License 2.0
java/com/google/android/libraries/pcc/chronicle/api/operation/OperationLibrary.kt
google
564,990,777
false
null
/* * Copyright 2022 Google LLC * * 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.google.android.libraries.pcc.chronicle.api.operation /** * An [OperationLibrary] is a collection of [Operations][Operation] which is searchable by * [Operation.name], [Operation.inputType], and [Operation.outputType]. */ interface OperationLibrary { /** * Finds a matching [Operation] within the [OperationLibrary], or returns `null` if none is found. */ fun <Input, Output> findOperation( name: String, inputType: Class<in Input>, outputType: Class<out Output>, ): Operation<in Input, out Output>? } /** * Finds a matching [Operation] within the receiving [OperationLibrary], or returns `null` if none * is found. */ inline fun <reified T> OperationLibrary.findOperation(name: String): Operation<in T, out T>? = findOperation(name, T::class.java, T::class.java)
0
Kotlin
6
24
2c1b7135980d5cf15dc6ecc9624be0125a792a5c
1,405
private-compute-libraries
Apache License 2.0
app/src/main/java/com/mospolytech/mospolyhelper/features/ui/account/payments/adapter/PagerAdapter.kt
mospolyhelper
259,442,737
false
{"Kotlin": 839539, "Batchfile": 69}
package com.mospolytech.mospolyhelper.features.ui.account.payments.adapter import android.annotation.SuppressLint import android.text.method.LinkMovementMethod import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.TextView import android.widget.Toast import androidx.core.text.HtmlCompat import androidx.recyclerview.widget.RecyclerView import by.kirich1409.viewbindingdelegate.viewBinding import com.mospolytech.mospolyhelper.R import com.mospolytech.mospolyhelper.databinding.ItemPaymentsBinding import com.mospolytech.mospolyhelper.domain.account.payments.model.Contract import com.mospolytech.mospolyhelper.utils.gone import com.mospolytech.mospolyhelper.utils.show class PagerAdapter(private val items: List<Contract>): RecyclerView.Adapter<PagerAdapter.PagerViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PagerViewHolder { return PagerViewHolder( LayoutInflater.from(parent.context) .inflate(R.layout.item_payments, parent, false)) } override fun onBindViewHolder(holder: PagerViewHolder, position: Int) { holder.bind(items[position]) } override fun getItemCount(): Int { return items.size } class PagerViewHolder(view: View): RecyclerView.ViewHolder(view) { private val viewBinding by viewBinding(ItemPaymentsBinding::bind) private val recycler: RecyclerView = viewBinding.recyclerDormitory private val info: TextView = viewBinding.paymentInfo private val all: TextView = viewBinding.paymentAll private val current: TextView = viewBinding.paymentCurrent private val sberQr: TextView = viewBinding.sberQr private val qrHelp: TextView = viewBinding.qrHelp private val qrContainer: FrameLayout = viewBinding.qrContainer @SuppressLint("SetTextI18n") fun bind(contract: Contract) { recycler.adapter = PaymentsAdapter(contract.payments) info.text = contract.name all.text = String.format(itemView.context.getString(R.string.payment_left), contract.remainingAmount, contract.paidAmount) current.text = when { contract.debt < 0 -> { String.format(itemView.context.getString(R.string.payment_debet), contract.debt, contract.debtDate).replace("-", "") } contract.debt == 0 -> { String.format(itemView.context.getString(R.string.payment_no_credit), contract.debtDate) } else -> { String.format(itemView.context.getString(R.string.payment_credit), contract.debt, contract.debtDate) } } if (contract.sberQR.isNotEmpty()) { sberQr.text = HtmlCompat.fromHtml( "<a href=\"https://e.mospolytech.ru/${contract.sberQR}\">Sber QR</a>", HtmlCompat.FROM_HTML_MODE_COMPACT) sberQr.movementMethod = LinkMovementMethod.getInstance() qrContainer.show() } else { qrContainer.gone() } qrHelp.setOnClickListener { Toast.makeText(itemView.context, R.string.help, Toast.LENGTH_LONG).show() } } } }
2
Kotlin
2
8
4f37c3617cf7523f22f03a22d7de2d7ecc74a098
3,437
mospolyhelper-android
MIT License