path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
756M
is_fork
bool
2 classes
languages_distribution
stringlengths
12
2.44k
content
stringlengths
6
6.29M
issues
float64
0
10k
main_language
stringclasses
128 values
forks
int64
0
54.2k
stars
int64
0
157k
commit_sha
stringlengths
40
40
size
int64
6
6.29M
name
stringlengths
1
100
license
stringclasses
104 values
tests/integration-tests/src/test/kotlin/interactions/Get.kt
hyperledger-labs
512,835,706
false
{"Scala": 2140880, "Kotlin": 115517, "Jupyter Notebook": 68331, "TypeScript": 46919, "Shell": 25146, "Python": 13697, "Gherkin": 6776, "Smarty": 1664, "JavaScript": 1205, "Dockerfile": 320}
package interactions import net.serenitybdd.annotations.Step import net.serenitybdd.screenplay.Actor import net.serenitybdd.screenplay.Tasks import net.serenitybdd.screenplay.rest.abilities.CallAnApi /** * This class is a copy of the class Get from serenity rest interactions * to add a custom authentication header to the request on-the-fly. */ open class Get(private val resource: String) : AuthRestInteraction() { @Step("{0} executes a GET on the resource #resource") override fun <T : Actor?> performAs(actor: T) { specWithAuthHeaders(actor).get(CallAnApi.`as`(actor).resolve(resource)) } companion object { fun resource(resource: String?): Get { return Tasks.instrumented(Get::class.java, resource) } } }
16
Scala
9
50
28a6d418e67dd609d864611dbf546134117528c9
772
open-enterprise-agent
Apache License 2.0
compose/src/commonMain/kotlin/androidx/constraintlayout/core/state/Transition.kt
Lavmee
711,725,142
false
{"Kotlin": 3000082}
/* * 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 androidx.constraintlayout.core.state import androidx.constraintlayout.core.motion.CustomVariable import androidx.constraintlayout.core.motion.Motion import androidx.constraintlayout.core.motion.MotionWidget import androidx.constraintlayout.core.motion.key.MotionKeyAttributes import androidx.constraintlayout.core.motion.key.MotionKeyCycle import androidx.constraintlayout.core.motion.key.MotionKeyPosition import androidx.constraintlayout.core.motion.utils.Easing import androidx.constraintlayout.core.motion.utils.KeyCache import androidx.constraintlayout.core.motion.utils.SpringStopEngine import androidx.constraintlayout.core.motion.utils.StopEngine import androidx.constraintlayout.core.motion.utils.StopLogicEngine import androidx.constraintlayout.core.motion.utils.StopLogicEngine.Decelerate import androidx.constraintlayout.core.motion.utils.TypedBundle import androidx.constraintlayout.core.motion.utils.TypedValues import androidx.constraintlayout.core.motion.utils.TypedValues.TransitionType import androidx.constraintlayout.core.motion.utils.Utils import androidx.constraintlayout.core.platform.System import androidx.constraintlayout.core.widgets.ConstraintWidget import androidx.constraintlayout.core.widgets.ConstraintWidgetContainer import kotlin.math.abs import kotlin.math.max import kotlin.math.min import kotlin.math.sign class Transition(dpToPixel: CorePixelDp) : TypedValues { private val mKeyPositions = HashMap<Int, HashMap<String, KeyPosition>>() private val mState: HashMap<String, WidgetState> = HashMap() private val mBundle = TypedBundle() // Interpolation private val mDefaultInterpolator = 0 private var mDefaultInterpolatorString: String? = null private var mEasing: Easing? = null private val mAutoTransition = 0 private val mDuration = 400 private var mStagger = 0.0f private var mOnSwipe: OnSwipe? = null val mToPixel: CorePixelDp = dpToPixel // Todo placed here as a temp till the refactor is done var mParentStartWidth = 0 var mParentStartHeight = 0 var mParentEndWidth = 0 var mParentEndHeight = 0 var mParentInterpolatedWidth = 0 var mParentInterpolateHeight = 0 var mWrap = false class KeyPosition( target: String, frame: Int, type: Int, x: Float, y: Float, ) { var mFrame = frame var mTarget: String = target var mType = type var mX = x var mY = y } // @TODO: add description fun createOnSwipe(): OnSwipe { mOnSwipe = OnSwipe() return mOnSwipe!! } // @TODO: add description fun hasOnSwipe(): Boolean { return mOnSwipe != null } /** * For the given position (in the MotionLayout coordinate space) determine whether we accept * the first down for on swipe. * * * This is based off [OnSwipe.mLimitBoundsTo]. If null, we accept the drag at any * position, otherwise, we only accept it if it's within its bounds. */ // @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun isFirstDownAccepted(posX: Float, posY: Float): Boolean { if (mOnSwipe == null) { return false } return if (mOnSwipe!!.mLimitBoundsTo != null) { val targetWidget: WidgetState? = mState[mOnSwipe!!.mLimitBoundsTo] if (targetWidget == null) { println("mLimitBoundsTo target is null") return false } // Calculate against the interpolated/current frame val frame: WidgetFrame = targetWidget.getFrame(2) posX >= frame.left && posX < frame.right && posY >= frame.top && posY < frame.bottom } else { true } } /** * Converts from xy drag to progress * This should be used till touch up * * @param baseW parent width * @param baseH parent height * @param dx change in x * @param dy change in y * @return the change in progress */ fun dragToProgress( currentProgress: Float, baseW: Int, baseH: Int, dx: Float, dy: Float, ): Float { val widgets: Collection<WidgetState> = mState.values var childWidget: WidgetState? = null for (widget in widgets) { childWidget = widget break } if (mOnSwipe == null || childWidget == null) { return if (childWidget != null) { -dy / childWidget.mParentHeight } else { 1.0f } } if (mOnSwipe!!.mAnchorId == null) { val dir = mOnSwipe!!.getDirection() val motionDpDtX: Float = childWidget.mParentHeight.toFloat() val motionDpDtY: Float = childWidget.mParentHeight.toFloat() val drag = if (dir[0] != 0f) { dx * abs(dir[0]) / motionDpDtX } else { dy * abs( dir[1], ) / motionDpDtY } return drag * mOnSwipe!!.getScale() } val base: WidgetState = mState[mOnSwipe!!.mAnchorId]!! val dir = mOnSwipe!!.getDirection() val side = mOnSwipe!!.getSide() val motionDpDt = FloatArray(2) base.interpolate(baseW, baseH, currentProgress, this) base.mMotionControl.getDpDt(currentProgress, side[0], side[1], motionDpDt) val drag = if (dir[0] != 0f) { dx * abs(dir[0]) / motionDpDt[0] } else { dy * abs( dir[1], ) / motionDpDt[1] } if (DEBUG) { Utils.log(" drag $drag") } return drag * mOnSwipe!!.getScale() } /** * Set the start of the touch up * * @param currentProgress 0...1 progress in * @param currentTime time in nanoseconds * @param velocityX pixels per millisecond * @param velocityY pixels per millisecond */ fun setTouchUp( currentProgress: Float, currentTime: Long, velocityX: Float, velocityY: Float, ) { if (mOnSwipe != null) { if (DEBUG) { Utils.log(" >>> velocity x,y = $velocityX , $velocityY") } val base: WidgetState = mState[mOnSwipe!!.mAnchorId]!! val motionDpDt = FloatArray(2) val dir = mOnSwipe!!.getDirection() val side = mOnSwipe!!.getSide() base.mMotionControl.getDpDt(currentProgress, side[0], side[1], motionDpDt) val movementInDir = dir[0] * motionDpDt[0] + dir[1] * motionDpDt[1] if (abs(movementInDir) < 0.01) { if (DEBUG) { Utils.log(" >>> cap minimum v!! ") } motionDpDt[0] = .01f motionDpDt[1] = .01f } var drag = if (dir[0] != 0f) velocityX / motionDpDt[0] else velocityY / motionDpDt[1] drag *= mOnSwipe!!.getScale() if (DEBUG) { Utils.log(" >>> velocity $drag") Utils.log(" >>> mDuration $mDuration") Utils.log(" >>> currentProgress $currentProgress") } mOnSwipe!!.config(currentProgress, drag, currentTime, mDuration * 1E-3f) if (DEBUG) { mOnSwipe!!.printInfo() } } } /** * get the current touch up progress current time in nanoseconds * (ideally coming from an animation clock) * * @param currentTime in nanoseconds * @return progress */ fun getTouchUpProgress(currentTime: Long): Float { return if (mOnSwipe != null) { mOnSwipe!!.getTouchUpProgress(currentTime) } else { 0f } } /** * Are we still animating * * @param currentProgress motion progress * @return true to continue moving */ fun isTouchNotDone(currentProgress: Float): Boolean { return mOnSwipe!!.isNotDone(currentProgress) } // @TODO: add description fun findPreviousPosition(target: String, frameNumber: Int): KeyPosition? { var frameNumber = frameNumber while (frameNumber >= 0) { val map = mKeyPositions[frameNumber] if (map != null) { val keyPosition = map[target] if (keyPosition != null) { return keyPosition } } frameNumber-- } return null } // @TODO: add description fun findNextPosition(target: String, frameNumber: Int): KeyPosition? { var frameNumber = frameNumber while (frameNumber <= 100) { val map = mKeyPositions[frameNumber] if (map != null) { val keyPosition = map[target] if (keyPosition != null) { return keyPosition } } frameNumber++ } return null } // @TODO: add description fun getNumberKeyPositions(frame: WidgetFrame): Int { var numKeyPositions = 0 var frameNumber = 0 while (frameNumber <= 100) { val map: HashMap<String, KeyPosition>? = mKeyPositions[frameNumber] if (map != null) { val keyPosition = map[frame.widget!!.stringId] if (keyPosition != null) { numKeyPositions++ } } frameNumber++ } return numKeyPositions } // @TODO: add description fun getMotion(id: String?): Motion { return getWidgetState(id, null, 0).mMotionControl } // @TODO: add description fun fillKeyPositions(frame: WidgetFrame, x: FloatArray, y: FloatArray, pos: FloatArray) { var numKeyPositions = 0 var frameNumber = 0 while (frameNumber <= 100) { val map: HashMap<String, KeyPosition>? = mKeyPositions[frameNumber] if (map != null) { val keyPosition = map[frame.widget!!.stringId] if (keyPosition != null) { x[numKeyPositions] = keyPosition.mX y[numKeyPositions] = keyPosition.mY pos[numKeyPositions] = keyPosition.mFrame.toFloat() numKeyPositions++ } } frameNumber++ } } // @TODO: add description fun hasPositionKeyframes(): Boolean { return mKeyPositions.size > 0 } // @TODO: add description fun setTransitionProperties(bundle: TypedBundle) { bundle.applyDelta(mBundle) bundle.applyDelta(this) } override fun setValue(id: Int, value: Int): Boolean { return false } override fun setValue(id: Int, value: Float): Boolean { if (id == TransitionType.TYPE_STAGGERED) { mStagger = value } return false } override fun setValue(id: Int, value: String): Boolean { if (id == TransitionType.TYPE_INTERPOLATOR) { mEasing = Easing.getInterpolator(value.also { mDefaultInterpolatorString = it }) } return false } override fun setValue(id: Int, value: Boolean): Boolean { return false } override fun getId(name: String?): Int { return 0 } val isEmpty: Boolean get() = mState.isEmpty() // @TODO: add description fun clear() { mState.clear() } /** * Reset animation properties of the Transition. * * * This will not affect the internal model of the widgets (a.k.a. [.mState]). */ fun resetProperties() { mOnSwipe = null mBundle.clear() } // @TODO: add description operator fun contains(key: String?): Boolean { return mState.containsKey(key) } // @TODO: add description fun addKeyPosition(target: String?, bundle: TypedBundle) { getWidgetState(target, null, 0).setKeyPosition(bundle) } // @TODO: add description fun addKeyAttribute(target: String?, bundle: TypedBundle) { getWidgetState(target, null, 0).setKeyAttribute(bundle) } /** * Add a key attribute and the custom variables into the * @param target the id of the target * @param bundle the key attributes bundle containing position etc. * @param custom the customVariables to add at that position */ fun addKeyAttribute(target: String?, bundle: TypedBundle, custom: Array<CustomVariable?>?) { getWidgetState(target, null, 0).setKeyAttribute(bundle, custom) } // @TODO: add description fun addKeyCycle(target: String?, bundle: TypedBundle) { getWidgetState(target, null, 0).setKeyCycle(bundle) } // @TODO: add description fun addKeyPosition(target: String?, frame: Int, type: Int, x: Float, y: Float) { val bundle = TypedBundle() bundle.add(TypedValues.PositionType.TYPE_POSITION_TYPE, 2) bundle.add(TypedValues.TYPE_FRAME_POSITION, frame) bundle.add(TypedValues.PositionType.TYPE_PERCENT_X, x) bundle.add(TypedValues.PositionType.TYPE_PERCENT_Y, y) getWidgetState(target, null, 0).setKeyPosition(bundle) val keyPosition = KeyPosition(target!!, frame, type, x, y) var map: HashMap<String, KeyPosition>? = mKeyPositions[frame] if (map == null) { map = HashMap() mKeyPositions[frame] = map } map[target] = keyPosition } // @TODO: add description fun addCustomFloat(state: Int, widgetId: String?, property: String, value: Float) { val widgetState: WidgetState = getWidgetState(widgetId, null, state) val frame: WidgetFrame = widgetState.getFrame(state) frame.addCustomFloat(property, value) } // @TODO: add description fun addCustomColor(state: Int, widgetId: String?, property: String, color: Int) { val widgetState: WidgetState = getWidgetState(widgetId, null, state) val frame: WidgetFrame = widgetState.getFrame(state) frame.addCustomColor(property, color) } private fun calculateParentDimensions(progress: Float) { mParentInterpolatedWidth = ( 0.5f + mParentStartWidth + (mParentEndWidth - mParentStartWidth) * progress ).toInt() mParentInterpolateHeight = ( 0.5f + mParentStartHeight + (mParentEndHeight - mParentStartHeight) * progress ).toInt() } val interpolatedWidth: Int get() = mParentInterpolatedWidth val interpolatedHeight: Int get() = mParentInterpolateHeight /** * Update container of parameters for the state * * @param container contains all the widget parameters * @param state starting or ending */ fun updateFrom(container: ConstraintWidgetContainer, state: Int) { mWrap = ( container.mListDimensionBehaviors[0] == ConstraintWidget.DimensionBehaviour.WRAP_CONTENT ) mWrap = mWrap or ( container.mListDimensionBehaviors[1] == ConstraintWidget.DimensionBehaviour.WRAP_CONTENT ) if (state == START) { mParentStartWidth = container.width mParentInterpolatedWidth = mParentStartWidth mParentStartHeight = container.height mParentInterpolateHeight = mParentStartHeight } else { mParentEndWidth = container.width mParentEndHeight = container.height } val children = container.children val count = children.size val states: Array<WidgetState?> = arrayOfNulls<WidgetState>(count) for (i in 0 until count) { val child = children[i] val widgetState: WidgetState = getWidgetState(child.stringId, null, state) states[i] = widgetState widgetState.update(child, state) val id: String? = widgetState.getPathRelativeId() if (id != null) { widgetState.setPathRelative(getWidgetState(id, null, state)) } } calcStagger() } // @TODO: add description fun interpolate(parentWidth: Int, parentHeight: Int, progress: Float) { var progress = progress if (mWrap) { calculateParentDimensions(progress) } if (mEasing != null) { progress = mEasing!!.get(progress.toDouble()).toFloat() } for (key in mState.keys) { val widget: WidgetState? = mState[key] widget?.interpolate(parentWidth, parentHeight, progress, this) } } // @TODO: add description fun getStart(id: String?): WidgetFrame { val widgetState: WidgetState = mState[id] ?: return null!! return widgetState.mStart } // @TODO: add description fun getEnd(id: String?): WidgetFrame { val widgetState: WidgetState = mState[id] ?: return null!! return widgetState.mEnd } // @TODO: add description fun getInterpolated(id: String?): WidgetFrame { val widgetState: WidgetState = mState[id] ?: return null!! return widgetState.mInterpolated } // @TODO: add description fun getPath(id: String?): FloatArray { val widgetState: WidgetState = mState[id]!! val duration = 1000 val frames = duration / 16 val mPoints = FloatArray(frames * 2) widgetState.mMotionControl.buildPath(mPoints, frames) return mPoints } // @TODO: add description fun getKeyFrames( id: String?, rectangles: FloatArray?, pathMode: IntArray?, position: IntArray?, ): Int { val widgetState: WidgetState = mState[id]!! return widgetState.mMotionControl.buildKeyFrames(rectangles, pathMode, position) } @Suppress("unused") private fun getWidgetState(widgetId: String): WidgetState? { return mState[widgetId] } fun getWidgetState( widgetId: String?, child: ConstraintWidget?, transitionState: Int, ): WidgetState { var widgetState: WidgetState? = mState[widgetId] if (widgetState == null) { widgetState = WidgetState() mBundle.applyDelta(widgetState.mMotionControl) widgetState.mMotionWidgetStart.updateMotion(widgetState.mMotionControl) mState[widgetId!!] = widgetState if (child != null) { widgetState.update(child, transitionState) } } return widgetState } /** * Used in debug draw */ fun getStart(child: ConstraintWidget): WidgetFrame { return getWidgetState(child.stringId, null, START).mStart } /** * Used in debug draw */ fun getEnd(child: ConstraintWidget): WidgetFrame { return getWidgetState(child.stringId, null, END).mEnd } /** * Used after the interpolation */ fun getInterpolated(child: ConstraintWidget): WidgetFrame { return getWidgetState(child.stringId, null, INTERPOLATED).mInterpolated } /** * This gets the interpolator being used */ fun getInterpolator(): Interpolator? { return getInterpolator(mDefaultInterpolator, mDefaultInterpolatorString) } /** * This gets the auto transition mode being used */ fun getAutoTransition(): Int { return mAutoTransition } fun calcStagger() { if (mStagger == 0.0f) { return } val flip = mStagger < 0.0 val stagger = abs(mStagger) var min = Float.MAX_VALUE var max = -Float.MAX_VALUE var useMotionStagger = false for (widgetId in mState.keys) { val widgetState = mState[widgetId] val f: Motion = widgetState!!.mMotionControl if (!f.getMotionStagger().isNaN()) { useMotionStagger = true break } } if (useMotionStagger) { for (widgetId in mState.keys) { val widgetState = mState[widgetId] val f: Motion = widgetState!!.mMotionControl val widgetStagger: Float = f.getMotionStagger() if (!widgetStagger.isNaN()) { min = min(min, widgetStagger) max = max(max, widgetStagger) } } for (widgetId in mState.keys) { val widgetState = mState[widgetId] val f: Motion = widgetState!!.mMotionControl val widgetStagger: Float = f.getMotionStagger() if (!widgetStagger.isNaN()) { val scale = 1 / (1 - stagger) var offset = stagger - stagger * (widgetStagger - min) / (max - min) if (flip) { offset = stagger - stagger * (max - widgetStagger) / (max - min) } f.setStaggerScale(scale) f.setStaggerOffset(offset) } } } else { for (widgetId in mState.keys) { val widgetState = mState[widgetId] val f: Motion = widgetState!!.mMotionControl val x: Float = f.getFinalX() val y: Float = f.getFinalY() val widgetStagger = x + y min = min(min, widgetStagger) max = max(max, widgetStagger) } for (widgetId in mState.keys) { val widgetState = mState[widgetId] val f: Motion = widgetState!!.mMotionControl val x: Float = f.getFinalX() val y: Float = f.getFinalY() val widgetStagger = x + y var offset = stagger - stagger * (widgetStagger - min) / (max - min) if (flip) { offset = stagger - stagger * (max - widgetStagger) / (max - min) } val scale = 1 / (1 - stagger) f.setStaggerScale(scale) f.setStaggerOffset(offset) } } } class OnSwipe { var mAnchorId: String? = null private var mAnchorSide = 0 private var mEngine: StopEngine? = null @Suppress("unused") private var mRotationCenterId: String? = null var mLimitBoundsTo: String? = null @Suppress("unused") private var mDragVertical = true private var mDragDirection = 0 private var mDragScale = 1f @Suppress("unused") private var mDragThreshold = 10f private var mAutoCompleteMode = 0 private var mMaxVelocity = 4f private var mMaxAcceleration = 1.2f // On touch up what happens private var mOnTouchUp = 0 private var mSpringMass = 1f private var mSpringStiffness = 400f private var mSpringDamping = 10f private var mSpringStopThreshold = 0.01f private var mDestination = 0.0f // In spring mode what happens at the boundary private var mSpringBoundary = 0 private var mStart: Long = 0 fun getScale(): Float { return mDragScale } fun getDirection(): FloatArray { return TOUCH_DIRECTION[mDragDirection] } fun getSide(): FloatArray { return TOUCH_SIDES[mAnchorSide] } fun setAnchorId(anchorId: String?) { mAnchorId = anchorId } fun setAnchorSide(anchorSide: Int) { mAnchorSide = anchorSide } fun setRotationCenterId(rotationCenterId: String?) { mRotationCenterId = rotationCenterId } fun setLimitBoundsTo(limitBoundsTo: String?) { mLimitBoundsTo = limitBoundsTo } fun setDragDirection(dragDirection: Int) { mDragDirection = dragDirection mDragVertical = mDragDirection < 2 } fun setDragScale(dragScale: Float) { if (dragScale.isNaN()) { return } mDragScale = dragScale } fun setDragThreshold(dragThreshold: Float) { if (dragThreshold.isNaN()) { return } mDragThreshold = dragThreshold } fun setAutoCompleteMode(mAutoCompleteMode: Int) { this.mAutoCompleteMode = mAutoCompleteMode } fun setMaxVelocity(maxVelocity: Float) { if (maxVelocity.isNaN()) { return } mMaxVelocity = maxVelocity } fun setMaxAcceleration(maxAcceleration: Float) { if (maxAcceleration.isNaN()) { return } mMaxAcceleration = maxAcceleration } fun setOnTouchUp(onTouchUp: Int) { mOnTouchUp = onTouchUp } fun setSpringMass(mSpringMass: Float) { if (mSpringMass.isNaN()) { return } this.mSpringMass = mSpringMass } fun setSpringStiffness(mSpringStiffness: Float) { if (mSpringStiffness.isNaN()) { return } this.mSpringStiffness = mSpringStiffness } fun setSpringDamping(mSpringDamping: Float) { if (mSpringDamping.isNaN()) { return } this.mSpringDamping = mSpringDamping } fun setSpringStopThreshold(mSpringStopThreshold: Float) { if (mSpringStopThreshold.isNaN()) { return } this.mSpringStopThreshold = mSpringStopThreshold } fun setSpringBoundary(mSpringBoundary: Int) { this.mSpringBoundary = mSpringBoundary } fun getDestinationPosition( currentPosition: Float, velocity: Float, duration: Float, ): Float { val rest = currentPosition + 0.5f * abs(velocity) * velocity / mMaxAcceleration when (mOnTouchUp) { ON_UP_AUTOCOMPLETE_TO_START -> { return if (currentPosition >= 1f) { 1f } else { 0f } } ON_UP_NEVER_COMPLETE_TO_END -> return 0f ON_UP_AUTOCOMPLETE_TO_END -> { return if (currentPosition <= 0f) { 0f } else { 1f } } ON_UP_NEVER_COMPLETE_TO_START -> return 1f ON_UP_STOP -> return Float.NaN ON_UP_DECELERATE -> return max(0f, min(1f, rest)) ON_UP_DECELERATE_AND_COMPLETE -> return if (rest > 0.2f && rest < 0.8f) { rest } else { if (rest > .5f) 1f else 0f } ON_UP_AUTOCOMPLETE -> {} } if (DEBUG) { Utils.log(" currentPosition = $currentPosition") Utils.log(" velocity = $velocity") Utils.log(" peek = $rest") Utils.log("mMaxAcceleration = $mMaxAcceleration") } return if (rest > .5) 1f else 0f } fun config(position: Float, velocity: Float, start: Long, duration: Float) { var velocity = velocity mStart = start if (abs(velocity) > mMaxVelocity) { velocity = mMaxVelocity * sign(velocity) } mDestination = getDestinationPosition(position, velocity, duration) if (mDestination == position) { mEngine = null return } if (mOnTouchUp == ON_UP_DECELERATE && mAutoCompleteMode == MODE_CONTINUOUS_VELOCITY) { val sld: Decelerate if (mEngine is Decelerate) { sld = mEngine as Decelerate } else { sld = Decelerate() mEngine = sld } sld.config(position, mDestination, velocity) return } if (mAutoCompleteMode == MODE_CONTINUOUS_VELOCITY) { val sl: StopLogicEngine if (mEngine is StopLogicEngine) { sl = mEngine as StopLogicEngine } else { sl = StopLogicEngine() mEngine = sl } sl.config( position, mDestination, velocity, duration, mMaxAcceleration, mMaxVelocity, ) return } val sl: SpringStopEngine if (mEngine is SpringStopEngine) { sl = mEngine as SpringStopEngine } else { sl = SpringStopEngine() mEngine = sl } sl.springConfig( position, mDestination, velocity, mSpringMass, mSpringStiffness, mSpringDamping, mSpringStopThreshold, mSpringBoundary, ) } /** * @param currentTime time in nanoseconds * @return new values of progress */ fun getTouchUpProgress(currentTime: Long): Float { val time = (currentTime - mStart) * 1E-9f var pos: Float = mEngine!!.getInterpolation(time) if (mEngine!!.isStopped) { pos = mDestination } return pos } fun printInfo() { if (mAutoCompleteMode == MODE_CONTINUOUS_VELOCITY) { println("velocity = " + mEngine!!.velocity) println("mMaxAcceleration = $mMaxAcceleration") println("mMaxVelocity = $mMaxVelocity") } else { println("mSpringMass = $mSpringMass") println("mSpringStiffness = $mSpringStiffness") println("mSpringDamping = $mSpringDamping") println("mSpringStopThreshold = $mSpringStopThreshold") println("mSpringBoundary = $mSpringBoundary") } } fun isNotDone(progress: Float): Boolean { return if (mOnTouchUp == ON_UP_STOP) { false } else { mEngine != null && !mEngine!!.isStopped } } companion object { const val ANCHOR_SIDE_TOP = 0 const val ANCHOR_SIDE_LEFT = 1 const val ANCHOR_SIDE_RIGHT = 2 const val ANCHOR_SIDE_BOTTOM = 3 const val ANCHOR_SIDE_MIDDLE = 4 const val ANCHOR_SIDE_START = 5 const val ANCHOR_SIDE_END = 6 val SIDES = arrayOf( "top", "left", "right", "bottom", "middle", "start", "end", ) private val TOUCH_SIDES = arrayOf( floatArrayOf(0.5f, 0.0f), floatArrayOf(0.0f, 0.5f), floatArrayOf(1.0f, 0.5f), floatArrayOf(0.5f, 1.0f), floatArrayOf(0.5f, 0.5f), floatArrayOf(0.0f, 0.5f), floatArrayOf(1.0f, 0.5f), ) const val DRAG_UP = 0 const val DRAG_DOWN = 1 const val DRAG_LEFT = 2 const val DRAG_RIGHT = 3 const val DRAG_START = 4 const val DRAG_END = 5 const val DRAG_CLOCKWISE = 6 const val DRAG_ANTICLOCKWISE = 7 val DIRECTIONS = arrayOf( "up", "down", "left", "right", "start", "end", "clockwise", "anticlockwise", ) const val MODE_CONTINUOUS_VELOCITY = 0 const val MODE_SPRING = 1 val MODE = arrayOf("velocity", "spring") const val ON_UP_AUTOCOMPLETE = 0 const val ON_UP_AUTOCOMPLETE_TO_START = 1 const val ON_UP_AUTOCOMPLETE_TO_END = 2 const val ON_UP_STOP = 3 const val ON_UP_DECELERATE = 4 const val ON_UP_DECELERATE_AND_COMPLETE = 5 const val ON_UP_NEVER_COMPLETE_TO_START = 6 const val ON_UP_NEVER_COMPLETE_TO_END = 7 val TOUCH_UP = arrayOf( "autocomplete", "toStart", "toEnd", "stop", "decelerate", "decelerateComplete", "neverCompleteStart", "neverCompleteEnd", ) const val BOUNDARY_OVERSHOOT = 0 const val BOUNDARY_BOUNCE_START = 1 const val BOUNDARY_BOUNCE_END = 2 const val BOUNDARY_BOUNCE_BOTH = 3 val BOUNDARY = arrayOf( "overshoot", "bounceStart", "bounceEnd", "bounceBoth", ) private val TOUCH_DIRECTION = arrayOf( floatArrayOf(0.0f, -1.0f), floatArrayOf(0.0f, 1.0f), floatArrayOf(-1.0f, 0.0f), floatArrayOf(1.0f, 0.0f), floatArrayOf(-1.0f, 0.0f), floatArrayOf(1.0f, 0.0f), ) } } companion object { private const val DEBUG = false const val START = 0 const val END = 1 const val INTERPOLATED = 2 const val EASE_IN_OUT = 0 const val EASE_IN = 1 const val EASE_OUT = 2 const val LINEAR = 3 const val BOUNCE = 4 const val OVERSHOOT = 5 const val ANTICIPATE = 6 private const val SPLINE_STRING = -1 @Suppress("unused") private val INTERPOLATOR_REFERENCE_ID = -2 /** * get the interpolater based on a constant or a string */ fun getInterpolator(interpolator: Int, interpolatorString: String?): Interpolator? { when (interpolator) { SPLINE_STRING -> return Interpolator { v: Float -> Easing.getInterpolator( interpolatorString, )!!.get(v.toDouble()).toFloat() } EASE_IN_OUT -> return Interpolator { v: Float -> Easing.getInterpolator( "standard", )!!.get(v.toDouble()).toFloat() } EASE_IN -> return Interpolator { v: Float -> Easing.getInterpolator( "accelerate", )!!.get(v.toDouble()).toFloat() } EASE_OUT -> return Interpolator { v: Float -> Easing.getInterpolator( "decelerate", )!!.get(v.toDouble()).toFloat() } LINEAR -> return Interpolator { v: Float -> Easing.getInterpolator( "linear", )!!.get(v.toDouble()).toFloat() } ANTICIPATE -> return Interpolator { v: Float -> Easing.getInterpolator( "anticipate", )!!.get(v.toDouble()).toFloat() } OVERSHOOT -> return Interpolator { v: Float -> Easing.getInterpolator( "overshoot", )!!.get(v.toDouble()).toFloat() } BOUNCE -> return Interpolator { v: Float -> Easing.getInterpolator( "spline(0.0, 0.2, 0.4, 0.6, " + "0.8 ,1.0, 0.8, 1.0, 0.9, 1.0)", )!!.get(v.toDouble()).toFloat() } } return null } class WidgetState { var mStart: WidgetFrame var mEnd: WidgetFrame var mInterpolated: WidgetFrame var mMotionControl: Motion var mNeedSetup = true var mMotionWidgetStart: MotionWidget var mMotionWidgetEnd: MotionWidget var mMotionWidgetInterpolated: MotionWidget var mKeyCache: KeyCache = KeyCache() var mParentHeight = -1 var mParentWidth = -1 constructor() { mStart = WidgetFrame() mEnd = WidgetFrame() mInterpolated = WidgetFrame() mMotionWidgetStart = MotionWidget(mStart) mMotionWidgetEnd = MotionWidget(mEnd) mMotionWidgetInterpolated = MotionWidget(mInterpolated) mMotionControl = Motion(mMotionWidgetStart) mMotionControl.setStart(mMotionWidgetStart) mMotionControl.setEnd(mMotionWidgetEnd) } fun setKeyPosition(prop: TypedBundle) { val keyPosition = MotionKeyPosition() prop.applyDelta(keyPosition) mMotionControl.addKey(keyPosition) } fun setKeyAttribute(prop: TypedBundle) { val keyAttributes = MotionKeyAttributes() prop.applyDelta(keyAttributes) mMotionControl.addKey(keyAttributes) } /** * Set tge keyAttribute bundle and associated custom attributes * @param prop * @param custom */ fun setKeyAttribute(prop: TypedBundle, custom: Array<CustomVariable?>?) { val keyAttributes = MotionKeyAttributes() prop.applyDelta(keyAttributes) if (custom != null) { for (i in custom.indices) { custom[i]?.let { customVariable -> keyAttributes.mCustom?.set(customVariable.getName(), customVariable) } } } mMotionControl.addKey(keyAttributes) } fun setKeyCycle(prop: TypedBundle) { val keyAttributes = MotionKeyCycle() prop.applyDelta(keyAttributes) mMotionControl.addKey(keyAttributes) } fun update(child: ConstraintWidget?, state: Int) { if (state == START) { mStart.update(child) mMotionWidgetStart.updateMotion(mMotionWidgetStart) mMotionControl.setStart(mMotionWidgetStart) mNeedSetup = true } else if (state == END) { mEnd.update(child) mMotionControl.setEnd(mMotionWidgetEnd) mNeedSetup = true } mParentWidth = -1 } /** * Return the id of the widget to animate relative to * * @return id of widget or null */ fun getPathRelativeId(): String? { return mMotionControl.getAnimateRelativeTo() } fun getFrame(type: Int): WidgetFrame { if (type == START) { return mStart } else if (type == END) { return mEnd } return mInterpolated } fun interpolate( parentWidth: Int, parentHeight: Int, progress: Float, transition: Transition?, ) { // TODO only update if parentHeight != mParentHeight || parentWidth != mParentWidth) { mParentHeight = parentHeight mParentWidth = parentWidth if (mNeedSetup) { mMotionControl.setup( parentWidth, parentHeight, 1f, System.nanoTime(), ) mNeedSetup = false } WidgetFrame.interpolate( parentWidth, parentHeight, mInterpolated, mStart, mEnd, transition!!, progress, ) mInterpolated.interpolatedPos = progress mMotionControl.interpolate( mMotionWidgetInterpolated, progress, System.nanoTime(), mKeyCache, ) } fun setPathRelative(widgetState: WidgetState) { mMotionControl.setupRelative(widgetState.mMotionControl) } } } }
3
Kotlin
0
21
98f52234fe6c8782f0f0d9ab9a794adf71492cda
42,000
constraintlayout-compose-multiplatform
Apache License 2.0
app/src/main/java/com/example/a99password/domain/Password.kt
CardosofGui
463,670,540
false
{"Kotlin": 71313}
package com.example.a99password.domain import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity(tableName = "password_table") data class Password( @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id_password") val id : Int?, @ColumnInfo(name = "password_name") val passwordName : String, @ColumnInfo(name = "password_email") val passwordEmail : String, @ColumnInfo(name = "password_password") val passwordPassword : String )
0
Kotlin
0
1
5eb4c4ae005d1d048e2637fab2c9cae41d7f3d78
490
99Password
MIT License
orchestration/stock/src/main/kotlin/com/example/stock/infra/ProductResource.kt
luramarchanjo
210,160,105
false
{"Kotlin": 35075}
package com.example.stock.infra import com.example.stock.domain.ProductService import org.slf4j.LoggerFactory import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/v1/products") class ProductResource(val productService: ProductService) { private val log = LoggerFactory.getLogger(this::class.java) @PostMapping fun post(@RequestBody request: ProductPostRequest): ResponseEntity<ProductResponse> { log.info("Receiving a POST /v1/products") val product = productService.create(request.name, request.value, request.quantity) val response = ProductResponse(product.id, product.name, product.value, product.quantity) log.info("Received a POST /v1/products") return ResponseEntity.status(HttpStatus.CREATED).body(response) } @GetMapping @ResponseStatus(HttpStatus.ACCEPTED) fun getAll() = productService.listAll() }
3
Kotlin
2
0
b47c5ec71ac006ecf510adf45e98601ea846141b
1,003
poc-saga-pattern
Apache License 2.0
src/main/kotlin/com/kotakotik/discordchat/messageQueue.kt
kotakotik22
517,670,749
false
{"Kotlin": 75059}
package com.kotakotik.discordchat import dev.kord.core.Kord import dev.kord.core.behavior.channel.createMessage import dev.kord.core.behavior.execute import dev.kord.core.entity.Webhook import dev.kord.core.entity.channel.TextChannel import dev.kord.rest.builder.message.create.UserMessageCreateBuilder import dev.kord.rest.builder.message.create.WebhookMessageCreateBuilder import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.Channel.Factory.UNLIMITED class QueueContext(val kord: Kord, val webhook: Webhook, val channel: TextChannel) { val webhookToken = webhook.token ?: error("webhook should have token") } fun interface QueueAction { suspend fun QueueContext.executeInQueue() } val queueChannel = Channel<QueueAction>(capacity = UNLIMITED) suspend fun setUpQueueReceiver(kord: Kord, webhook: Webhook, channel: TextChannel) { val ctx = QueueContext(kord, webhook, channel) logger.info("Receiving from queue") for (msg in queueChannel) { with(msg) { ctx.executeInQueue() } } logger.info("Queue channel closed, cleaning up") channel.createMessage(Config.Messages.serverStopping) discordContext.close() } suspend fun enqueue(action: QueueAction) = queueChannel.send(action) suspend inline fun enqueueBotMessage(crossinline builder: suspend UserMessageCreateBuilder.() -> Unit) = enqueue { channel.createMessage { builder() } } suspend inline fun enqueueWebhookMessage(crossinline builder: suspend WebhookMessageCreateBuilder.() -> Unit) = enqueue { webhook.execute(webhookToken) { builder() } }
0
Kotlin
0
0
890af4d68882bcd4b52b4bae1173fc69854f8b0c
1,671
discordchat
MIT License
src/main/kotlin/org/jetbrains/teamcity/rest/models/buildType/Investigation.kt
JetBrains
321,975,548
false
{"Kotlin": 638039}
/** * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package org.jetbrains.teamcity.rest.models import com.google.gson.annotations.SerializedName import org.jetbrains.teamcity.rest.base.* import org.jetbrains.teamcity.rest.infrastructure.ApiClient import org.jetbrains.teamcity.rest.infrastructure.RequestConfig import java.time.LocalDateTime /** Represents an investigation on build problem. * @param id * @param state * @param href * @param assignee * @param assignment * @param scope * @param target * @param resolution * @param responsible */ data class Investigation( @SerializedName("id") val id: String? = null, @SerializedName("state") val state: String? = null, @SerializedName("href") override val href: String? = null, @SerializedName("assignee") val assignee: User? = null, @SerializedName("assignment") val assignment: Comment? = null, @SerializedName("scope") val scope: ProblemScope? = null, @SerializedName("target") val target: ProblemTarget? = null, @SerializedName("resolution") val resolution: Resolution? = null, @SerializedName("responsible") val responsible: User? = null ) : DataEntity() { @Transient private val classModelName: String = "investigation" }
0
Kotlin
1
1
0e29bfb12d0d17c481c295d8ec89815a4a9fb0c2
1,361
teamcity-rest-auto-kotlin-client
Apache License 2.0
BasicMarkdownParser.kt
ycannot
504,123,004
false
{"Kotlin": 3107}
/** * @author <NAME> (ycannot, https://github.com/ycannot) * @date 14.06.2022 */ import android.graphics.Color import android.text.Spannable import android.text.SpannableStringBuilder import android.text.style.ForegroundColorSpan import android.text.style.UnderlineSpan import androidx.annotation.ColorInt import androidx.annotation.Keep import androidx.core.text.toSpannable object BasicMarkdownParser { val highlightIndicator = "::" val underlineIndicator = "__" private const val defaultColorCode = "#654FD3" @ColorInt var highlightColor = Color.parseColor(defaultColorCode) private val specialCharset = arrayOf(highlightIndicator, underlineIndicator) fun parseMarkdown(s: String): Spannable { var temp = s val recurrences = arrayListOf<Recurrence>() specialCharset.forEach { specialChar -> temp = temp.replace(specialChar, "") recurrences.addAll(extractRecurrences(s, specialChar)) } val attributed = SpannableStringBuilder(temp) recurrences.forEach { recurrence -> when (recurrence.stylingChar) { highlightIndicator -> { attributed.setSpan( ForegroundColorSpan(highlightColor), recurrence.startIndex, recurrence.endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE ) } underlineIndicator -> { attributed.setSpan( UnderlineSpan(), recurrence.startIndex, recurrence.endIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE ) } } } return attributed.toSpannable() } private fun extractRecurrences( s: String, specialChar: String ): ArrayList<Recurrence> { val regex = Regex("\\$specialChar(.*?)\\$specialChar") return regex.findAll(s).mapTo(arrayListOf()) { match -> val startIndex = calculateRefinedStartIndex(s, match) val endIndex = startIndex + match.value.length specialCharset.forEach { endIndex -= match.value.count(it) } Recurrence( match.value, startIndex, endIndex, specialChar ) } } private fun calculateRefinedStartIndex( s: String, recurrence: MatchResult ): Int { val rawIndex = recurrence.range.first var specialCharCountBefore = 0 specialCharset.forEach { specialCharCountBefore += s.substring(0, rawIndex).count(it) } return rawIndex - specialCharCountBefore } fun String.count(s: String): Int{ return this.split(s).size - 1 } @Keep private data class Recurrence( val recurrence: String, val startIndex: Int, val endIndex: Int, val stylingChar: String ) }
0
Kotlin
0
1
35b3b0d6ecb8db079d0de1eab6a56cca68778e3f
3,107
basic-markdown-parser-android
Apache License 2.0
src/main/kotlin/org/wildfly/modelgraph/browser/Model.kt
model-graph-tools
352,568,285
false
null
package org.wildfly.modelgraph.browser import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable const val SINGLETON_PARENT_TYPE: String = "SingletonParentResource" interface Typed { val type: String val valueType: String? } interface WithDeprecated { val deprecation: Deprecation? val deprecated: Boolean get() = deprecation != null } @Serializable sealed class Model { abstract val id: String abstract val name: String abstract val modelType: String } @Serializable data class Models( val attributes: List<Attribute> = emptyList(), val capabilities: List<Capability> = emptyList(), val operations: List<Operation> = emptyList(), val resources: List<Resource> = emptyList() ) { val models: List<Model> get() = attributes + capabilities + operations + resources val size: Int get() = attributes.size + capabilities.size + operations.size + resources.size override fun toString(): String = "Models(a(${attributes.size}),c(${capabilities.size}),o(${operations.size}),r(${resources.size})" } @Serializable @SerialName("Attribute") data class Attribute( override val id: String, override val name: String, override val modelType: String, // required properties override val type: String, // optional properties val accessType: String? = null, val alias: String? = null, val attributeGroup: String? = null, val defaultValue: String? = null, val description: String? = null, val expressionAllowed: Boolean = false, val max: Long = 0, val maxLength: Long = 0, val min: Long = 0, val minLength: Long = 0, val nillable: Boolean = false, val required: Boolean = false, val restartRequired: String? = null, val since: String? = null, val storage: String? = null, val unit: String? = null, override val valueType: String? = null, override val deprecation: Deprecation? = null, // references val attributes: List<Attribute> = emptyList(), val alternatives: List<String> = emptyList(), val capability: String? = null, val definedIn: String? = null, val requires: List<String> = emptyList(), ) : Model(), Typed, WithDeprecated @Serializable @SerialName("Capability") data class Capability( override val id: String, override val name: String, override val modelType: String, val declaredBy: List<String> = emptyList(), ) : Model() @Serializable @SerialName("Deprecation") data class Deprecation( override val modelType: String, val reason: String, val since: Version ) : Model() { override val id: String = "" override val name: String = "" } @Serializable @SerialName("Operation") data class Operation( override val id: String, override val name: String, override val modelType: String, // required properties val global: Boolean, // optional properties val description: String? = null, val readOnly: Boolean = false, val returnValue: String? = null, val valueType: String? = null, val runtimeOnly: Boolean = false, override val deprecation: Deprecation? = null, // relations val parameters: List<Parameter> = emptyList(), val providedBy: String? = null, ) : Model(), WithDeprecated { companion object { var globalOperations: List<Operation> = emptyList() } } @Serializable @SerialName("Parameter") data class Parameter( override val id: String, override val name: String, override val modelType: String, // required properties override val type: String, // optional properties val description: String? = null, val expressionAllowed: Boolean = false, val max: Long = 0, val maxLength: Long = 0, val min: Long = 0, val minLength: Long = 0, val nillable: Boolean = false, val required: Boolean = false, val since: String? = null, val unit: String? = null, override val valueType: String? = null, override val deprecation: Deprecation? = null, // references val alternatives: List<String> = emptyList(), val capability: String? = null, val parameters: List<Parameter> = emptyList(), val requires: List<String> = emptyList(), ) : Model(), Typed, WithDeprecated @Serializable @SerialName("Resource") data class Resource( override val id: String, override val name: String, override val modelType: String, // required properties val address: String, val singleton: Boolean, val childDescriptions: Map<String, String> = emptyMap(), // optional properties val description: String? = null, override val deprecation: Deprecation? = null, // references val parent: Resource? = null, val children: List<Resource> = emptyList(), val attributes: List<Attribute> = emptyList(), val capabilities: List<Capability> = emptyList(), val operations: List<Operation> = emptyList(), ) : Model(), WithDeprecated { val singletonParent: Boolean get() = modelType == SINGLETON_PARENT_TYPE val singletonParentName: String get() = if (singleton) name.substringBefore('=') else name val singletonChildName: String get() = if (singleton) name.substringAfter('=') else name override fun toString(): String = buildString { append("Resource(") append(id) append(", ") append(address) if (singletonParent) { append(", singleton-parent") } else if (singleton) { append(", singleton") } append(")") } companion object { val UNDEFINED = Resource("-1", "n/a", "Resource", "/", true) } } @Serializable @SerialName("Version") data class Version( override val id: String, override val modelType: String, val major: Int, val minor: Int, val patch: Int, ) : Model() { override val name: String = "" fun ordinal(): Int { var ordinal = 0 val numbers = intArrayOf(patch, minor, major) for (i in numbers.indices) { ordinal = ordinal or (numbers[i] shl i * 10) } return ordinal } override fun toString(): String = "$major.$minor.$patch" }
0
Kotlin
0
0
7babdb3137b7ac4699496657e1e29967a1d60b41
6,253
browser
Apache License 2.0
app/src/main/java/com/beettechnologies/newsapp/common/data/db/NewsDao.kt
beetsolutions
162,338,193
false
null
package com.beettechnologies.newsapp.common.data.db import android.arch.persistence.room.Dao import android.arch.persistence.room.Insert import android.arch.persistence.room.OnConflictStrategy import android.arch.persistence.room.Query import com.beettechnologies.newsapp.common.data.model.News import io.reactivex.Flowable @Dao abstract class NewsDao { @Query("""SELECT * FROM News WHERE source = :source""") abstract fun getNews(source: String): Flowable<MutableList<News>> @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun insert(vararg news: News) }
0
Kotlin
0
0
eb9b43f28e3c23385710e6b10199a38bad70efed
585
newsapp
MIT License
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/combat/specialattack/weapons/ranged/magic_shortbow.plugin.kts
andtheysay
283,298,024
true
{"Kotlin": 3891210, "Dockerfile": 1354}
package gg.rsmod.plugins.content.combat.specialattack.weapons.ranged import gg.rsmod.plugins.content.combat.createProjectile import gg.rsmod.plugins.content.combat.dealHit import gg.rsmod.plugins.content.combat.formula.RangedCombatFormula import gg.rsmod.plugins.content.combat.specialattack.ExecutionType import gg.rsmod.plugins.content.combat.specialattack.SpecialAttacks import gg.rsmod.plugins.content.combat.strategy.RangedCombatStrategy import gg.rsmod.plugins.content.combat.strategy.ranged.RangedProjectile val SPECIAL_REQUIREMENT = 55 SpecialAttacks.register(intArrayOf(Items.MAGIC_SHORTBOW, Items.MAGIC_SHORTBOW_I), SPECIAL_REQUIREMENT, ExecutionType.EXECUTE_ON_ATTACK) { player.animate(1074) for (i in 0 until 2) { fireMagicArrow(player, target, i) } } fun fireMagicArrow(player: Player, target : Pawn, extraDelay : Int = 0) { val world = player.world val ammo = player.getEquipment(EquipmentType.AMMO) val ammoProjectile = if (ammo != null) RangedProjectile.values.firstOrNull { it == RangedProjectile.MAGIC_ARROW } else null if (ammoProjectile != null) { val projectile = player.createProjectile(target, ammoProjectile.gfx, ammoProjectile.type, extraDelay = extraDelay*ammoProjectile.type.delay) ammoProjectile.drawback?.let { drawback -> drawback.delay = (extraDelay*ammoProjectile.type.delay) player.graphic(drawback) } world.spawn(projectile) world.spawn(AreaSound(tile = player.tile, id = 2693, radius = 10, volume = 1)) val maxHit = RangedCombatFormula.getMaxHit(player, target) val accuracy = RangedCombatFormula.getAccuracy(player, target) val landHit = accuracy >= world.randomDouble() val delay = RangedCombatStrategy.getHitDelay(target.getCentreTile(), target.tile.transform(target.getSize() / 2, target.getSize() / 2))/2 player.dealHit(target = target, maxHit = maxHit, landHit = landHit, delay = delay +1) } }
0
Kotlin
0
0
ff6ba961acf3905a89746682b3e7c2eaad558bf5
2,002
rsmod
Apache License 2.0
app/src/main/java/io/github/armcha/sample/data/DataSource.kt
armcha
122,985,858
false
null
package io.github.armcha.sample.data object DataSource { val items by lazy { mutableListOf<Item>().apply { repeat(5) { add(Item("Google", "http://diylogodesigns.com/blog/wp-content/uploads/2016/04/google-logo-icon-PNG-Transparent-Background-768x768.png")) add(Item("Beach", "https://cdn.pixabay.com/photo/2017/11/15/20/17/beach-2952391_640.jpg")) add(Item("Strawberries", "https://cdn.pixabay.com/photo/2016/05/16/17/59/strawberries-1396330_640.jpg")) add(Item("Flower", "https://cdn.pixabay.com/photo/2018/02/08/22/27/flower-3140492_640.jpg")) add(Item("Pension", "https://cdn.pixabay.com/photo/2018/02/07/14/27/pension-3137209_640.jpg")) add(Item("Poppy", "https://cdn.pixabay.com/photo/2018/02/07/17/53/poppy-3137588_640.jpg")) add(Item("Dance", "https://cdn.pixabay.com/photo/2018/02/06/14/07/dance-3134828_640.jpg")) add(Item("Substances", "https://cdn.pixabay.com/photo/2012/04/26/22/31/substances-43354_640.jpg")) add(Item("Mediterranean", "https://cdn.pixabay.com/photo/2017/06/06/22/46/mediterranean-cuisine-2378758_640.jpg")) add(Item("Easter", "https://cdn.pixabay.com/photo/2018/02/01/19/21/easter-3123834_640.jpg")) add(Item("Paint", "https://cdn.pixabay.com/photo/2017/11/29/09/15/paint-2985569_640.jpg")) add(Item("Strawberry", "https://cdn.pixabay.com/photo/2017/11/18/17/09/strawberry-2960533_640.jpg")) add(Item("Flower", "https://cdn.pixabay.com/photo/2017/11/05/00/46/flower-2919284_640.jpg")) add(Item("Peppers", "https://cdn.pixabay.com/photo/2017/09/25/20/44/peppers-2786684_640.jpg")) add(Item("Blue", "https://cdn.pixabay.com/photo/2017/09/01/21/53/blue-2705642_640.jpg")) add(Item("Sea", "https://cdn.pixabay.com/photo/2017/05/31/18/38/sea-2361247_640.jpg")) add(Item("Christmas", "https://cdn.pixabay.com/photo/2017/12/05/16/39/decorating-christmas-tree-2999722_640.jpg")) add(Item("Abstract", "https://cdn.pixabay.com/photo/2017/10/12/20/12/abstract-2845763_640.jpg")) add(Item("Nature", "https://cdn.pixabay.com/photo/2018/02/02/22/28/nature-3126513_640.jpg")) add(Item("Lens", "https://cdn.pixabay.com/photo/2018/01/28/21/14/lens-3114729_640.jpg")) add(Item("Woman", "https://cdn.pixabay.com/photo/2018/01/27/05/49/woman-3110483_640.jpg")) add(Item("Sea", "https://cdn.pixabay.com/photo/2018/01/31/16/27/sea-3121435_640.jpg")) add(Item("Architecture", "https://cdn.pixabay.com/photo/2018/01/31/12/16/architecture-3121009_640.jpg")) add(Item("Bird", "https://cdn.pixabay.com/photo/2018/01/28/14/41/bird-3113835_640.jpg")) add(Item("Nature", "https://cdn.pixabay.com/photo/2018/01/28/11/24/nature-3113318_640.jpg")) add(Item("Gallery", "https://cdn.pixabay.com/photo/2018/01/28/17/48/gallery-3114279_640.jpg")) add(Item("Jeans", "https://cdn.pixabay.com/photo/2017/11/26/19/50/jeans-2979818_640.jpg")) add(Item("Food photography", "https://cdn.pixabay.com/photo/2017/10/09/19/29/food-photography-2834549_640.jpg")) add(Item("Polynesia", "https://cdn.pixabay.com/photo/2017/12/15/13/51/polynesia-3021072_640.jpg")) add(Item("Girl", "https://cdn.pixabay.com/photo/2016/11/13/00/40/girl-1820122_640.jpg")) } } } }
6
Kotlin
46
461
2c83a49395923e7b17e61643ccade3bb82926129
3,568
ColoredShadowImageView
Apache License 2.0
ambassador-storage/src/main/kotlin/com/roche/ambassador/storage/project/ProjectGroupProjection.kt
Roche
409,076,487
false
{"Kotlin": 747718, "Smarty": 5180, "Dockerfile": 850, "Shell": 72}
package com.roche.ambassador.storage.project import com.roche.ambassador.model.group.Group import org.springframework.beans.factory.annotation.Value interface ProjectGroupProjection { fun getGroupId(): Long fun getScore(): Double fun getCriticality(): Double fun getActivity(): Double fun getStars(): Int fun getForks(): Int fun getType(): Group.Type @Value("#{target.projects.split(\",\")}") fun getProjectIds(): List<String> // FIXME handy workaround, cause it's not that easy to make a list of longs out of it }
12
Kotlin
0
17
4ade31a957e7eb7c66db82a96857d399ce30869d
553
the-ambassador
Apache License 2.0
technocracy.foundation/src/main/kotlin/net/cydhra/technocracy/foundation/client/gui/multiblock/BaseMultiblockTab.kt
frozolotl
206,179,330
true
{"Kotlin": 789585}
package net.cydhra.technocracy.foundation.client.gui.multiblock import net.cydhra.technocracy.foundation.client.gui.TCGui import net.cydhra.technocracy.foundation.client.gui.tabs.TCTab import net.cydhra.technocracy.foundation.tileentity.multiblock.TileEntityMultiBlockPart import net.minecraft.util.ResourceLocation abstract class BaseMultiblockTab(val controller: TileEntityMultiBlockPart<*>, parent: TCGui, icon: ResourceLocation) : TCTab(name = controller.blockType.localizedName, parent = parent, icon = icon) { }
0
Kotlin
0
0
5edb6a699cd39417c4a313d56bacd39077bb23eb
521
Technocracy
MIT License
benchmark_kotlin_mpp/wip/jzlib/ZOutputStream.kt
jtransc
51,313,992
false
null
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */ /* Copyright (c) 2011 ymnk, JCraft,Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The names of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jtransc.compression.jzlib import com.jtransc.annotation.JTranscInvisible import java.io.FilterOutputStream import java.io.IOException import java.lang.Exception /** * ZOutputStream * * deprecated use DeflaterOutputStream or InflaterInputStream */ //@Deprecated @JTranscInvisible class ZOutputStream : FilterOutputStream { protected var bufsize = 512 var flushMode: Int = JZlib.Z_NO_FLUSH protected var buf = ByteArray(bufsize) protected var compress: Boolean protected var out: java.io.OutputStream? private var end = false private var dos: DeflaterOutputStream? = null private var inflater: Inflater? = null constructor(out: java.io.OutputStream?) : super(out) { this.out = out inflater = Inflater() inflater.init() compress = false } @JvmOverloads constructor(out: java.io.OutputStream?, level: Int, nowrap: Boolean = false) : super(out) { this.out = out val deflater = Deflater(level, nowrap) dos = DeflaterOutputStream(out, deflater) compress = true } private val buf1 = ByteArray(1) @Throws(IOException::class) override fun write(b: Int) { buf1[0] = b.toByte() write(buf1, 0, 1) } @Throws(IOException::class) override fun write(b: ByteArray, off: Int, len: Int) { if (len == 0) return if (compress) { dos.write(b, off, len) } else { inflater.setInput(b, off, len, true) var err: Int = JZlib.Z_OK while (inflater.avail_in > 0) { inflater.setOutput(buf, 0, buf.size) err = inflater.inflate(flushMode) if (inflater.next_out_index > 0) out.write(buf, 0, inflater.next_out_index) if (err != JZlib.Z_OK) break } if (err != JZlib.Z_OK) throw ZStreamException("inflating: " + inflater.msg) return } } @Throws(IOException::class) fun finish() { var err: Int if (compress) { val tmp = flushMode var flush: Int = JZlib.Z_FINISH try { write("".toByteArray(), 0, 0) } finally { flush = tmp } } else { dos.finish() } flush() } @Synchronized fun end() { if (end) return if (compress) { try { dos.finish() } catch (e: Exception) { } } else { inflater.end() } end = true } @Throws(IOException::class) override fun close() { try { try { finish() } catch (ignored: IOException) { } } finally { end() out.close() out = null } } val totalIn: Long get() = if (compress) dos.getTotalIn() else inflater.total_in val totalOut: Long get() = if (compress) dos.getTotalOut() else inflater.total_out @Throws(IOException::class) override fun flush() { out.flush() } }
59
Java
66
619
6f9a2166f128c2ce5fb66f9af46fdbdbcbbe4ba4
4,079
jtransc
Apache License 2.0
demo/src/main/java/nl/joery/demo/animatedbottombar/playground/PlaygroundActivity.kt
Droppers
243,871,280
false
null
package nl.joery.demo.animatedbottombar.playground import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.text.Html import android.text.Spanned import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.google.android.material.snackbar.Snackbar import kotlinx.android.synthetic.main.activity_playground.* import nl.joery.animatedbottombar.AnimatedBottomBar import nl.joery.animatedbottombar.BottomBarStyle import nl.joery.demo.animatedbottombar.ExampleActivity import nl.joery.demo.animatedbottombar.R import nl.joery.demo.animatedbottombar.playground.properties.* import nl.joery.demo.animatedbottombar.spPx class PlaygroundActivity : AppCompatActivity() { private lateinit var properties: ArrayList<Property> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_playground) bottom_bar.setBadgeAtTabIndex( 1, AnimatedBottomBar.Badge( text = "99", backgroundColor = Color.RED, textColor = Color.GREEN, textSize = 12.spPx ) ) initProperties() initRecyclerView() view_xml.setOnClickListener { showXmlDialog() } open_examples.setOnClickListener { startActivity(Intent(this, ExampleActivity::class.java)) } } private fun initProperties() { properties = ArrayList() properties.add( CategoryProperty( getString(R.string.category_general) ) ) properties.add( ColorProperty( "backgroundColor" ) ) properties.add( CategoryProperty( getString(R.string.category_tab) ) ) properties.add( EnumProperty( "selectedTabType", AnimatedBottomBar.TabType::class.java ) ) properties.add( ColorProperty( "tabColor" ) ) properties.add( ColorProperty( "tabColorSelected" ) ) properties.add( ColorProperty( "tabColorDisabled" ) ) properties.add( IntegerProperty( "textSize", TypedValue.COMPLEX_UNIT_SP ) ) properties.add( IntegerProperty( "iconSize", TypedValue.COMPLEX_UNIT_DIP ) ) properties.add( BooleanProperty( "rippleEnabled" ) ) properties.add( ColorProperty( "rippleColor" ) ) properties.add( CategoryProperty( getString(R.string.category_indicator) ) ) properties.add( ColorProperty( "indicatorColor" ) ) properties.add( IntegerProperty( "indicatorHeight", TypedValue.COMPLEX_UNIT_DIP ) ) properties.add( IntegerProperty( "indicatorMargin", TypedValue.COMPLEX_UNIT_DIP ) ) properties.add( EnumProperty( "indicatorAppearance", AnimatedBottomBar.IndicatorAppearance::class.java ) ) properties.add( EnumProperty( "indicatorLocation", AnimatedBottomBar.IndicatorLocation::class.java ) ) properties.add( CategoryProperty( getString(R.string.category_animations) ) ) properties.add( IntegerProperty( "animationDuration" ) ) properties.add( InterpolatorProperty( "animationInterpolator" ) ) properties.add( EnumProperty( "tabAnimation", AnimatedBottomBar.TabAnimation::class.java ) ) properties.add( EnumProperty( "tabAnimationSelected", AnimatedBottomBar.TabAnimation::class.java ) ) properties.add( EnumProperty( "indicatorAnimation", AnimatedBottomBar.IndicatorAnimation::class.java ) ) properties.add( CategoryProperty( getString(R.string.category_animations) ) ) properties.add( EnumProperty( "badgeAnimation", AnimatedBottomBar.BadgeAnimation::class.java ) ) properties.add( IntegerProperty( "badgeAnimationDuration" ) ) properties.add( ColorProperty( "badgeBackgroundColor" ) ) properties.add( ColorProperty( "badgeTextColor" ) ) properties.add( IntegerProperty( "badgeTextSize", TypedValue.COMPLEX_UNIT_SP ) ) } private fun initRecyclerView() { recycler.layoutManager = LinearLayoutManager(applicationContext, LinearLayoutManager.VERTICAL, false) recycler.adapter = PropertyAdapter(bottom_bar, properties) } private fun showXmlDialog() { val html = XmlGenerator.generateHtmlXml( "nl.joery.animatedbottombar.AnimatedBottomBar", "abb", bottom_bar, properties, arrayOf(BottomBarStyle.Tab(), BottomBarStyle.Indicator()) ) val layout = LayoutInflater.from(this).inflate(R.layout.view_generated_xml, null) val textView = layout.findViewById<TextView>(R.id.xml) textView.setHorizontallyScrolling(true) textView.text = htmlToSpanned(html) MaterialAlertDialogBuilder(this) .setTitle(R.string.generate_xml_title) .setView(layout) .setPositiveButton(R.string.copy_to_clipboard) { _, _ -> val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager val clip = ClipData.newPlainText(getString(R.string.generate_xml_title), htmlToText(html)) clipboard.setPrimaryClip(clip) Snackbar.make( findViewById<View>(android.R.id.content), R.string.copied_xml_clipboard, Snackbar.LENGTH_LONG ).show() } .show() } private fun htmlToText(html: String): String { return htmlToSpanned(html).toString().replace("\u00A0", " ") } private fun htmlToSpanned(html: String): Spanned { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY) } else { @Suppress("DEPRECATION") Html.fromHtml(html) } } }
25
Kotlin
99
1,258
3b7dd98a70f3d4abff855e8a7e1b71100e24556e
7,749
AnimatedBottomBar
MIT License
app/src/main/java/ir/easazade/dailynotes/sdk/AppContextWrapper.kt
easazade
167,930,367
false
null
package ir.easazade.dailynotes.sdk import android.content.Context import android.content.res.Configuration import android.os.Build import java.util.* class AppContextWrapper { companion object { fun wrap(base: Context?): Context? { //caligraphy setting default font var context: Context? = base //setFab fixed locale //since this app has only one language val locale = Locale("en") Locale.setDefault(locale) val config = Configuration() config.locale = locale if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { context = context?.createConfigurationContext(config) } else { context?.resources?.updateConfiguration(config, context?.resources?.displayMetrics) } //context = CalligraphyContextWrapper.wrap(context) return context } } }
0
Kotlin
0
0
a742f57eff42f972c685345ff553615f6c9a19b2
966
daily-notes
Apache License 2.0
build.gradle.kts
naufalazzaahid
408,368,259
true
{"Kotlin": 1288806, "Lex": 28656, "Ruby": 691, "Shell": 104}
import java.io.ByteArrayOutputStream import org.gradle.api.tasks.testing.logging.TestExceptionFormat import org.jetbrains.configureBintrayPublicationIfNecessary import org.jetbrains.configureSonatypePublicationIfNecessary import org.jetbrains.registerPublicationFromKotlinPlugin import org.jetbrains.signPublicationsIfNecessary plugins { kotlin("multiplatform") version "1.4.10" id("org.jetbrains.dokka") version "1.4.20" id("com.jfrog.bintray") `maven-publish` signing } group = "org.jetbrains" val baseVersion = project.property("version").toString() version = if (project.property("snapshot")?.toString()?.toBoolean() != false) { baseVersion.substringBefore("-").split('.').let { (major, minor, patch) -> "$major.$minor.${patch.toInt() + 1}-SNAPSHOT" } } else { baseVersion } repositories { jcenter() mavenCentral() } kotlin { jvm { compilations { all { kotlinOptions.jvmTarget = "1.6" } val main by getting val test by getting } testRuns["test"].executionTask.configure { useJUnit { excludeCategories("org.intellij.markdown.ParserPerformanceTest") } } } js(BOTH) { nodejs {} } linuxX64() mingwX64() macosX64() // Disabled until test data loading is fixed. iOS tests run on the simulator, and so don't have // access to test resources on the local file system. // ios() sourceSets { val commonMain by getting { } val commonTest by getting { dependencies { implementation(kotlin("test-common")) implementation(kotlin("test-annotations-common")) } } val jvmMain by getting { } val jvmTest by getting { dependencies { implementation(kotlin("test-junit")) } } val jsMain by getting { } val jsTest by getting { dependencies { implementation(kotlin("test-js")) } } val nativeMain by creating { dependsOn(commonMain) } val linuxX64Main by getting { dependsOn(nativeMain) } val mingwX64Main by getting { dependsOn(nativeMain) } val macosX64Main by getting { dependsOn(nativeMain) } // val iosMain by getting { // dependsOn(nativeMain) // } val nativeTest by creating { dependsOn(commonTest) } val linuxX64Test by getting { dependsOn(nativeTest) } val mingwX64Test by getting { dependsOn(nativeTest) } val macosX64Test by getting { dependsOn(nativeTest) } // val iosTest by getting { // dependsOn(nativeTest) // } } } tasks { register<Test>("performanceTest") { val testCompilation = kotlin.jvm().compilations["test"] group = "verification" testClassesDirs = testCompilation.output.classesDirs classpath = testCompilation.runtimeDependencyFiles dependsOn("compileTestKotlinJvm") useJUnit { includeCategories("org.intellij.markdown.ParserPerformanceTest") } testLogging { exceptionFormat = TestExceptionFormat.FULL } } task("downloadCommonmark", type = Exec::class) { group = "Code Generation" description = "Clone the CommonMark repo locally" onlyIf { !File("commonmark-spec").exists() } executable("git") args("clone", "https://github.com/commonmark/commonmark-spec") } task("downloadGfm", type = Exec::class) { group = "Code Generation" description = "Clone the GFM repo locally" onlyIf { !File("cmark-gfm").exists() } executable("git") args("clone", "https://github.com/github/cmark-gfm") } task("generateCommonMarkTest", type = Exec::class) { group = "Code Generation" description = "Generate unit tests for the CommonMark spec" dependsOn("downloadCommonmark") executable("python") workingDir("commonmark-spec") args("test/spec_tests.py", "--dump-tests") val output = ByteArrayOutputStream() standardOutput = output doLast { val tests = String(output.toByteArray()) generateSpecTest( tests, "CommonMarkSpecTest", "org.intellij.markdown.flavours.commonmark.CommonMarkFlavourDescriptor" ) } } task("generateGfmTest", type = Exec::class) { group = "Code Generation" description = "Generate unit tests for the GFM spec" dependsOn("downloadGfm") executable("python") workingDir("cmark-gfm/test") args("spec_tests.py", "--dump-tests") val output = ByteArrayOutputStream() standardOutput = output doLast { val tests = String(output.toByteArray()) generateSpecTest( tests, "GfmSpecTest", "org.intellij.markdown.flavours.gfm.GFMFlavourDescriptor" ) } } task("generateAllTests") { group = "Code Generation" description = "Generate unit tests for the all markdown specs" dependsOn("generateCommonMarkTest", "generateGfmTest") } } val dokkaOutputDir = project.buildDir.resolve("dokkaHtml") subprojects { tasks.withType<org.jetbrains.dokka.gradle.DokkaTask> { outputDirectory.set(dokkaOutputDir) } } tasks.register<Jar>("javadocJar") { dependsOn(":docs:dokkaHtml") archiveClassifier.set("javadoc") from(dokkaOutputDir) } val publicationsToArtifacts = mapOf( "kotlinMultiplatform" to "markdown", "jvm" to "markdown-jvm", "js" to "markdown-js", "linuxX64" to "markdown-linuxx64", "mingwX64" to "markdown-mingwx64", "macosX64" to "markdown-macosx64", "metadata" to "markdown-metadata" ) publicationsToArtifacts.forEach { publicationName, artifactId -> registerPublicationFromKotlinPlugin(publicationName, artifactId) } signPublicationsIfNecessary(*publicationsToArtifacts.keys.toTypedArray()) configureSonatypePublicationIfNecessary() configureBintrayPublicationIfNecessary()
0
Kotlin
0
0
b47f00c325ae673ca280eaaefd92e8f1c22dc3d8
6,509
markdown
Apache License 2.0
src/main/kotlin/dev/ocpd/jsensible/internal/jpa/MisalignedNullability.kt
ocpddev
587,719,778
false
{"Kotlin": 28098, "Java": 7748}
package dev.ocpd.jsensible.internal.jpa import com.tngtech.archunit.base.DescribedPredicate.describe import com.tngtech.archunit.core.domain.JavaMember import com.tngtech.archunit.lang.ArchCondition import com.tngtech.archunit.lang.conditions.ArchConditions.be import dev.ocpd.jsensible.internal.nullability.NullabilityAnnotations.nullableAnnotations import kotlin.jvm.optionals.getOrNull /** * Misaligned nullability declaration condition. */ object MisalignedNullability { /** * Matches misaligned nullability declaration. */ internal fun haveMisalignedNullability(): ArchCondition<in JavaMember> { return be(describe("have misaligned nullability") { member -> val jpaNullability = member.jpaNullability() ?: return@describe false jpaNullability != member.javaNullability() }) } private fun JavaMember.jpaNullability(): Boolean? = annotations.firstOrNull { it.type.name in nullableJpaAnnotations } ?.run { this["nullable"].getOrNull() as? Boolean ?: this["optional"].getOrNull() as? Boolean } private fun JavaMember.javaNullability(): Boolean = isAnnotatedWith(nullableAnnotations()) private val nullableJpaAnnotations = setOf( "jakarta.persistence.ManyToOne", "jakarta.persistence.OneToOne", "jakarta.persistence.Column" ) }
3
Kotlin
2
1
db8bccb166ea4b56e26d70b13f02e73c69e284b6
1,414
jsensible
Apache License 2.0
app/src/main/java/ca/llamabagel/transpo/transit/workers/RemoteMetadataWorker.kt
Llamabagel
175,222,878
false
{"Kotlin": 191040}
/* * Copyright (c) 2019 <NAME>. Subject to the MIT license. */ package ca.llamabagel.transpo.transit.workers import android.content.Context import androidx.work.CoroutineWorker import androidx.work.Data import androidx.work.WorkerParameters import ca.llamabagel.transpo.transit.data.DataRepository import com.squareup.inject.assisted.Assisted import com.squareup.inject.assisted.AssistedInject class RemoteMetadataWorker @AssistedInject constructor( @Assisted appContext: Context, @Assisted params: WorkerParameters, private val dataRepository: DataRepository ) : CoroutineWorker(appContext, params) { override suspend fun doWork(): Result { val remoteMetadata = dataRepository.getRemoteAppMetadata() val localMetadata = dataRepository.getLocalAppMetadata() val data = Data.Builder() if (remoteMetadata.dataSchemaVersion != localMetadata.dataSchemaVersion || remoteMetadata.dataVersion <= localMetadata.dataVersion ) { data.putBoolean(KEY_UPDATE, false) } else { data.putBoolean(KEY_UPDATE, true) } data.putString(KEY_REMOTE_VERSION, remoteMetadata.dataVersion) return Result.success(data.build()) } @AssistedInject.Factory interface Factory : ChildWorkerFactory }
10
Kotlin
2
1
70ca00367b6cb93a8c1bd19f1a6524e093b65484
1,315
transpo-android
MIT License
core/src/main/kotlin/id/barakkastudio/core/data/model/Product.kt
im-o
635,182,956
false
{"Kotlin": 132309}
package id.barakkastudio.core.data.model import com.google.gson.annotations.SerializedName data class Product( @SerializedName("brand") val brand: String? = null, @SerializedName("category") val category: String? = null, @SerializedName("description") val description: String? = null, @SerializedName("discountPercentage") val discountPercentage: Double? = null, @SerializedName("id") val id: Int? = null, @SerializedName("images") val images: List<String?>? = null, @SerializedName("price") val price: Long? = null, @SerializedName("rating") val rating: Double? = null, @SerializedName("stock") val stock: Int? = null, @SerializedName("thumbnail") val thumbnail: String? = null, @SerializedName("title") val title: String? = null )
0
Kotlin
5
17
69f276d175453b06d276fab12dc4513f69937214
823
jetpack-compose-clean-architecture
MIT License
settings.gradle.kts
dolphin2410-archive
432,660,726
false
{"Kotlin": 9369}
rootProject.name = "WebJelly"
0
Kotlin
0
2
1aa7162fc3ebee5837b3544932ad0b6091db2631
31
WebJelly
Apache License 2.0
buildSrc/src/main/kotlin/cozy-module.gradle.kts
QuiltMC
360,203,063
false
{"Kotlin": 636991, "Groovy": 24653, "Dockerfile": 247}
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import org.cadixdev.gradle.licenser.LicenseExtension //import org.ec4j.gradle.EditorconfigCheckTask import org.jetbrains.kotlin.gradle.tasks.KotlinCompile plugins { kotlin("jvm") kotlin("plugin.serialization") id("com.expediagroup.graphql") id("com.google.devtools.ksp") id("io.gitlab.arturbosch.detekt") id("org.cadixdev.licenser") // id("org.ec4j.editorconfig") } group = "org.quiltmc.community" version = "1.0.1-SNAPSHOT" repositories { mavenLocal() google() maven { name = "Sleeping Town" url = uri("https://repo.sleeping.town") content { includeGroup("com.unascribed") } } maven { name = "Sonatype Snapshots" url = uri("https://s01.oss.sonatype.org/content/repositories/snapshots") } maven { name = "Sonatype Snapshots (Legacy)" url = uri("https://oss.sonatype.org/content/repositories/snapshots") } maven { name = "QuiltMC (Releases)" url = uri("https://maven.quiltmc.org/repository/release/") } maven { name = "QuiltMC (Snapshots)" url = uri("https://maven.quiltmc.org/repository/snapshot/") } maven { name = "Shedaniel" url = uri("https://maven.shedaniel.me") } maven { name = "Fabric" url = uri("https://maven.fabricmc.net") } maven { name = "JitPack" url = uri("https://jitpack.io") } } configurations.all { resolutionStrategy.cacheDynamicVersionsFor(10, "seconds") resolutionStrategy.cacheChangingModulesFor(10, "seconds") } tasks { afterEvaluate { withType<KotlinCompile>().configureEach { kotlinOptions { jvmTarget = "17" freeCompilerArgs += "-opt-in=kotlin.RequiresOptIn" } } license { header(rootDir.toPath().resolve("LICENSE")) } java { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } // check { // dependsOn("editorconfigCheck") // } // // editorconfig { // excludes = mutableListOf( // "build", // ".*/**", // ) // } } } detekt { buildUponDefaultConfig = true config = rootProject.files("detekt.yml") } // Credit to ZML for this workaround. // https://github.com/CadixDev/licenser/issues/6#issuecomment-817048318 extensions.configure(LicenseExtension::class.java) { exclude { it.file.startsWith(buildDir) } } sourceSets { main { java { srcDir(file("$buildDir/generated/ksp/main/kotlin/")) } } test { java { srcDir(file("$buildDir/generated/ksp/test/kotlin/")) } } } val sourceJar = task("sourceJar", Jar::class) { dependsOn(tasks["classes"]) archiveClassifier.set("sources") from(sourceSets.main.get().allSource) }
20
Kotlin
23
22
9b40580a6c77a6b57cb05819a907bbaf07512384
2,756
cozy-discord
MIT License
korma/src/commonTest/kotlin/com/soywiz/korma/geom/RectangleTest.kt
SerVB
251,643,142
true
{"Kotlin": 503751, "Shell": 1701, "Batchfile": 1527}
package com.soywiz.korma.geom import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue class RectangleTest { @Test fun name() { val big = Rectangle.fromBounds(0, 0, 50, 50) val small = Rectangle.fromBounds(10, 10, 20, 20) val out = Rectangle.fromBounds(100, 10, 200, 20) assertTrue(small in big) assertTrue(big !in small) assertTrue(small == (small intersection big)) assertTrue(small == (big intersection small)) assertTrue(null == (big intersection out)) assertTrue(small intersects big) assertTrue(big intersects small) assertFalse(big intersects out) } @Test fun name2() { val r1 = Rectangle(20, 0, 30, 10) val r2 = Rectangle(100, 0, 100, 50) val ro = r1.copy() ro.setToAnchoredRectangle(ro, Anchor.MIDDLE_CENTER, r2) //Assert.assertEquals(Rectangle(0, 0, 0, 0), r1) assertEquals(Rectangle(135, 20, 30, 10), ro) } }
0
null
0
0
7d233a0f63b9d41c1891c7f5ca44ab50d753e3a1
1,043
korma
Boost Software License 1.0
FilmStacks/app/src/main/java/com/example/filmstacks/data/local/MovieEntity.kt
ArthurDrd
618,166,921
false
null
package com.example.filmstacks.data.local import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class MovieEntity( @PrimaryKey val id: Int, val title: String, val overview: String, val adult: Boolean?, val backdrop_path: String?, val poster_path: String?, val release_date: String?, val vote_average: Double?, val budget: Int?, val popularity: Double?, val runtime: Int?, val status: String?, val genres: List<GenreEntity>? = null, val production_companies: List<CompaniesEntity>? = null ) @Entity data class GenreEntity( @PrimaryKey val id: Int, val name: String ) @Entity data class CompaniesEntity( @PrimaryKey val id: Int, val name: String, val logo_path: String?, val origin_country: String )
0
Kotlin
0
0
548698cc4db4979f40b8b14f961a47819d109c6d
800
FilmStacks
MIT License
app/src/main/java/com/steleot/jetpackcompose/playground/compose/constraintlayout/MotionLayout1Screen.kt
Sagar19RaoRane
410,922,276
true
{"Kotlin": 887894}
package com.steleot.jetpackcompose.playground.compose.constraintlayout import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Button import androidx.compose.material.Icon import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.constraintlayout.compose.ConstraintSet import androidx.constraintlayout.compose.MotionLayout import androidx.constraintlayout.compose.layoutId import com.steleot.jetpackcompose.playground.compose.reusable.DefaultScaffold import com.steleot.jetpackcompose.playground.navigation.ConstraintLayoutNavRoutes private const val Url = "constraintlayout/MotionLayout1Screen.kt" @Composable fun MotionLayout1Screen() { DefaultScaffold( title = ConstraintLayoutNavRoutes.MotionLayout1, link = Url, ) { MotionLayout1Example() } } @Composable private fun MotionLayout1Example() { var animateToEnd by remember { mutableStateOf(false) } val progress by animateFloatAsState( targetValue = if (animateToEnd) 1f else 0f, animationSpec = tween(1000) ) Column(Modifier.background(Color.White)) { MotionLayout( ConstraintSet( """ { background: { width: "spread", height: 60, start: ['parent', 'start', 16], bottom: ['parent', 'bottom', 16], end: ['parent', 'end', 16] }, v1: { width: 100, height: 60, start: ['parent', 'start', 16], bottom: ['parent', 'bottom', 16] }, title: { width: "spread", start: ['v1', 'end', 8], top: ['v1', 'top', 8], end: ['parent', 'end', 8], custom: { textSize: 14 } }, description: { start: ['v1', 'end', 8], top: ['title', 'bottom', 0], custom: { textSize: 12 } }, list: { width: "spread", height: 0, start: ['parent', 'start', 8], end: ['parent', 'end', 8], top: ['parent', 'bottom', 0] }, play: { end: ['close', 'start', 8], top: ['v1', 'top', 0], bottom: ['v1', 'bottom', 0] }, close: { end: ['parent', 'end', 24], top: ['v1', 'top', 0], bottom: ['v1', 'bottom', 0] } } """ ), ConstraintSet( """ { background: { width: "spread", height: 250, start: ['parent', 'start', 0], end: ['parent', 'end', 0], top: ['parent', 'top', 0] }, v1: { width: "spread", height: 250, start: ['parent', 'start', 0], end: ['parent', 'end', 0], top: ['parent', 'top', 0] }, title: { width: "spread", height: 28, start: ['parent', 'start', 16], top: ['v1', 'bottom', 16], end: ['parent', 'end', 16], custom: { textSize: 20 } }, description: { width: "spread", start: ['parent', 'start', 16], top: ['title', 'bottom', 8], end: ['parent', 'end', 16], custom: { textSize: 14 } }, list: { width: "spread", height: 400, start: ['parent', 'start', 16], end: ['parent', 'end', 16], top: ['description', 'bottom', 16] }, play: { start: ['parent', 'end', 8], top: ['v1', 'top', 0], bottom: ['v1', 'bottom', 0] }, close: { start: ['parent', 'end', 8], top: ['v1', 'top', 0], bottom: ['v1', 'bottom', 0] } } """ ), progress = progress, modifier = Modifier .fillMaxSize() .background(Color.White) ) { Box( modifier = Modifier .layoutId("background", "box") .background(Color.Cyan) .clickable(onClick = { animateToEnd = !animateToEnd }) ) Button( onClick = { animateToEnd = !animateToEnd }, modifier = Modifier .layoutId("v1", "box") .background(Color.Blue), shape = RoundedCornerShape(0f) ) {} Text( text = "MotionLayout in Compose", modifier = Modifier.layoutId("title"), color = Color.Black, fontSize = motionProperties("title").value.fontSize("textSize") ) Text( text = "Jetpack Compose Playground", modifier = Modifier.layoutId("description"), color = Color.Black, fontSize = motionProperties("description").value.fontSize("textSize") ) Box( modifier = Modifier .layoutId("list", "box") .background(Color.Gray) ) Icon( Icons.Filled.PlayArrow, contentDescription = "Play", tint = Color.Black, modifier = Modifier.layoutId("play") ) Icon( Icons.Filled.Close, contentDescription = "Close", tint = Color.Black, modifier = Modifier.layoutId("close") ) } } }
0
null
0
1
91d0a3571031a97a437e13ab103a6cd7092f1598
6,918
Jetpack-Compose-Playground
Apache License 2.0
colourythm/src/test/java/com/mikkipastel/colourythm/ColourythmTest.kt
mikkipastel
167,805,997
false
null
package com.mikkipastel.colourythm import org.junit.Test import org.junit.Assert.* class ColourythmTest { @Test fun generateTextColorBlackFromPrimaryBlue() { assertEquals("#FFFFFF", Colourythm().genStringTextBWcolorFromBg(63, 81, 181)) } @Test fun generateTextColorBlackFromPrimaryDarkBlue() { assertEquals("#FFFFFF", Colourythm().genStringTextBWcolorFromBg(48, 63, 159)) } @Test fun generateTextColorBlackFromAccentBlue() { assertEquals("#000000", Colourythm().genStringTextBWcolorFromBg(21, 192, 255)) } @Test fun generateTextColorBlackFromAllPrimaryBlue() { assertEquals("#FFFFFF", Colourythm().genStringTextBWcolorFromBg(35, 44, 58)) } @Test fun generateTextColorBlackFromWhite() { assertEquals("#000000", Colourythm().genStringTextBWcolorFromBg(255, 255, 255)) } @Test fun generateTextColorWhiteFromBlack() { assertEquals("#FFFFFF", Colourythm().genStringTextBWcolorFromBg(0, 0, 0)) } @Test fun generateTextColorBlackFromRed600() { assertEquals("#000000", Colourythm().genStringTextBWcolorFromBg(229, 57, 53)) } @Test fun generateTextColorWhiteFromRed700() { assertEquals("#FFFFFF", Colourythm().genStringTextBWcolorFromBg(211, 47, 47)) } @Test fun generateTextColorBlackFromPink500() { assertEquals("#000000", Colourythm().genStringTextBWcolorFromBg(233, 30, 99)) } @Test fun generateTextColorWhiteFromPink600() { assertEquals("#FFFFFF", Colourythm().genStringTextBWcolorFromBg(216, 27, 96)) } }
0
Kotlin
1
4
6d954ddfb32e6de09c5d3cde4453f335e76ec6b2
1,614
Colourythm
MIT License
drestaurant-apps/drestaurant-microservices/drestaurant-microservices-command-restaurant/src/main/kotlin/com/drestaurant/web/CommandController.kt
idugalic
135,263,722
false
null
package com.drestaurant.web import com.drestaurant.common.domain.api.model.AuditEntry import com.drestaurant.common.domain.api.model.Money import com.drestaurant.restaurant.domain.api.CreateRestaurantCommand import com.drestaurant.restaurant.domain.api.MarkRestaurantOrderAsPreparedCommand import com.drestaurant.restaurant.domain.api.model.MenuItem import com.drestaurant.restaurant.domain.api.model.RestaurantMenu import com.drestaurant.restaurant.domain.api.model.RestaurantOrderId import org.axonframework.commandhandling.callbacks.LoggingCallback import org.axonframework.commandhandling.gateway.CommandGateway import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.annotation.* import java.math.BigDecimal import java.util.* import javax.servlet.http.HttpServletResponse /** * REST Controller for handling 'commands' */ @RestController @RequestMapping(value = ["/api/command"]) class CommandController(private val commandGateway: CommandGateway) { private val currentUser: String get() = if (SecurityContextHolder.getContext().authentication != null) { SecurityContextHolder.getContext().authentication.name } else "TEST" private val auditEntry: AuditEntry get() = AuditEntry(currentUser, Calendar.getInstance().time) @RequestMapping(value = ["/restaurant/createcommand"], method = [RequestMethod.POST], consumes = [MediaType.APPLICATION_JSON_VALUE]) @ResponseStatus(value = HttpStatus.CREATED) fun createRestaurant(@RequestBody request: CreateRestaurantRequest, response: HttpServletResponse) { val menuItems = ArrayList<MenuItem>() for ((id, name, price) in request.menuItems) { val item = MenuItem(id, name, Money(price)) menuItems.add(item) } val menu = RestaurantMenu(menuItems, "ver.0") val command = CreateRestaurantCommand(request.name, menu, auditEntry) commandGateway.send(command, LoggingCallback.INSTANCE) } @RequestMapping(value = ["/restaurant/order/{id}/markpreparedcommand"], method = [RequestMethod.POST], consumes = [MediaType.APPLICATION_JSON_VALUE]) @ResponseStatus(value = HttpStatus.CREATED) fun markRestaurantOrderAsPrepared(@PathVariable id: String, response: HttpServletResponse) = commandGateway.send(MarkRestaurantOrderAsPreparedCommand(RestaurantOrderId(id), auditEntry), LoggingCallback.INSTANCE) } /** * A request for creating a Restaurant */ data class CreateRestaurantRequest(val name: String, val menuItems: List<MenuItemRequest>) /** * A Menu item request */ data class MenuItemRequest(val id: String, val name: String, val price: BigDecimal)
0
Kotlin
83
284
920248e62c5b7d9b8d3c365b2f911355aa19c7db
2,780
digital-restaurant
Apache License 2.0
app/src/main/java/io/github/thegbguy/ussdnavigator/telephony/TelephonyUtils.kt
theGBguy
473,963,580
false
{"Kotlin": 31947}
/* * * * * Created by <NAME> on 26/3/22, 1:07 pm * * Copyright (c) 2022 . All rights reserved. * * Last modified 26/3/22, 1:07 pm * */ package io.github.thegbguy.ussdnavigator.telephony import android.Manifest import android.annotation.SuppressLint import android.app.Activity import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.net.Uri import android.os.Build import android.provider.Settings import android.telecom.TelecomManager import android.text.TextUtils.SimpleStringSplitter import android.util.Log import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat.checkSelfPermission import androidx.core.content.ContextCompat.startActivity import io.github.thegbguy.ussdnavigator.ui.MainActivity // dials the number in the phone's default dialer fun dial(context: Context, number: String?) { val dialIntent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Uri.encode(number))) dialIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK context.startActivity(dialIntent) } // calls the given number using the appropriate sim card fun call(context: Context, number: String, simSlotIndex: Int?) { simSlotIndex?.let { context.startActivity( getActionCallIntent( context, Uri.parse("tel:$number"), simSlotIndex ) ) MainActivity.isRequestOngoing = true Log.d("TelephonyUtils", "Called Number : $number") } } // generates appropriate call intent for any sim slot @RequiresApi(Build.VERSION_CODES.M) @SuppressLint("MissingPermission") private fun getActionCallIntent(context: Context, uri: Uri, simSlotIndex: Int): Intent { // https://stackoverflow.com/questions/25524476/make-call-using-a-specified-sim-in-a-dual-sim-device val simSlotName = arrayOf( "extra_asus_dial_use_dualsim", "com.android.phone.extra.slot", "slot", "simslot", "sim_slot", "subscription", "Subscription", "phone", "com.android.phone.DialingMode", "simSlot", "slot_id", "simId", "simnum", "phone_type", "slotId", "slotIdx" ) val intent = Intent(Intent.ACTION_CALL, uri) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK intent.putExtra("com.android.phone.force.slot", true) intent.putExtra("Cdma_Supp", true) for (slotIndex in simSlotName) intent.putExtra(slotIndex, simSlotIndex) val telecomManager = context.getSystemService(Context.TELECOM_SERVICE) as TelecomManager if (isPermissionGranted(context, Manifest.permission.READ_PHONE_STATE)) { val phoneAccountHandleList = telecomManager.callCapablePhoneAccounts if (phoneAccountHandleList != null && phoneAccountHandleList.size > simSlotIndex) intent.putExtra( "android.telecom.extra.PHONE_ACCOUNT_HANDLE", phoneAccountHandleList[simSlotIndex] ) } else { Toast.makeText(context, "Permission is not granted", Toast.LENGTH_LONG).show() } return intent } val permissions = arrayOf(Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE) fun isPermissionsGranted(context: Context): Boolean { permissions.forEach { permission -> if (!isPermissionGranted(context = context, permission = permission)) { return false } } return isAccessibilityServiceEnabled(context = context) } fun isPermissionGranted(context: Context, permission: String): Boolean { return checkSelfPermission( context, permission ) == PackageManager.PERMISSION_GRANTED } fun requestPermission(activity: Activity, permission: String){ ActivityCompat.requestPermissions(activity, arrayOf(permission), 1100) } fun requestPermissions(activity: Activity, permissions: Array<String>) { ActivityCompat.requestPermissions(activity, permissions, 1000) if (!isAccessibilityServiceEnabled(activity)) { startActivity(activity, Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS), null) } } // checks whether accessibility service is enabled fun isAccessibilityServiceEnabled(context: Context): Boolean { val expectedComponentName = ComponentName(context, UssdService::class.java) val enabledServicesSetting = Settings.Secure.getString( context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES ) ?: return false val colonSplitter = SimpleStringSplitter(':') colonSplitter.setString(enabledServicesSetting) while (colonSplitter.hasNext()) { val componentNameString = colonSplitter.next() val enabledComponentName = ComponentName.unflattenFromString(componentNameString) if (enabledComponentName != null && enabledComponentName == expectedComponentName) return true } return false }
0
Kotlin
2
15
4a64ed78d5806ae928705a3c0f396fb902d23b49
5,003
USSDNavigator
MIT License
screen-switcher/src/test/java/com/jaynewstrom/screenswitcher/ScreenSwitcherFactoryTest.kt
JayNewstrom
48,964,076
false
null
package com.jaynewstrom.screenswitcher import android.app.Activity import android.content.Context import android.view.View import android.view.ViewGroup import org.fest.assertions.api.Assertions.assertThat import org.junit.Assert.fail import org.junit.Before import org.junit.Test import org.mockito.Mockito.`when` import org.mockito.Mockito.mock class ScreenSwitcherFactoryTest { private lateinit var activity: Activity private lateinit var view: ViewGroup private lateinit var state: ScreenSwitcherState private lateinit var finishHandler: ScreenSwitcherFinishHandler @Before fun setup() { activity = mock(Activity::class.java) val hostView = mock(ViewGroup::class.java) `when`<View>(activity.findViewById<View>(android.R.id.content)).thenReturn(hostView) `when`(hostView.context).thenReturn(activity) view = mock(ViewGroup::class.java) `when`<Context>(view.context).thenReturn(activity) val screen = mock(Screen::class.java) ScreenTestUtils.mockCreateView(screen) state = ScreenTestUtils.defaultState(screen) finishHandler = mock(ScreenSwitcherFinishHandler::class.java) } @Test fun activityScreenSwitcherRejectsStateWithNoScreens() { try { state.removeScreen(state.screens[0]) ScreenSwitcherFactory.activityScreenSwitcher(activity, state, finishHandler) fail() } catch (expected: IllegalArgumentException) { assertThat(expected).hasMessage("state needs screens in order to initialize a ScreenSwitcher") } } @Test fun activityScreenSwitcherIsCreated() { val screenSwitcher = ScreenSwitcherFactory.activityScreenSwitcher(activity, state, finishHandler) assertThat(screenSwitcher).isNotNull } @Test fun viewScreenSwitcherRejectsStateWithNoScreens() { try { state.removeScreen(state.screens[0]) ScreenSwitcherFactory.viewScreenSwitcher(view, state, finishHandler) fail() } catch (expected: IllegalArgumentException) { assertThat(expected).hasMessage("state needs screens in order to initialize a ScreenSwitcher") } } @Test fun viewScreenSwitcherIsCreated() { val screenSwitcher = ScreenSwitcherFactory.viewScreenSwitcher(view, state, finishHandler) assertThat(screenSwitcher).isNotNull } }
1
Kotlin
2
2
565a513435ba6c1935ca8c3586aee183fd2d7b17
2,409
ScreenSwitcher
Apache License 2.0
app/src/main/java/com/santansarah/scan/domain/models/DeviceDescriptor.kt
santansarah
588,753,371
false
null
package com.santansarah.scan.domain.models import com.santansarah.scan.domain.bleparsables.CCCD import com.santansarah.scan.utils.decodeSkipUnreadable import com.santansarah.scan.utils.print import com.santansarah.scan.utils.toBinaryString import com.santansarah.scan.utils.toHex import timber.log.Timber data class DeviceDescriptor( val uuid: String, val name: String, val charUuid: String, val permissions: List<BlePermissions>, val notificationProperty: BleProperties?, val readBytes: ByteArray? ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as DeviceDescriptor if (uuid != other.uuid) return false if (name != other.name) return false if (charUuid != other.charUuid) return false if (permissions != other.permissions) return false if (notificationProperty != other.notificationProperty) return false if (readBytes != null) { if (other.readBytes == null) return false if (!readBytes.contentEquals(other.readBytes)) return false } else if (other.readBytes != null) return false return true } override fun hashCode(): Int { var result = uuid.hashCode() result = 31 * result + name.hashCode() result = 31 * result + charUuid.hashCode() result = 31 * result + permissions.hashCode() result = 31 * result + (notificationProperty?.hashCode() ?: 0) result = 31 * result + (readBytes?.contentHashCode() ?: 0) return result } } fun DeviceDescriptor.getWriteCommands(): Array<String> { return when (uuid) { CCCD.uuid -> { CCCD.commands(notificationProperty!!) } else -> { emptyArray() } } } fun DeviceDescriptor.getReadInfo(): String { val sb = StringBuilder() Timber.d("readbytes from first load: $readBytes") readBytes?.let { bytes -> with(sb) { when (uuid) { CCCD.uuid -> { appendLine(CCCD.getReadStringFromBytes(bytes)) appendLine("[" + bytes.print() + "]") } else -> { appendLine("String, Hex, Bytes, Binary:") appendLine(bytes.decodeSkipUnreadable()) appendLine(bytes.toHex()) appendLine("[" + bytes.print() + "]") appendLine(bytes.toBinaryString()) } } } } ?: sb.appendLine("No data.") return sb.toString() }
1
Kotlin
1
16
9e76dab6a244e1eded2480e5e19a812612698326
2,651
ble-scanner
MIT License
xbinder/src/main/java/com/luqinx/xbinder/annotation/AsyncCall.kt
luqinx
450,696,816
false
{"Kotlin": 149701, "Java": 13435, "AIDL": 458}
package com.luqinx.xbinder.annotation /** * @author qinchao * * @since 2022/2/19 */ @kotlin.annotation.Retention(AnnotationRetention.RUNTIME) @Target(AnnotationTarget.FUNCTION) annotation class AsyncCall()
0
Kotlin
1
7
6579d890983b4e16a200003d69ed9b69e8841b80
212
XBinder
Apache License 2.0
src/main/kotlin/xyz/magentaize/dynamicdata/cache/internal/Transformer.kt
Magentaize
290,133,754
false
null
package xyz.magentaize.dynamicdata.cache.internal import io.reactivex.rxjava3.core.Observable import xyz.magentaize.dynamicdata.cache.ChangeAwareCache import xyz.magentaize.dynamicdata.cache.ChangeReason import xyz.magentaize.dynamicdata.cache.ChangeSet import xyz.magentaize.dynamicdata.cache.notEmpty import xyz.magentaize.dynamicdata.kernel.Error import xyz.magentaize.dynamicdata.kernel.Optional import xyz.magentaize.dynamicdata.kernel.Stub import java.lang.Exception internal class Transformer<K, E, R>( private val _source: Observable<ChangeSet<K, E>>, private val _factory: (K, E, Optional<E>) -> R, private val _exceptionCallback: (Error<K, E>) -> Unit = Stub.EMPTY_COMSUMER, private val _transformOnRefresh: Boolean = false ) { fun run(): Observable<ChangeSet<K, R>> = _source.scan(ChangeAwareCache.empty<K, R>()) { state, changes -> val cache = if (state == ChangeAwareCache.empty<K, R>()) ChangeAwareCache(changes.size) else state changes.forEach { change -> val action = { val transformed = _factory(change.key, change.current, change.previous) cache.addOrUpdate(transformed, change.key) } when (change.reason) { ChangeReason.Add, ChangeReason.Update -> { if (_exceptionCallback != ((Stub)::EMPTY_COMSUMER)) { try { action() } catch (ex: Exception) { _exceptionCallback(Error(ex, change.key, change.current)) } } else action() } ChangeReason.Remove -> cache.remove(change.key) ChangeReason.Refresh -> { if (_transformOnRefresh) action() else cache.refresh(change.key) } ChangeReason.Moved -> return@forEach } } return@scan cache } .skip(1) .filter { it != ChangeAwareCache.empty<K, R>() } .map { it.captureChanges() } .notEmpty() }
0
Kotlin
0
3
dda522f335a6ab3847cc90ff56e8429c15834800
2,574
dynamicdata-kotlin
MIT License
feature-swap-impl/src/main/java/io/novafoundation/nova/feature_swap_impl/presentation/common/PriceImpactFormatter.kt
novasamatech
415,834,480
false
{"Kotlin": 8656332, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_swap_impl.presentation.common import io.novafoundation.nova.common.resources.ResourceManager import io.novafoundation.nova.common.utils.Percent import io.novafoundation.nova.common.utils.colorSpan import io.novafoundation.nova.common.utils.formatting.format import io.novafoundation.nova.common.utils.toSpannable import io.novafoundation.nova.feature_swap_impl.R private val THRESHOLDS = listOf( 15.0 to R.color.text_negative, 5.0 to R.color.text_warning, 1.0 to R.color.text_secondary, ) interface PriceImpactFormatter { fun format(priceImpact: Percent?): CharSequence? fun formatWithBrackets(priceImpact: Percent?): CharSequence? } class RealPriceImpactFormatter(private val resourceManager: ResourceManager) : PriceImpactFormatter { override fun format(priceImpact: Percent?): CharSequence? { if (priceImpact == null) return null val color = getColor(priceImpact) ?: return null return priceImpact.format().toSpannable(colorSpan(resourceManager.getColor(color))) } override fun formatWithBrackets(priceImpact: Percent?): CharSequence? { if (priceImpact == null) return null val color = getColor(priceImpact) ?: return null val formattedImpact = "(${priceImpact.format()})" return formattedImpact.toSpannable(colorSpan(resourceManager.getColor(color))) } private fun getColor(priceImpact: Percent): Int? { return THRESHOLDS.firstOrNull { priceImpact.value > it.first } ?.second } }
18
Kotlin
6
15
547f9966ee3aec864b864d6689dc83b6193f5c15
1,554
nova-wallet-android
Apache License 2.0
domain/src/test/java/com/huskielabs/baac/domain/usecase/GetAllEmojisUseCaseTest.kt
tiagotrcz
336,550,961
false
null
package com.huskielabs.baac.domain.usecase import com.huskielabs.baac.domain.datasource.EmojiDataSource import com.huskielabs.baac.domain.usecase.GetAllEmojisUseCase import com.huskielabs.baac.domain.usecase.shared.NoParams import io.mockk.coEvery import io.mockk.coVerify import io.mockk.confirmVerified import io.mockk.mockk import kotlinx.coroutines.runBlocking import org.junit.Assert import org.junit.Before import org.junit.Test class GetAllEmojisUseCaseTest { private val emojiDataSource = mockk<EmojiDataSource>() private lateinit var useCase: GetAllEmojisUseCase @Before fun `set up`() { useCase = GetAllEmojisUseCase(emojiDataSource) } @Test fun `should get all emojis`() { val dataSourceResponse = listOf("emojiUrl") val expected = listOf("emojiUrl") coEvery { emojiDataSource.getAll() } returns dataSourceResponse val actual = runBlocking { useCase(NoParams) } Assert.assertEquals(expected, actual) coVerify(exactly = 1) { emojiDataSource.getAll() } confirmVerified(emojiDataSource) } }
0
Kotlin
0
0
fd8fb093cd9444978c8c4853c123115c7b053445
1,058
baac
MIT License
android/app/src/main/kotlin/com/webby/webproject/MainActivity.kt
Venki889220
430,059,979
false
{"HTML": 3932, "Dart": 1938, "Swift": 404, "Kotlin": 125, "Objective-C": 38}
package com.webby.webproject import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
HTML
0
0
99dc26b2bc2889a8d3c368b411883d32c5126415
125
webby.github.io
MIT License
src/main/kotlin/com/wonddak/fonthelper/util/FontUtil.kt
jmseb3
631,765,992
false
null
package com.wonddak.fonthelper.util import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VfsUtil import com.intellij.psi.impl.file.PsiDirectoryFactory import com.wonddak.fonthelper.model.FontCheck import java.io.File /** * Font Helper Object */ object FontUtil { const val NORMAL = "Normal" const val ITALIC = "Italic" private val indexToWeight: Map<Int, String> = mapOf( 0 to "Thin", 1 to "ExtraLight", 2 to "Light", 3 to "Normal", 4 to "Medium", 5 to "SemiBold", 6 to "Bold", 7 to "ExtraBold", 8 to "Black" ) fun getWeightTextByIndex(index: Int): String { return indexToWeight[index] ?: "" } fun getWeightCount(): Int { return indexToWeight.size } private fun makeFileName(name: String, fontCheck: FontCheck): String { val st = StringBuilder() st.append(name.lowercase()) st.append("_") st.append(getWeightTextByIndex(fontCheck.weightIndex).lowercase()) if (fontCheck.isItalic) { st.append("_") st.append(ITALIC.lowercase()) } st.append(".ttf") return st.toString() } private fun copyFontFile(srcPath: String, name: String) { // Source file val sourceFile = File(srcPath) // Destination directory val destinationDir = File(PathUtil.getFontPath()) // Create the destination directory if it doesn't exist if (!destinationDir.exists()) { destinationDir.mkdirs() } // Destination file val destinationFile = File(destinationDir, name) // Check File Exist if (destinationFile.exists()) { destinationFile.delete() } // Copy the file FileUtil.copy(sourceFile, destinationFile) } fun copyFontFile(fontCheck: FontCheck) { copyFontFile(fontCheck.path, makeFileName(PathUtil.fileName, fontCheck)) } fun makeFontFamily(fontCheck: List<FontCheck>) { val name = PathUtil.fileName val project = ProjectManager.getInstance().defaultProject val directory = VfsUtil.createDirectoryIfMissing(PathUtil.getClassPath()) val fileName = PathUtil.makeSavingFormatFileName() WriteCommandAction.runWriteCommandAction(project) { directory?.let { directory -> val psiDirectory = PsiDirectoryFactory.getInstance(project).createDirectory(directory) var psiFile = psiDirectory.findFile(fileName) psiFile?.delete() psiFile = psiDirectory.createFile(fileName) psiFile.virtualFile.setBinaryContent(makeContentString(name, fontCheck).toByteArray()) } } PathUtil.refresh() } private fun makeContentString(name: String, fontCheck: List<FontCheck>): String { fun makeFontString(index: Int, isItalic: Boolean): String { val st = StringBuilder() val type = getWeightTextByIndex(index) st.append("\tFont(R.font.${name.lowercase()}_${type.lowercase()}") if (isItalic) { st.append("_italic") } st.append(", FontWeight.${type}, FontStyle.") if (isItalic) { st.append("Italic") } else { st.append("Normal") } st.append(")") return st.toString() } val st = StringBuilder() if (PathUtil.packageName.isNotEmpty()) { st.append("package ") st.append(PathUtil.packageName) st.append("\n") } st.append("\n") st.append("import androidx.compose.ui.text.font.Font\n") st.append("import androidx.compose.ui.text.font.FontFamily\n") st.append("import androidx.compose.ui.text.font.FontStyle\n") st.append("import androidx.compose.ui.text.font.FontWeight\n") st.append("\n") st.append("val ${name.lowercase()} = FontFamily(\n") st.append(fontCheck.joinToString(",\n") { makeFontString(it.weightIndex, it.isItalic) }) st.append("\n") st.append(")") return st.toString().trimIndent() } }
0
Kotlin
0
1
5f34ecf046c7b46c8ce423094a97572eec7fbd71
4,415
Android_Font_Helper_Plugin
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/memoir/generated/equip2000005.kt
pointillion
428,683,199
true
{"Kotlin": 1212476, "HTML": 26704, "CSS": 26127, "JavaScript": 1640}
package xyz.qwewqa.relive.simulator.core.presets.memoir.generated import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.autoskill.EffectTag import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.memoir.CutinBlueprint import xyz.qwewqa.relive.simulator.core.stage.memoir.PartialMemoirBlueprint val equip2000005 = PartialMemoirBlueprint( id = 2000005, name = "「別れの戦記」の王国旗", rarity = 2, baseStats = StatData( hp = 0, actPower = 0, normalDefense = 15, specialDefense = 15, ), growthStats = StatData( hp = 0, actPower = 0, normalDefense = 2288, specialDefense = 2288, ), additionalTags = listOf() )
0
Kotlin
0
0
53479fe3d1f4a067682509376afd87bdd205d19d
776
relive-simulator
MIT License
base/build-system/gradle-core/src/test/java/com/android/build/api/artifact/impl/OperationsImplTest.kt
qiangxu1996
255,410,085
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * 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.build.api.artifact.impl import com.android.build.api.artifact.ArtifactKind import com.android.build.api.artifact.ArtifactType import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_DIRECTORIES import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_DIRECTORY import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_FILE import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_FILES import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_REPLACABLE_DIRECTORY import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_REPLACABLE_FILE import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_TRANSFORMABLE_DIRECTORY import com.android.build.api.artifact.impl.OperationsImplTest.TestArtifactType.TEST_TRANSFORMABLE_FILE import com.google.common.truth.Truth import org.gradle.api.DefaultTask import org.gradle.api.Project import org.gradle.api.file.Directory import org.gradle.api.file.DirectoryProperty import org.gradle.api.file.FileSystemLocation import org.gradle.api.file.RegularFile import org.gradle.api.file.RegularFileProperty import org.gradle.api.tasks.InputDirectory import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputDirectory import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskProvider import org.gradle.testfixtures.ProjectBuilder import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicInteger class OperationsImplTest { @Suppress("ClassName") sealed class TestArtifactType<T : FileSystemLocation>(kind: ArtifactKind<T>) : ArtifactType<T>(kind) { override val isPublic: Boolean get() = false object TEST_FILE : TestArtifactType<RegularFile>(FILE), Single object TEST_FILES : TestArtifactType<RegularFile>(FILE), Multiple object TEST_DIRECTORY : TestArtifactType<Directory>(DIRECTORY), Single object TEST_DIRECTORIES : TestArtifactType<Directory>(DIRECTORY), Multiple object TEST_APPENDABLE_FILES : TestArtifactType<RegularFile>(FILE), Multiple, Appendable object TEST_APPENDABLE_DIRECTORIES : TestArtifactType<Directory>(DIRECTORY), Multiple, Appendable object TEST_TRANSFORMABLE_FILE : TestArtifactType<RegularFile>(FILE), Single, Transformable object TEST_TRANSFORMABLE_FILES : TestArtifactType<RegularFile>(FILE), Multiple, Transformable object TEST_TRANSFORMABLE_DIRECTORY : TestArtifactType<Directory>(DIRECTORY), Single, Transformable object TEST_TRANSFORMABLE_DIRECTORIES : TestArtifactType<Directory>(DIRECTORY), Multiple, Transformable object TEST_REPLACABLE_FILE : TestArtifactType<RegularFile>(FILE), Single, Replaceable object TEST_REPLACABLE_DIRECTORY : TestArtifactType<Directory>(DIRECTORY), Single, Replaceable } @Rule @JvmField val tmpDir: TemporaryFolder = TemporaryFolder() lateinit var project: Project lateinit var operations: OperationsImpl @Before fun setUp() { project = ProjectBuilder.builder().withProjectDir( tmpDir.newFolder()).build() operations = OperationsImpl(project.objects,"debug", project.layout.buildDirectory) } @Test fun testSingleFileAGPProvider() { abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider(TEST_FILE, agpProducer, AGPTask::outputFile) Truth.assertThat(agpInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_FILE) Truth.assertThat(agpProducer.get().outputFile.get().asFile.absolutePath).contains("test_file") Truth.assertThat(agpProducer.get().outputFile.get().asFile.absolutePath).doesNotContain("agpProvider") // final artifact value should be the agp producer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(agpProducer.get().outputFile.asFile.get().absolutePath) } @Test fun testSingleDirectoryAGPProvider() { abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider(TEST_DIRECTORY, agpProducer, AGPTask::outputFolder) Truth.assertThat(agpInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_DIRECTORY) Truth.assertThat(agpProducer.get().outputFolder.get().asFile.absolutePath).contains("test_directory") Truth.assertThat(agpProducer.get().outputFolder.get().asFile.absolutePath).doesNotContain("agpProducer") // final artifact value should be the agp producer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(agpProducer.get().outputFolder.asFile.get().absolutePath) } @Test fun testOneAGPProviderForMultipleFileArtifactType() { abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) operations.addInitialProvider(TEST_FILES, agpProducer, AGPTask::outputFile) val artifactContainer = operations.getArtifactContainer(TEST_FILES) Truth.assertThat(artifactContainer.get().get()).hasSize(1) val outputFile = artifactContainer.get().get()[0] Truth.assertThat(outputFile.asFile.absolutePath).contains("test_files") // since multiple producer are possible, task name is provided in path even with a single registered producer Truth.assertThat(outputFile.asFile.absolutePath).contains("agpProducer") } @Test fun testMultipleAGPProvidersForMultipleFileArtifactType() { abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val initializedTasks = AtomicInteger(0) val agpProducers = mutableListOf<TaskProvider<AGPTask>>() for (i in 0..2) { val agpProducer = project.tasks.register("agpProducer$i", AGPTask::class.java) { initializedTasks.incrementAndGet() } agpProducers.add(agpProducer) operations.addInitialProvider(TEST_FILES, agpProducer, AGPTask::outputFile) } Truth.assertThat(initializedTasks.get()).isEqualTo(0) val artifactContainer = operations.getArtifactContainer(TEST_FILES) for (i in 0..2) { Truth.assertThat(agpProducers[i].get().outputFile.get().asFile.absolutePath).contains("test_files") // since multiple producer, task name is provided in path. Truth.assertThat(agpProducers[i].get().outputFile.get().asFile.absolutePath).contains("agpProducer$i") } Truth.assertThat(artifactContainer.get().get()).hasSize(3) Truth.assertThat(initializedTasks.get()).isEqualTo(3) } @Test fun testOneAGPProviderForMultipleDirectoryArtifactType() { abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputDirectory: DirectoryProperty } val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) operations.addInitialProvider(TEST_DIRECTORIES, agpProducer, AGPTask::outputDirectory) val artifactContainer = operations.getArtifactContainer(TEST_DIRECTORIES) Truth.assertThat(artifactContainer.get().get()).hasSize(1) val outputFile = artifactContainer.get().get()[0] Truth.assertThat(outputFile.asFile.absolutePath).contains("test_directories") // since multiple producer are possible, task name is provided in path even with a single registered producer Truth.assertThat(outputFile.asFile.absolutePath).contains("agpProducer") } @Test fun testMultipleAGPProvidersForMultipleDirectoryArtifactType() { abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputDirectory: DirectoryProperty } val initializedTasks = AtomicInteger(0) val agpProducers = mutableListOf<TaskProvider<AGPTask>>() for (i in 0..2) { val agpProducer = project.tasks.register("agpProducer$i", AGPTask::class.java) { initializedTasks.incrementAndGet() } agpProducers.add(agpProducer) operations.addInitialProvider(TEST_DIRECTORIES, agpProducer, AGPTask::outputDirectory) } Truth.assertThat(initializedTasks.get()).isEqualTo(0) val artifactContainer = operations.getArtifactContainer(TEST_DIRECTORIES) for (i in 0..2) { Truth.assertThat(agpProducers[i].get().outputDirectory.get().asFile.absolutePath).contains("test_directories") // since multiple producer, task name is provided in path. Truth.assertThat(agpProducers[i].get().outputDirectory.get().asFile.absolutePath).contains("agpProducer$i") } Truth.assertThat(artifactContainer.get().get()).hasSize(3) Truth.assertThat(initializedTasks.get()).isEqualTo(3) } @Test fun testFileTransform() { abstract class TransformTask: DefaultTask() { @get:InputFile abstract val inputFile: RegularFileProperty @get:OutputFile abstract val outputFile: RegularFileProperty } val transformerInitialized = AtomicBoolean(false) val transformerProvider = project.tasks.register("transformer", TransformTask::class.java) { transformerInitialized.set(true) } operations.transform(transformerProvider, TransformTask::inputFile, TransformTask::outputFile).on(TEST_TRANSFORMABLE_FILE) Truth.assertThat(transformerInitialized.get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider( TEST_TRANSFORMABLE_FILE, agpProducer, AGPTask::outputFile) Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(transformerInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_TRANSFORMABLE_FILE) // agp Producer should output in a folder with its task name since there are transforms registered. Truth.assertThat(agpProducer.get().outputFile.get().asFile.absolutePath).contains("agpProducer") // transform input should be in the agp producer. Truth.assertThat(transformerProvider.get().inputFile.asFile.get().absolutePath).contains("agpProducer") // transform output should have the task name in its output. Truth.assertThat(transformerProvider.get().outputFile.get().asFile.absolutePath).contains("transformer") // final artifact value should be the transformer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(transformerProvider.get().outputFile.asFile.get().absolutePath) } @Test fun testDirectoryTransform() { abstract class TransformTask: DefaultTask() { @get:InputDirectory abstract val inputFolder: DirectoryProperty @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val transformerInitialized = AtomicBoolean(false) val transformerProvider = project.tasks.register("transformer", TransformTask::class.java) { transformerInitialized.set(true) } operations.transform(transformerProvider, TransformTask::inputFolder, TransformTask::outputFolder).on(TEST_TRANSFORMABLE_DIRECTORY) Truth.assertThat(transformerInitialized.get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider(TEST_TRANSFORMABLE_DIRECTORY, agpProducer, AGPTask::outputFolder) Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(transformerInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_TRANSFORMABLE_DIRECTORY) // agp Producer should output in a folder with its task name since there are transforms registered. Truth.assertThat(agpProducer.get().outputFolder.get().asFile.absolutePath).contains("agpProducer") // transform input should be in the agp producer. Truth.assertThat(transformerProvider.get().inputFolder.asFile.get().absolutePath).contains("agpProducer") // transform output should have the task name in its output. Truth.assertThat(transformerProvider.get().outputFolder.get().asFile.absolutePath).contains("transformer") // final artifact value should be the transformer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(transformerProvider.get().outputFolder.asFile.get().absolutePath) } @Test fun testOverlappingFileTransforms() { abstract class TransformTask: DefaultTask() { @get:InputFile abstract val inputFile: RegularFileProperty @get:OutputFile abstract val outputFile: RegularFileProperty } // register first transformer. val transformerOneInitialized = AtomicBoolean(false) val transformerOneProvider = project.tasks.register("transformerOne", TransformTask::class.java) { transformerOneInitialized.set(true) } operations.transform(transformerOneProvider, TransformTask::inputFile, TransformTask::outputFile).on(TEST_TRANSFORMABLE_FILE) Truth.assertThat(transformerOneInitialized.get()).isFalse() // register second transformer val transformerTwoInitialized = AtomicBoolean(false) val transformerTwoProvider = project.tasks.register("transformerTwo", TransformTask::class.java) { transformerTwoInitialized.set(true) } operations.transform(transformerTwoProvider, TransformTask::inputFile, TransformTask::outputFile).on(TEST_TRANSFORMABLE_FILE) Truth.assertThat(transformerTwoInitialized.get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) operations.setInitialProvider(TEST_TRANSFORMABLE_FILE, agpProducer, AGPTask::outputFile) agpProducer.configure { agpInitialized.set(true) } Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(transformerOneInitialized.get()).isFalse() Truth.assertThat(transformerTwoInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_TRANSFORMABLE_FILE) // final artifact value should be the transformerTwo task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(transformerTwoProvider.get().outputFile.asFile.get().absolutePath) // agp Producer should output in a folder with its task name since there are transforms registered. Truth.assertThat(agpProducer.get().outputFile.get().asFile.absolutePath).contains("agpProducer") // transformOne input should be in the agp producer. Truth.assertThat(transformerOneProvider.get().inputFile.asFile.get().absolutePath).contains("agpProducer") // transformOne output should have the task name in its output. Truth.assertThat(transformerOneProvider.get().outputFile.get().asFile.absolutePath).contains("transformerOne") // transformTwo input should be TransformOne output Truth.assertThat(transformerTwoProvider.get().inputFile.asFile.get().absolutePath).contains("transformerOne") // transformTwo output should have the task name in its output. Truth.assertThat(transformerTwoProvider.get().outputFile.get().asFile.absolutePath).contains("transformerTwo") // the producers have been looked up, it should now be configured Truth.assertThat(agpInitialized.get()).isTrue() Truth.assertThat(transformerOneInitialized.get()).isTrue() Truth.assertThat(transformerTwoInitialized.get()).isTrue() } @Test fun testOverlappingDirectoryTransforms() { abstract class TransformTask: DefaultTask() { @get:InputDirectory abstract val inputFolder: DirectoryProperty @get:OutputDirectory abstract val outputFolder: DirectoryProperty } // register first transformer. val transformerOneInitialized = AtomicBoolean(false) val transformerOneProvider = project.tasks.register("transformerOne", TransformTask::class.java) { transformerOneInitialized.set(true) } operations.transform(transformerOneProvider, TransformTask::inputFolder, TransformTask::outputFolder).on(TEST_TRANSFORMABLE_DIRECTORY) Truth.assertThat(transformerOneInitialized.get()).isFalse() // register second transformer val transformerTwoInitialized = AtomicBoolean(false) val transformerTwoProvider = project.tasks.register("transformerTwo", TransformTask::class.java) { transformerTwoInitialized.set(true) } operations.transform(transformerTwoProvider, TransformTask::inputFolder, TransformTask::outputFolder).on(TEST_TRANSFORMABLE_DIRECTORY) Truth.assertThat(transformerTwoInitialized.get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) operations.setInitialProvider(TEST_TRANSFORMABLE_DIRECTORY, agpProducer, AGPTask::outputFolder) agpProducer.configure { agpInitialized.set(true) } Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(transformerOneInitialized.get()).isFalse() Truth.assertThat(transformerTwoInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_TRANSFORMABLE_DIRECTORY) // final artifact value should be the transformerTwo task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(transformerTwoProvider.get().outputFolder.asFile.get().absolutePath) // agp Producer should output in a folder with its task name since there are transforms registered. Truth.assertThat(agpProducer.get().outputFolder.get().asFile.absolutePath).contains("agpProducer") // transformOne input should be in the agp producer. Truth.assertThat(transformerOneProvider.get().inputFolder.asFile.get().absolutePath).contains("agpProducer") // transformOne output should have the task name in its output. Truth.assertThat(transformerOneProvider.get().outputFolder.get().asFile.absolutePath).contains("transformerOne") // transformTwo input should be TransformOne output Truth.assertThat(transformerTwoProvider.get().inputFolder.asFile.get().absolutePath).contains("transformerOne") // transformTwo output should have the task name in its output. Truth.assertThat(transformerTwoProvider.get().outputFolder.get().asFile.absolutePath).contains("transformerTwo") // the producers have been looked up, it should now be configured Truth.assertThat(agpInitialized.get()).isTrue() Truth.assertThat(transformerOneInitialized.get()).isTrue() Truth.assertThat(transformerTwoInitialized.get()).isTrue() } @Test fun testFileReplace() { abstract class ReplaceTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val replaceTaskInitialized = AtomicBoolean(false) val replaceTaskProvider = project.tasks.register("replaceTask", ReplaceTask::class.java) { replaceTaskInitialized.set(true) } operations.replace(replaceTaskProvider, ReplaceTask::outputFile).on(TEST_REPLACABLE_FILE) Truth.assertThat(replaceTaskInitialized.get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } Truth.assertThat(operations.getArtifactContainer(TEST_REPLACABLE_FILE) .needInitialProducer().get()).isFalse() val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider( TEST_REPLACABLE_FILE, agpProducer, AGPTask::outputFile) Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_REPLACABLE_FILE) // transform output should have the task name in its output. Truth.assertThat(replaceTaskProvider.get().outputFile.get().asFile.absolutePath).contains("replaceTask") // final artifact value should be the transformer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(replaceTaskProvider.get().outputFile.asFile.get().absolutePath) // agp provider should be ignored. Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskInitialized.get()).isTrue() } @Test fun testDirectoryReplace() { abstract class ReplaceTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val replaceTaskInitialized = AtomicBoolean(false) val replaceTaskProvider = project.tasks.register("replaceTask", ReplaceTask::class.java) { replaceTaskInitialized.set(true) } operations.replace(replaceTaskProvider, ReplaceTask::outputFolder).on(TEST_REPLACABLE_DIRECTORY) Truth.assertThat(replaceTaskInitialized.get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } Truth.assertThat(operations.getArtifactContainer(TEST_REPLACABLE_DIRECTORY) .needInitialProducer().get()).isFalse() val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider(TEST_REPLACABLE_DIRECTORY, agpProducer, AGPTask::outputFolder) Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_REPLACABLE_DIRECTORY) // transform output should have the task name in its output. Truth.assertThat(replaceTaskProvider.get().outputFolder.get().asFile.absolutePath).contains("replaceTask") // final artifact value should be the transformer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(replaceTaskProvider.get().outputFolder.asFile.get().absolutePath) // agp provider should be ignored. Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskInitialized.get()).isTrue() } @Test fun testOverlappingFileReplace() { abstract class ReplaceTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val replaceTaskOneInitialized = AtomicBoolean(false) val replaceTaskOneProvider = project.tasks.register("replaceTaskOne", ReplaceTask::class.java) { replaceTaskOneInitialized.set(true) } operations.replace(replaceTaskOneProvider, ReplaceTask::outputFile).on(TEST_REPLACABLE_FILE) Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() val replaceTaskTwoInitialized = AtomicBoolean(false) val replaceTaskTwoProvider = project.tasks.register("replaceTaskTwo", ReplaceTask::class.java) { replaceTaskTwoInitialized.set(true) } operations.replace(replaceTaskTwoProvider, ReplaceTask::outputFile).on(TEST_REPLACABLE_FILE) Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() Truth.assertThat(replaceTaskTwoInitialized.get()).isFalse() Truth.assertThat(operations.getArtifactContainer(TEST_REPLACABLE_FILE).needInitialProducer().get()) .isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputFile abstract val outputFile: RegularFileProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider( TEST_REPLACABLE_FILE, agpProducer, AGPTask::outputFile) Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() Truth.assertThat(replaceTaskTwoInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_REPLACABLE_FILE) // transform output should have the task name in its output. Truth.assertThat(replaceTaskTwoProvider.get().outputFile.get().asFile.absolutePath).contains("replaceTaskTwo") // final artifact value should be the transformer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(replaceTaskTwoProvider.get().outputFile.asFile.get().absolutePath) // agp provider should be ignored, so is the fist transform. Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() Truth.assertThat(replaceTaskTwoInitialized.get()).isTrue() } @Test fun testOverlappingDirectoryReplace() { abstract class ReplaceTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val replaceTaskOneInitialized = AtomicBoolean(false) val replaceTaskOneProvider = project.tasks.register("replaceTaskOne", ReplaceTask::class.java) { replaceTaskOneInitialized.set(true) } operations.replace(replaceTaskOneProvider, ReplaceTask::outputFolder).on(TEST_REPLACABLE_DIRECTORY) Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() val replaceTaskTwoInitialized = AtomicBoolean(false) val replaceTaskTwoProvider = project.tasks.register("replaceTaskTwo", ReplaceTask::class.java) { replaceTaskTwoInitialized.set(true) } operations.replace(replaceTaskTwoProvider, ReplaceTask::outputFolder).on(TEST_REPLACABLE_DIRECTORY) Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() Truth.assertThat(replaceTaskTwoInitialized.get()).isFalse() Truth.assertThat(operations.getArtifactContainer(TEST_REPLACABLE_DIRECTORY) .needInitialProducer().get()).isFalse() // now registers AGP provider. abstract class AGPTask: DefaultTask() { @get:OutputDirectory abstract val outputFolder: DirectoryProperty } val agpInitialized = AtomicBoolean(false) val agpProducer = project.tasks.register("agpProducer", AGPTask::class.java) { agpInitialized.set(true) } operations.setInitialProvider( TEST_REPLACABLE_DIRECTORY, agpProducer, AGPTask::outputFolder) Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() Truth.assertThat(replaceTaskTwoInitialized.get()).isFalse() val artifactContainer = operations.getArtifactContainer(TEST_REPLACABLE_DIRECTORY) // transform output should have the task name in its output. Truth.assertThat(replaceTaskTwoProvider.get().outputFolder.get().asFile.absolutePath).contains("replaceTaskTwo") // final artifact value should be the transformer task output Truth.assertThat(artifactContainer.get().get().asFile.absolutePath) .isEqualTo(replaceTaskTwoProvider.get().outputFolder.asFile.get().absolutePath) // agp provider should be ignored, so is the fist transform. Truth.assertThat(agpInitialized.get()).isFalse() Truth.assertThat(replaceTaskOneInitialized.get()).isFalse() Truth.assertThat(replaceTaskTwoInitialized.get()).isTrue() } }
0
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
31,242
vmtrace
Apache License 2.0
increase-kotlin-core/src/main/kotlin/com/increase/api/services/blocking/simulations/CardRefundService.kt
Increase
614,596,742
false
{"Kotlin": 12881439, "Shell": 1257, "Dockerfile": 305}
// File generated from our OpenAPI spec by Stainless. @file:Suppress("OVERLOADS_INTERFACE") // See https://youtrack.jetbrains.com/issue/KT-36102 package com.increase.api.services.blocking.simulations import com.increase.api.core.RequestOptions import com.increase.api.models.SimulationCardRefundCreateParams import com.increase.api.models.Transaction interface CardRefundService { /** * Simulates refunding a card transaction. The full value of the original sandbox transaction is * refunded. */ fun create( params: SimulationCardRefundCreateParams, requestOptions: RequestOptions = RequestOptions.none() ): Transaction }
0
Kotlin
0
2
496494b0adf5480bab91f61b7a6decbfe3a129fa
670
increase-kotlin
Apache License 2.0
app/src/main/java/io/github/wulkanowy/ui/modules/message/send/SendMessageActivity.kt
wulkanowy
87,721,285
false
{"Kotlin": 1659048, "HTML": 1949, "Shell": 220}
package io.github.wulkanowy.ui.modules.message.send import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.graphics.Rect import android.os.Build import android.os.Bundle import android.text.Spanned import android.view.Menu import android.view.MenuItem import android.view.TouchDelegate import android.view.View.GONE import android.view.View.VISIBLE import android.view.ViewGroup import android.widget.Toast import android.widget.Toast.LENGTH_LONG import androidx.core.text.parseAsHtml import androidx.core.text.toHtml import androidx.core.view.* import androidx.core.widget.doOnTextChanged import com.google.android.material.dialog.MaterialAlertDialogBuilder import dagger.hilt.android.AndroidEntryPoint import io.github.wulkanowy.R import io.github.wulkanowy.data.db.entities.Mailbox import io.github.wulkanowy.data.db.entities.Message import io.github.wulkanowy.databinding.ActivitySendMessageBinding import io.github.wulkanowy.ui.base.BaseActivity import io.github.wulkanowy.ui.modules.message.mailboxchooser.MailboxChooserDialog import io.github.wulkanowy.ui.modules.message.mailboxchooser.MailboxChooserDialog.Companion.LISTENER_KEY import io.github.wulkanowy.ui.modules.message.mailboxchooser.MailboxChooserDialog.Companion.MAILBOX_KEY import io.github.wulkanowy.utils.dpToPx import io.github.wulkanowy.utils.hideSoftInput import io.github.wulkanowy.utils.nullableSerializable import io.github.wulkanowy.utils.showSoftInput import javax.inject.Inject @AndroidEntryPoint class SendMessageActivity : BaseActivity<SendMessagePresenter, ActivitySendMessageBinding>(), SendMessageView { @Inject override lateinit var presenter: SendMessagePresenter companion object { private const val EXTRA_MESSAGE = "EXTRA_MESSAGE" private const val EXTRA_REASON = "EXTRA_REASON" private const val EXTRA_REPLY = "EXTRA_REPLY" fun getStartIntent(context: Context) = Intent(context, SendMessageActivity::class.java) fun getStartIntent(context: Context, message: Message?, reply: Boolean = false): Intent { return getStartIntent(context) .putExtra(EXTRA_MESSAGE, message) .putExtra(EXTRA_REPLY, reply) } fun getStartIntent(context: Context, reason: String): Intent { return getStartIntent(context) .putExtra(EXTRA_REASON, reason) } } override val isDropdownListVisible: Boolean get() = binding.sendMessageTo.isDropdownListVisible @Suppress("UNCHECKED_CAST") override lateinit var formRecipientsData: List<RecipientChipItem> override lateinit var formSubjectValue: String override lateinit var formContentValue: String override val messageRequiredRecipients: String get() = getString(R.string.message_required_recipients) override val messageContentMinLength: String get() = getString(R.string.message_content_min_length) override val messageSuccess: String get() = getString(R.string.message_send_successful) override val mailboxStudent: String get() = getString(R.string.message_mailbox_type_student) override val mailboxParent: String get() = getString(R.string.message_mailbox_type_parent) override val mailboxGuardian: String get() = getString(R.string.message_mailbox_type_guardian) override val mailboxEmployee: String get() = getString(R.string.message_mailbox_type_employee) @Suppress("UNCHECKED_CAST") public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView( ActivitySendMessageBinding.inflate(layoutInflater).apply { binding = this }.root ) setSupportActionBar(binding.sendMessageToolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { WindowCompat.setDecorFitsSystemWindows(window, false) binding.sendAppBar.isLifted = true } initializeMessageContainer() messageContainer = binding.sendMessageContainer formRecipientsData = binding.sendMessageTo.addedChipItems as List<RecipientChipItem> formSubjectValue = binding.sendMessageSubject.text.toString() formContentValue = binding.sendMessageMessageContent.text.toString().parseAsHtml().toString() binding.sendMessageFrom.setOnClickListener { presenter.onOpenMailboxChooser() } presenter.onAttachView( view = this, reason = intent.nullableSerializable(EXTRA_REASON), message = intent.nullableSerializable(EXTRA_MESSAGE), reply = intent.nullableSerializable(EXTRA_REPLY) ) supportFragmentManager.setFragmentResultListener(LISTENER_KEY, this) { _, bundle -> presenter.onMailboxSelected(bundle.nullableSerializable(MAILBOX_KEY)) } } @SuppressLint("ClickableViewAccessibility") override fun initView() { setUpExtendedHitArea() with(binding) { sendMessageScroll.setOnTouchListener { _, _ -> presenter.onTouchScroll() } sendMessageTo.onChipAddListener = { onRecipientChange() } sendMessageTo.onTextChangeListener = presenter::onRecipientsTextChange sendMessageSubject.doOnTextChanged { text, _, _, _ -> onMessageSubjectChange(text) } sendMessageMessageContent.doOnTextChanged { text, _, _, _ -> onMessageContentChange(text) } } } private fun initializeMessageContainer() { ViewCompat.setOnApplyWindowInsetsListener(binding.sendMessageScroll) { view, insets -> val navigationBarInsets = insets.getInsets(WindowInsetsCompat.Type.navigationBars()) val imeInsets = insets.getInsets(WindowInsetsCompat.Type.ime()) view.updateLayoutParams<ViewGroup.MarginLayoutParams> { bottomMargin = if (imeInsets.bottom > navigationBarInsets.bottom) { imeInsets.bottom } else { navigationBarInsets.bottom } } WindowInsetsCompat.CONSUMED } } private fun onMessageSubjectChange(text: CharSequence?) { formSubjectValue = text.toString() presenter.onMessageContentChange() } private fun onMessageContentChange(text: CharSequence?) { formContentValue = (text as Spanned).toHtml() presenter.onMessageContentChange() } private fun onRecipientChange() { presenter.onMessageContentChange() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.action_menu_send_message, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return if (item.itemId == R.id.sendMessageMenuSend) presenter.onSend() else false } override fun onSupportNavigateUp(): Boolean { return presenter.onUpNavigate() } override fun setMailbox(mailbox: String) { binding.sendMessageFrom.text = mailbox } override fun setRecipients(recipients: List<RecipientChipItem>) { binding.sendMessageTo.filterableChipItems = recipients } override fun setSelectedRecipients(recipients: List<RecipientChipItem>) { binding.sendMessageTo.addChips(recipients) } override fun showProgress(show: Boolean) { binding.sendMessageProgress.visibility = if (show) VISIBLE else GONE } override fun showContent(show: Boolean) { binding.sendMessageContent.visibility = if (show) VISIBLE else GONE } override fun showEmpty(show: Boolean) { binding.sendMessageEmpty.visibility = if (show) VISIBLE else GONE } override fun showActionBar(show: Boolean) { supportActionBar?.apply { if (show) show() else hide() } } override fun setSubject(subject: String) { binding.sendMessageSubject.setText(subject) } override fun setContent(content: String) { binding.sendMessageMessageContent.setText(content.parseAsHtml()) } override fun showMessage(text: String) { Toast.makeText(this, text, LENGTH_LONG).show() } override fun showSoftInput(show: Boolean) { if (show) showSoftInput() else hideSoftInput() } override fun hideDropdownList() { binding.sendMessageTo.hideDropdownList() } override fun scrollToRecipients() { with(binding.sendMessageScroll) { post { scrollTo(0, binding.sendMessageTo.bottom - dpToPx(53f).toInt()) } } } override fun showMailboxChooser(mailboxes: List<Mailbox>) { MailboxChooserDialog.newInstance( mailboxes = mailboxes, isMailboxRequired = true, folder = LISTENER_KEY, ).show(supportFragmentManager, "chooser") } override fun popView() { finish() } private fun setUpExtendedHitArea() { fun extendHitArea() { val containerHitRect = Rect().apply { binding.sendMessageContent.getHitRect(this) } val contentHitRect = Rect().apply { binding.sendMessageMessageContent.getHitRect(this) } contentHitRect.top = contentHitRect.bottom contentHitRect.bottom = containerHitRect.bottom binding.sendMessageContent.touchDelegate = TouchDelegate(contentHitRect, binding.sendMessageMessageContent) } with(binding.sendMessageMessageContent) { post { addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> extendHitArea() } extendHitArea() } } } override fun showMessageBackupDialog() { MaterialAlertDialogBuilder(this) .setTitle(R.string.message_title) .setMessage(presenter.getMessageBackupContent(presenter.getRecipientsNames())) .setPositiveButton(R.string.all_yes) { _, _ -> presenter.restoreMessageParts() } .setNegativeButton(R.string.all_no) { _, _ -> presenter.clearDraft() } .show() } @Suppress("UNCHECKED_CAST") override fun clearDraft() { formRecipientsData = binding.sendMessageTo.addedChipItems as List<RecipientChipItem> presenter.clearDraft() } override fun getMessageBackupDialogString() = resources.getString(R.string.message_restore_dialog) override fun getMessageBackupDialogStringWithRecipients(recipients: String) = resources.getString(R.string.message_restore_dialog_with_recipients, recipients) }
98
Kotlin
32
247
c2ec05662b73f8e106ad7f7889bf5e5d14b3b147
10,761
wulkanowy
Apache License 2.0
src/macosMain/kotlin/sample/SampleMacos.kt
snan
433,440,339
true
{"Kotlin": 1064342, "Java": 656, "CSS": 301, "HTML": 186}
package sample fun hello(): String = "Hello, Kotlin/Native!" fun main() { println(hello()) }
0
Kotlin
0
0
e0b382dddaacc36a8fa0ab919e1c2471567e22f5
98
kotlin-native-fireman
MIT License
platform/credential-store/test/testClass.kt
tnorbye
152,908,241
true
{"Java": 169603963, "Python": 25582594, "Kotlin": 6740047, "Groovy": 3535139, "HTML": 2117263, "C": 214294, "C++": 180123, "CSS": 172743, "JavaScript": 148969, "Lex": 148871, "XSLT": 113036, "Jupyter Notebook": 93222, "Shell": 60209, "NSIS": 58584, "Batchfile": 49961, "Roff": 37497, "Objective-C": 32636, "TeX": 25473, "AMPL": 20665, "TypeScript": 9958, "J": 5050, "PHP": 2699, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "Ruby": 1217, "Perl": 973, "Smalltalk": 906, "C#": 696, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Erlang": 10}
@file:Suppress("PackageDirectoryMismatch") package com.intellij.ide.passwordSafe.impl.providers.masterKey class MasterKeyPasswordSafeTest { }
1
Java
1
1
f01cf262fc196bf4dbb99e20cd937dee3705a7b6
143
intellij-community
Apache License 2.0
src/main/kotlin/me/dolphin2410/webjelly/WebJelly.kt
dolphin2410-archive
432,660,726
false
{"Kotlin": 9369}
package me.dolphin2410.webjelly import me.dolphin2410.webjelly.maven.MavenArtifact import me.dolphin2410.webjelly.maven.MavenRepository import org.apache.maven.repository.internal.MavenRepositorySystemUtils import org.eclipse.aether.RepositorySystem import org.eclipse.aether.artifact.DefaultArtifact import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory import org.eclipse.aether.repository.LocalRepository import org.eclipse.aether.repository.RemoteRepository import org.eclipse.aether.resolution.ArtifactRequest import org.eclipse.aether.spi.connector.RepositoryConnectorFactory import org.eclipse.aether.spi.connector.transport.TransporterFactory import org.eclipse.aether.transport.file.FileTransporterFactory import org.eclipse.aether.transport.http.HttpTransporterFactory import java.io.File object WebJelly { @JvmStatic fun fetchArtifact(repository: MavenRepository, artifactName: MavenArtifact, folder: File = File(System.getProperty("java.io.tmpdir"))): File { return MavenRepositorySystemUtils.newServiceLocator().apply { addService(RepositoryConnectorFactory::class.java, BasicRepositoryConnectorFactory::class.java) addService(TransporterFactory::class.java, FileTransporterFactory::class.java) addService(TransporterFactory::class.java, HttpTransporterFactory::class.java) }.getService(RepositorySystem::class.java).run { resolveArtifact( MavenRepositorySystemUtils.newSession().apply { localRepositoryManager = newLocalRepositoryManager( this, LocalRepository(folder.toString()) ) }, ArtifactRequest().apply { artifact = DefaultArtifact(artifactName.toString()) repositories = arrayListOf(RemoteRepository.Builder("public", "default", repository.url.toString()).build()) } ).artifact.file } } }
0
Kotlin
0
2
1aa7162fc3ebee5837b3544932ad0b6091db2631
2,020
WebJelly
Apache License 2.0
app/build.gradle.kts
nuhkoca
258,777,733
false
null
/* * Copyright (C) 2020. <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import common.addJUnit5TestDependencies import common.addOkHttpBom import common.addTestDependencies import dependencies.Dependencies import extensions.applyDefault import extensions.configureAndroidTests import extensions.createDebug import extensions.createKotlinAndroidTest import extensions.createKotlinMain import extensions.createKotlinTest import extensions.createRelease import extensions.createReleaseConfig import extensions.generateApplicationOutputs import extensions.getSemanticAppVersionName import extensions.setDefaults import utils.javaVersion plugins { id(Plugins.androidApplication) kotlin(Plugins.kotlinAndroid) kotlin(Plugins.kotlinAndroidExtension) kotlin(Plugins.kotlinKapt) id(Plugins.kotlinSerialization) id(Plugins.junit5) id(Plugins.safeArgs) id(Plugins.ossLicenses) } val baseUrl: String by project android { compileSdkVersion(extra["compileSdkVersion"] as Int) defaultConfig { applicationId = "io.github.nuhkoca.vivy" minSdkVersion(extra["minSdkVersion"] as Int) targetSdkVersion(extra["targetSdkVersion"] as Int) versionCode = 1 versionName = getSemanticAppVersionName() vectorDrawables.useSupportLibrary = true testApplicationId = "io.github.nuhkoca.libbra.test" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunnerArgument(Config.JUNIT5_KEY, Config.JUNIT5_VALUE) testInstrumentationRunnerArgument(Config.ORCHESTRATOR_KEY, Config.ORCHESTRATOR_VALUE) configureAndroidTests() signingConfig = signingConfigs.getByName("debug") // All supported languages should be added here. It tells all libraries that we only want to // compile these languages into our project -> Reduces .APK size resConfigs("en") } // JUnit 5 will bundle in files with identical paths; exclude them packagingOptions { exclude("META-INF/LICENSE*") } signingConfigs { createReleaseConfig(this) } buildTypes { createRelease(this) createDebug(this) generateApplicationOutputs(applicationVariants) forEach { type -> if (type.name == "release") { type.signingConfig = signingConfigs.getByName(type.name) } type.buildConfigField("String", "BASE_URL", baseUrl) } } sourceSets { createKotlinMain(this) createKotlinTest(this) createKotlinAndroidTest(this) } compileOptions { sourceCompatibility = javaVersion targetCompatibility = javaVersion } kotlinOptions { jvmTarget = javaVersion.toString() } androidExtensions { isExperimental = true } dataBinding { isEnabled = true } viewBinding { isEnabled = true } lintOptions.setDefaults() testOptions.applyDefault() } dependencies { implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) lintChecks(project(Modules.lintRules)) implementation(Dependencies.Core.kotlin) implementation(Dependencies.Core.coroutines) implementation(Dependencies.UI.material) implementation(Dependencies.UI.core_ktx) implementation(Dependencies.UI.appcompat) implementation(Dependencies.UI.fragment_ktx) implementation(Dependencies.UI.activity_ktx) implementation(Dependencies.UI.recylerview) implementation(Dependencies.UI.constraint_layout) implementation(Dependencies.Navigation.nav_fragment_ktx) implementation(Dependencies.Navigation.nav_ui_ktx) implementation(Dependencies.Pagination.runtime_ktx) implementation(Dependencies.Room.room_ktx) implementation(Dependencies.Room.runtime_ktx) kapt(Dependencies.Room.compiler) implementation(Dependencies.Lifecycle.lifecycle_extensions) implementation(Dependencies.Lifecycle.viewmodel_ktx) implementation(Dependencies.Lifecycle.livedata_ktx) implementation(Dependencies.Lifecycle.runtime_ktx) implementation(Dependencies.Lifecycle.common_java) kapt(Dependencies.Lifecycle.compiler) implementation(Dependencies.Dagger.dagger) kapt(Dependencies.Dagger.compiler) implementation(Dependencies.Network.retrofit) implementation(Dependencies.Network.retrofit_serialization_adapter) addOkHttpBom() implementation(Dependencies.Other.timber) implementation(Dependencies.Other.coil) implementation(Dependencies.Other.oss_licenses) addTestDependencies() addJUnit5TestDependencies() }
3
Kotlin
3
17
512412bef33ffdd0ab0ac2bb358a88ebb0a09c44
5,211
vivy-challenge
Apache License 2.0
corelib/src/main/java/com/exmple/corelib/base/BaseFragment.kt
mouxuefei
158,362,813
false
null
package com.exmple.corelib.base import android.content.Context import android.os.Bundle import android.support.annotation.LayoutRes import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.exmple.corelib.R import com.exmple.corelib.utils.MLoadingView import com.exmple.corelib.utils.register import com.exmple.corelib.utils.unregister /** * @FileName: com.mou.demo.basekotlin.BaseFragment.java * @author: mouxuefei * @date: 2017-12-19 15:48 * @version V1.0 <描述当前版本功能> * @desc */ abstract class BaseFragment : Fragment() { private var isViewPrepare = false private var hasLoadData = false open var mContext: Context? = null private var mProgressDialog: MLoadingView? = null protected abstract fun lazyLoad() open val useEventBus: Boolean = false @LayoutRes protected abstract fun getContentView(): Int override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val layout = getContentView() val rootView = inflater.inflate(layout, container, false) this.mContext = context if (useEventBus) { register(this) } return rootView } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) isViewPrepare = true initView(view) mProgressDialog = MLoadingView(context!!, R.style.dialog_transparent_style) savedStanceState(savedInstanceState) initData() lazyLoadDataIfPrepared() } protected abstract fun initView(view: View) open fun savedStanceState(savedInstanceState: Bundle?) {} open fun initData() {} override fun setUserVisibleHint(isVisibleToUser: Boolean) { super.setUserVisibleHint(isVisibleToUser) if (isVisibleToUser) { lazyLoadDataIfPrepared() } } private fun lazyLoadDataIfPrepared() { if (userVisibleHint&&isViewPrepare){ loadDataVisible() } if (userVisibleHint && isViewPrepare && !hasLoadData) { lazyLoad() hasLoadData = true } } open fun loadDataVisible() { } fun showProgressDialog(text: String?) { mProgressDialog?.showProgressDialogWithText(text) } fun dismissProgressDialog() { mProgressDialog?.dismissProgressDialog() } override fun onDestroy() { super.onDestroy() if (useEventBus) { unregister(this) } } } inline fun <reified F : Fragment> Context.newFragment(vararg args: Pair<String, String>): F { val bundle = Bundle() args.let { for (arg in args) { bundle.putString(arg.first, arg.second) } } return Fragment.instantiate(this, F::class.java.name, bundle) as F }
1
Kotlin
0
4
53f564af815d8cf00396c2e33c42c3aa11c0a8d1
2,932
KotlinVpExample
Apache License 2.0
android/versioned-abis/expoview-abi47_0_0/src/main/java/abi47_0_0/expo/modules/mailcomposer/MailComposerPackage.kt
betomoedano
462,599,485
true
{"TypeScript": 7804102, "Kotlin": 3383974, "Objective-C": 2722124, "Swift": 1723956, "Java": 1686584, "JavaScript": 847793, "C++": 310224, "C": 237463, "Objective-C++": 191888, "Ruby": 167983, "Shell": 59271, "HTML": 31107, "CMake": 25754, "Batchfile": 89, "CSS": 42}
package abi47_0_0.expo.modules.mailcomposer import android.content.Context import abi47_0_0.expo.modules.core.BasePackage class MailComposerPackage : BasePackage() { override fun createExportedModules(context: Context) = listOf(MailComposerModule(context)) }
0
TypeScript
0
4
52d6405570a39a87149648d045d91098374f4423
267
expo
MIT License
diktat-rules/src/test/kotlin/org/cqfn/diktat/util/TestUtils.kt
petertrr
284,037,259
false
null
package org.cqfn.diktat.util import com.pinterest.ktlint.core.KtLint import com.pinterest.ktlint.core.LintError import com.pinterest.ktlint.core.Rule import com.pinterest.ktlint.core.RuleSet import org.assertj.core.api.Assertions import org.assertj.core.api.SoftAssertions import org.cqfn.diktat.common.config.rules.RulesConfig import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.cqfn.diktat.ruleset.utils.log const val TEST_FILE_NAME = "/TestFileName.kt" @Suppress("ForbiddenComment") fun lintMethod(rule: Rule, code: String, vararg lintErrors: LintError, rulesConfigList: List<RulesConfig>? = null, fileName: String? = null) { val res = mutableListOf<LintError>() KtLint.lint( KtLint.Params( fileName = fileName ?: TEST_FILE_NAME, text = code, ruleSets = listOf(DiktatRuleSetProvider4Test(rule, rulesConfigList).get()), cb = { e, _ -> res.add(e) } ) ) Assertions.assertThat(res) .hasSize(lintErrors.size) .allSatisfy { actual -> val expected = lintErrors[res.indexOf(actual)] SoftAssertions.assertSoftly { it.assertThat(actual.line).`as`("Line").isEqualTo(expected.line) it.assertThat(actual.col).`as`("Column").isEqualTo(expected.col) it.assertThat(actual.ruleId).`as`("Rule id").isEqualTo(expected.ruleId) it.assertThat(actual.detail).`as`("Detailed message").isEqualTo(expected.detail) // fixme: fix all tests and uncomment // it.assertThat(actual.canBeAutoCorrected).`as`("Can be autocorrected").isEqualTo(expected.canBeAutoCorrected) } } } internal fun Rule.format(text: String, fileName: String, rulesConfigList: List<RulesConfig>? = emptyList()): String { return KtLint.format( KtLint.Params( text = text, ruleSets = listOf(DiktatRuleSetProvider4Test(this, rulesConfigList).get()), fileName = fileName, cb = { lintError, _ -> log.warn("Received linting error: $lintError") } ) ) } internal fun applyToCode(code: String, applyToNode: (node: ASTNode) -> Unit) { KtLint.lint( KtLint.Params( text = code, ruleSets = listOf( RuleSet("test", object : Rule("astnode-utils-test") { override fun visit(node: ASTNode, autoCorrect: Boolean, params: KtLint.Params, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit) { applyToNode(node) } }) ), cb = { _, _ -> Unit } ) ) }
3
Kotlin
0
1
45231eddab4e968db6f19a6ad82ae96f14223385
3,201
diktat-backup
MIT License
app/src/androidTest/java/dev/alexknittel/syntact/app/general/config/AndroidTestApplicationComponent.kt
alex-kn
146,649,461
false
null
package dev.alexknittel.syntact.app.general.config import android.content.Context import dagger.BindsInstance import dagger.Component import dev.alexknittel.syntact.data.config.AndroidTestDaoModule import dev.alexknittel.syntact.data.config.AndroidTestDatabaseModule import dev.alexknittel.syntact.service.config.AndroidTestNetworkModule import javax.inject.Singleton @Component(modules = [AndroidTestNetworkModule::class, AndroidTestDatabaseModule::class, AndroidTestDaoModule::class]) @Singleton interface AndroidTestApplicationComponent : ApplicationComponent { @Component.Builder interface Builder { @BindsInstance fun applicationContext(applicationContext: Context): Builder fun build(): AndroidTestApplicationComponent } }
0
Kotlin
0
0
eb06d0b01c9bb37bae25035afeef4e9dd49df4dd
771
Syntact
MIT License
clara-app/src/main/kotlin/de/unistuttgart/iste/sqa/clara/utils/kotlinx/PairExt.kt
SteveBinary
724,727,375
false
{"Kotlin": 89820}
package de.unistuttgart.iste.sqa.clara.utils.kotlinx import kotlinx.coroutines.Deferred import kotlinx.coroutines.joinAll suspend fun <A, B> Pair<Deferred<A>, Deferred<B>>.awaitBoth(): Pair<A, B> { listOf(this.first, this.second).joinAll() return Pair(this.first.await(), this.second.await()) }
0
Kotlin
0
0
1015a1ef4a5f3608a78968bf32bbf3631bb025bd
305
clara
MIT License
src/main/kotlin/init/ItemRegistry.kt
PleahMaCaka
437,354,059
false
{"Kotlin": 9045, "Java": 1910}
@file:Suppress("HasPlatformType", "unused") package com.pleahmacaka.examplemod.init import com.pleahmacaka.examplemod.MODID import com.pleahmacaka.examplemod.items.SadObsidianMaker import net.minecraft.world.item.Item import net.minecraftforge.eventbus.api.IEventBus import net.minecraftforge.registries.DeferredRegister import net.minecraftforge.registries.ForgeRegistries object ItemRegistry { // for register private val ITEMS: DeferredRegister<Item> = DeferredRegister.create(ForgeRegistries.ITEMS, MODID) fun register(bus: IEventBus) = ITEMS.register(bus) // ==================== // // Normal Items // // ==================== // val SAD_OBSIDIAN_MAKER = ITEMS.register("sad_obsidian_maker") { SadObsidianMaker } }
0
Kotlin
0
17
f218761059cab733282c38d82fb7055638ae867a
762
forge-kotlin-template
MIT License
mobile_app1/module1024/src/main/java/module1024packageKt0/Foo117.kt
uber-common
294,831,672
false
null
package module1024packageKt0; annotation class Foo117Fancy @Foo117Fancy class Foo117 { fun foo0(){ module1024packageKt0.Foo116().foo6() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } fun foo4(){ foo3() } fun foo5(){ foo4() } fun foo6(){ foo5() } }
6
Java
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
329
android-build-eval
Apache License 2.0
shared/src/commonMain/kotlin/ui/icons/Rectangle.kt
c5inco
349,346,768
false
{"Kotlin": 202698, "CSS": 635, "HTML": 470, "Shell": 438, "JavaScript": 44}
package ui.icons 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 val AppIcons.Rectangle: ImageVector get() { if (_rectangle != null) { return _rectangle!! } _rectangle = Builder(name = "Rectangle", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 18.0f) horizontalLineTo(5.0f) verticalLineTo(6.0f) horizontalLineTo(19.0f) verticalLineTo(18.0f) close() } } .build() return _rectangle!! } private var _rectangle: ImageVector? = null
5
Kotlin
3
162
2c7e8c55eeaab15e38696397a84b57475a84a6a3
1,383
Compose-Modifiers-Playground
MIT License
zcash-android-wallet-app/app/src/main/java/cash/z/android/wallet/di/annotation/ApplicationScoped.kt
gmale
151,591,683
false
null
package cash.z.android.wallet.di.annotation import javax.inject.Scope @Scope annotation class ApplicationScoped
1
Kotlin
0
1
689a9a522b4087bbf2573e1e704f6d11451def28
114
zcash-android-wallet-poc
Apache License 2.0
build/launch/src/com/intellij/tools/launch/impl/ClassPathBuilder.kt
hieuprogrammer
284,920,751
true
null
package com.intellij.tools.launch.impl import com.intellij.execution.CommandLineWrapperUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.tools.launch.ModulesProvider import com.intellij.tools.launch.PathsProvider import org.jetbrains.jps.model.JpsElementFactory import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService import org.jetbrains.jps.model.serialization.JpsProjectLoader import java.io.File import com.intellij.util.SystemProperties import org.jetbrains.jps.model.java.JpsJavaClasspathKind import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.model.module.JpsModule import org.jetbrains.jps.model.module.JpsModuleDependency import java.nio.file.Files import java.nio.file.StandardCopyOption import java.util.* import java.util.jar.Manifest internal class ClassPathBuilder(private val paths: PathsProvider, private val modules: ModulesProvider) { private val model = JpsElementFactory.getInstance().createModel() ?: throw Exception("Couldn't create JpsModel") fun build(): File { val pathVariablesConfiguration = JpsModelSerializationDataService.getOrCreatePathVariablesConfiguration(model.global) val m2HomePath = File(SystemProperties.getUserHome()) .resolve(".m2") .resolve("repository") pathVariablesConfiguration.addPathVariable("MAVEN_REPOSITORY", m2HomePath.canonicalPath) val kotlinPath = paths.communityRootFolder .resolve("build") .resolve("dependencies") .resolve("build") .resolve("kotlin") .resolve("Kotlin") .resolve("kotlinc") pathVariablesConfiguration.addPathVariable("KOTLIN_BUNDLED", kotlinPath.canonicalPath) val pathVariables = JpsModelSerializationDataService.computeAllPathVariables(model.global) JpsProjectLoader.loadProject(model.project, pathVariables, paths.projectRootFolder.canonicalPath) val productionOutput = paths.outputRootFolder.resolve("production") if (!productionOutput.isDirectory) { error("Production classes output directory is missing: $productionOutput") } JpsJavaExtensionService.getInstance().getProjectExtension(model.project)!!.outputUrl = "file://${FileUtil.toSystemIndependentName(paths.outputRootFolder.path)}" val modulesList = arrayListOf<String>() modulesList.add("intellij.platform.boot") modulesList.add(modules.mainModule) modulesList.addAll(modules.additionalModules) modulesList.add("intellij.configurationScript") return createClassPathFileForModules(modulesList) } private fun createClassPathFileForModules(modulesList: List<String>): File { val classpath = mutableListOf<String>() for (moduleName in modulesList) { val module = model.project.modules.singleOrNull { it.name == moduleName } ?: throw Exception("Module $moduleName not found") if (isModuleExcluded(module)) continue classpath.addAll(getClasspathForModule(module)) } /* println("Created classpath:") for (path in classpath.distinct().sorted()) { println(" $path") } println("-- END") */ val tempClasspathJarFile = CommandLineWrapperUtil.createClasspathJarFile(Manifest(), classpath.distinct()) val launcherFolder = paths.launcherFolder if (!launcherFolder.exists()) { launcherFolder.mkdirs() } // Important note: classpath file should start from CommandLineWrapperUtil.CLASSPATH_JAR_FILE_NAME_PREFIX val launcherClasspathPrefix = CommandLineWrapperUtil.CLASSPATH_JAR_FILE_NAME_PREFIX val launcherClasspathFile = launcherFolder.resolve("${launcherClasspathPrefix}Launcher${UUID.randomUUID()}.jar") Files.move(tempClasspathJarFile.toPath(), launcherClasspathFile.toPath(), StandardCopyOption.REPLACE_EXISTING) return launcherClasspathFile } private fun getClasspathForModule(module: JpsModule): List<String> { return JpsJavaExtensionService .dependencies(module) .recursively() .satisfying { if (it is JpsModuleDependency) !isModuleExcluded(it.module) else true } .includedIn(JpsJavaClasspathKind.runtime(modules.includeTestDependencies)) .classes().roots.filter { it.exists() }.map { it.path }.toList() } private fun isModuleExcluded(module: JpsModule?): Boolean { if (module == null) return true return modules.excludedModules.contains(module.name) } }
1
null
0
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
4,377
intellij-community
Apache License 2.0
app/src/main/kotlin/com/github/ramonrabello/smartfood/shared/presentation/BaseView.kt
ramonrabello
100,962,719
false
null
package com.github.ramonrabello.smartfood.shared.presentation /** * Created by ramonrabello on 21/08/17. */ interface BaseView { fun showProgress() fun hideProgress() fun notifyLoadingError() }
0
Kotlin
1
0
a2fc792c7a1dcce056f70dab0ce2e0a3a3505f5e
208
SmartFood
Apache License 2.0
common/compose/src/main/kotlin/app/surgo/common/compose/icons/DrawableIcons.kt
tsukiymk
382,220,719
false
{"Kotlin": 889558, "Shell": 553, "CMake": 252, "C++": 166}
package app.surgo.common.compose.icons import app.surgo.common.resources.R object DrawableIcons { val EnterHome = R.drawable.avd_home_enter val EnterExplore = R.drawable.avd_explore_enter val EnterLibraryMusic = R.drawable.avd_library_music_enter val PlayArrowToPause = R.drawable.avd_play_arrow_to_pause val ShuffleOn = R.drawable.ic_shuffle_on val ShuffleOff = R.drawable.ic_shuffle_off val ShuffleOffToOn = R.drawable.avd_shuffle_off_to_on val ShuffleOnToOff = R.drawable.avd_shuffle_on_to_off val RepeatOff = R.drawable.ic_repeat_off val RepeatOne = R.drawable.ic_repeat_one val RepeatAll = R.drawable.ic_repeat_all val LyricsOnToOff = R.drawable.avd_lyrics_on_to_off }
0
Kotlin
0
0
99038e0621ecc17e47965c3b352391c6a780f26c
728
surgo
Apache License 2.0
kotlinx-coroutines-core/common/src/internal/Atomic.kt
hltj
151,721,407
true
null
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NO_EXPLICIT_VISIBILITY_IN_API_MODE") package kotlinx.coroutines.internal import kotlinx.atomicfu.atomic import kotlinx.coroutines.* import kotlin.jvm.* import kotlin.native.concurrent.* /** * The most abstract operation that can be in process. Other threads observing an instance of this * class in the fields of their object shall invoke [perform] to help. * * @suppress **This is unstable API and it is subject to change.** */ public abstract class OpDescriptor { /** * Returns `null` is operation was performed successfully or some other * object that indicates the failure reason. */ abstract fun perform(affected: Any?): Any? /** * Returns reference to atomic operation that this descriptor is a part of or `null` * if not a part of any [AtomicOp]. */ abstract val atomicOp: AtomicOp<*>? override fun toString(): String = "$classSimpleName@$hexAddress" // debug fun isEarlierThan(that: OpDescriptor): Boolean { val thisOp = atomicOp ?: return false val thatOp = that.atomicOp ?: return false return thisOp.opSequence < thatOp.opSequence } } @SharedImmutable @JvmField internal val NO_DECISION: Any = Symbol("NO_DECISION") /** * Descriptor for multi-word atomic operation. * Based on paper * ["A Practical Multi-Word Compare-and-Swap Operation"](https://www.cl.cam.ac.uk/research/srg/netos/papers/2002-casn.pdf) * by <NAME>, <NAME> and <NAME>. * * Note: parts of atomic operation must be globally ordered. Otherwise, this implementation will produce * `StackOverflowError`. * * @suppress **This is unstable API and it is subject to change.** */ @InternalCoroutinesApi public abstract class AtomicOp<in T> : OpDescriptor() { private val _consensus = atomic<Any?>(NO_DECISION) // Returns NO_DECISION when there is not decision yet val consensus: Any? get() = _consensus.value val isDecided: Boolean get() = _consensus.value !== NO_DECISION /** * Sequence number of this multi-word operation for deadlock resolution. * An operation with lower number aborts itself with (using [RETRY_ATOMIC] error symbol) if it encounters * the need to help the operation with higher sequence number and then restarts * (using higher `opSequence` to ensure progress). * Simple operations that cannot get into the deadlock always return zero here. * * See https://github.com/Kotlin/kotlinx.coroutines/issues/504 */ open val opSequence: Long get() = 0L override val atomicOp: AtomicOp<*> get() = this fun decide(decision: Any?): Any? { assert { decision !== NO_DECISION } val current = _consensus.value if (current !== NO_DECISION) return current if (_consensus.compareAndSet(NO_DECISION, decision)) return decision return _consensus.value } abstract fun prepare(affected: T): Any? // `null` if Ok, or failure reason abstract fun complete(affected: T, failure: Any?) // failure != null if failed to prepare op // returns `null` on success @Suppress("UNCHECKED_CAST") final override fun perform(affected: Any?): Any? { // make decision on status var decision = this._consensus.value if (decision === NO_DECISION) { decision = decide(prepare(affected as T)) } // complete operation complete(affected as T, decision) return decision } } /** * A part of multi-step atomic operation [AtomicOp]. * * @suppress **This is unstable API and it is subject to change.** */ public abstract class AtomicDesc { lateinit var atomicOp: AtomicOp<*> // the reference to parent atomicOp, init when AtomicOp is created abstract fun prepare(op: AtomicOp<*>): Any? // returns `null` if prepared successfully abstract fun complete(op: AtomicOp<*>, failure: Any?) // decision == null if success } /** * It is returned as an error by [AtomicOp] implementations when they detect potential deadlock * using [AtomicOp.opSequence] numbers. */ @JvmField @SharedImmutable internal val RETRY_ATOMIC: Any = Symbol("RETRY_ATOMIC")
1
Kotlin
106
255
9565dc2d1bc33056dd4321f9f74da085e6c0f39e
4,268
kotlinx.coroutines-cn
Apache License 2.0
app/src/main/java/com/elifox/legocatalog/util/CrashReportingTree.kt
Eli-Fox
198,384,890
false
null
package com.elifox.legocatalog.util import android.util.Log import timber.log.Timber // TODO add crash reporting /** A tree which logs important information for crash reporting. */ class CrashReportingTree : Timber.Tree() { override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { if (priority == Log.VERBOSE || priority == Log.DEBUG) return //FakeCrashLibrary.log(priority, tag, message) if (t != null) { if (priority == Log.ERROR) { //FakeCrashLibrary.logError(t) } else if (priority == Log.WARN) { //FakeCrashLibrary.logWarning(t) } } } }
8
Kotlin
189
770
65bb14ed9972cc21604b13b06209e3c22c1adc3a
677
LEGO-Catalog
Apache License 2.0
app/src/main/java/io/mokshjn/style/models/Style.kt
MJ10
95,791,795
false
null
package io.mokshjn.style.models import android.graphics.Bitmap /** * Created by moksh on 29/6/17. */ data class Style(val name: String, val image: Bitmap)
1
Kotlin
7
11
b61d9760cd512f5d5d06591e204e14480e254595
159
Style
MIT License
exif/src/main/java/it/sephiroth/android/library/exif2/JpegHeader.kt
tribela
177,438,602
true
{"Kotlin": 2480525, "Java": 1546261, "Perl": 60440}
/* * Copyright (C) 2012 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 it.sephiroth.android.library.exif2 @Suppress("unused", "MemberVisibilityCanBePrivate") object JpegHeader { /** Start Of Image */ const val TAG_SOI = 0xD8 /** JFIF (JPEG File Interchange Format) */ const val TAG_M_JFIF = 0xE0 /** EXIF table */ const val TAG_M_EXIF = 0xE1 /** Product Information Comment */ const val TAG_M_COM = 0xFE /** Quantization Table */ const val TAG_M_DQT = 0xDB /** Start of frame */ const val TAG_M_SOF0 = 0xC0 const val TAG_M_SOF1 = 0xC1 const val TAG_M_SOF2 = 0xC2 const val TAG_M_SOF3 = 0xC3 const val TAG_M_DHT = 0xC4 const val TAG_M_SOF5 = 0xC5 const val TAG_M_SOF6 = 0xC6 const val TAG_M_SOF7 = 0xC7 const val TAG_M_SOF9 = 0xC9 const val TAG_M_SOF10 = 0xCA const val TAG_M_SOF11 = 0xCB const val TAG_M_SOF13 = 0xCD const val TAG_M_SOF14 = 0xCE const val TAG_M_SOF15 = 0xCF /** Start Of Scan */ const val TAG_M_SOS = 0xDA /** End of Image */ const val TAG_M_EOI = 0xD9 const val TAG_M_IPTC = 0xED /** default JFIF Header bytes */ val JFIF_HEADER = byteArrayOf( 0xff.toByte(), TAG_M_JFIF.toByte(), 0x00, 0x10, 'J'.toByte(), 'F'.toByte(), 'I'.toByte(), 'F'.toByte(), 0x00, 0x01, 0x01, 0x01, 0x01, 0x2C, 0x01, 0x2C, 0x00, 0x00 ) const val SOI = 0xFFD8.toShort() const val M_EXIF = 0xFFE1.toShort() const val M_JFIF = 0xFFE0.toShort() const val M_EOI = 0xFFD9.toShort() /** * SOF (start of frame). All value between M_SOF0 and SOF15 is SOF marker except for M_DHT, JPG, * and DAC marker. */ const val M_SOF0 = 0xFFC0.toShort() const val M_SOF1 = 0xFFC1.toShort() const val M_SOF2 = 0xFFC2.toShort() const val M_SOF3 = 0xFFC3.toShort() const val M_SOF5 = 0xFFC5.toShort() const val M_SOF6 = 0xFFC6.toShort() const val M_SOF7 = 0xFFC7.toShort() const val M_SOF9 = 0xFFC9.toShort() const val M_SOF10 = 0xFFCA.toShort() const val M_SOF11 = 0xFFCB.toShort() const val M_SOF13 = 0xFFCD.toShort() const val M_SOF14 = 0xFFCE.toShort() const val M_SOF15 = 0xFFCF.toShort() const val M_DHT = 0xFFC4.toShort() const val JPG = 0xFFC8.toShort() const val DAC = 0xFFCC.toShort() /** Define quantization table */ const val M_DQT = 0xFFDB.toShort() /** IPTC marker */ const val M_IPTC = 0xFFED.toShort() /** Start of scan (begins compressed data */ const val M_SOS = 0xFFDA.toShort() /** Comment section * */ const val M_COM = 0xFFFE.toShort() // Comment section fun isSofMarker(marker : Short) : Boolean { return marker >= M_SOF0 && marker <= M_SOF15 && marker != M_DHT && marker != JPG && marker != DAC } }
0
Kotlin
0
0
65d99b947323eb8df4c2053c586373e9f95536bc
3,211
SubwayTooter
Apache License 2.0
example-react-native/android/app/src/main/java/com/blockstack/MainApplication.kt
clydedacruz
172,174,933
true
{"Kotlin": 25260, "Objective-C": 11914, "JavaScript": 11435, "Swift": 5251, "Java": 4416, "C#": 3641, "Python": 3476, "Ruby": 1342}
package com.blockstack import android.app.Application import com.blockstack.sdk.BlockstackPackage import com.facebook.react.ReactApplication import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.shell.MainReactPackage import com.facebook.soloader.SoLoader class MainApplication : Application(), ReactApplication { private val mReactNativeHost = object : ReactNativeHost(this) { override fun getUseDeveloperSupport(): Boolean { return BuildConfig.DEBUG } override fun getPackages(): List<ReactPackage> { return arrayListOf( MainReactPackage(), BlockstackPackage() ) } override fun getJSMainModuleName(): String { return "index" } } override fun getReactNativeHost(): ReactNativeHost { return mReactNativeHost } override fun onCreate() { super.onCreate() SoLoader.init(this, /* native exopackage */ false) } }
0
Kotlin
0
0
0f95d5ef13ba57cb545951da73651a6d511fe570
1,053
blockstack-react-native
MIT License
app/src/main/java/com/eccard/popularmovies/di/ViewModelModule.kt
eccard
151,618,036
false
null
package com.eccard.popularmovies.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.eccard.popularmovies.ui.main.MainViewModel import com.eccard.popularmovies.ui.moviedetail.reviews.ReviewsViewModel import com.eccard.popularmovies.ui.moviedetail.summary.SummaryViewModel import com.eccard.popularmovies.ui.moviedetail.trailers.TrailerViewModel import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap @Module abstract class ViewModelModule { @Binds @IntoMap @ViewModelKey(MainViewModel::class) abstract fun bindMainViewModel(mainViewModel: MainViewModel) : ViewModel @Binds @IntoMap @ViewModelKey(SummaryViewModel::class) abstract fun bindSummaryViewModel(summaryViewModel: SummaryViewModel) : ViewModel @Binds @IntoMap @ViewModelKey(TrailerViewModel::class) abstract fun bindTrailerViewModel(trailerViewModel: TrailerViewModel) : ViewModel @Binds @IntoMap @ViewModelKey(ReviewsViewModel::class) abstract fun bindReviewViewModel(reviewsViewModel: ReviewsViewModel) : ViewModel @Binds abstract fun bindViewModelFactory(factory: PopularMovieViewModelFactory): ViewModelProvider.Factory }
0
Kotlin
0
0
20423e23dc44578c7599caee95335a92757b0c6d
1,230
Filmes-Famosos
MIT License
app/src/main/java/idv/chauyan/doordashlite/presentation/screen/restaurant_list/presenter/RestaurantListPresenter.kt
wangchauyan
234,817,112
false
null
package idv.chauyan.doordashlite.presentation.screen.restaurant_list.presenter import idv.chauyan.doordashlite.presentation.screen.restaurant_list.RestaurantListContract import kotlinx.coroutines.runBlocking class RestaurantListPresenter( private val restaurantListModel: RestaurantListContract.Model, private val restaurantListView: RestaurantListContract.View ) : RestaurantListContract.Presenter { override fun getRestaurantList( lat: Double, lng: Double, offset: Int, limit: Int ) { runBlocking { val data = restaurantListModel.getRestaurantList(lat, lng, offset, limit) restaurantListView.updateRestaurants(data) } } }
0
Kotlin
0
0
3c38f0f761d8501c906f02d09802bdc399c4daaa
672
DoorDashLite
MIT License
brv/src/main/java/com/drake/brv/DefaultDecoration.kt
xieqi520
464,813,491
true
{"Kotlin": 132442, "Java": 91149}
/* * Copyright (C) 2018 Drake, Inc. * * 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.drake.brv import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Rect import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import android.view.View import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.annotation.DrawableRes import androidx.annotation.LayoutRes import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.drake.brv.DefaultDecoration.Edge.Companion.computeEdge import com.drake.brv.annotaion.DividerOrientation import com.drake.brv.item.ItemExpand import kotlin.math.ceil import kotlin.math.roundToInt /** * 最强大的分割线工具 * * 1. 分隔图片 * 2. 分隔颜色 * 3. 分隔间距 * 4. 回调函数判断间隔 * 5. 首尾是否显示分隔线, 可以展示表格效果 * 6. 类型池来指定是否显示分割线 * 7. 支持全部的LayoutManager, 竖向/横向/网格分割线 * 8. 优于其他框架, 完美支持均布网格分隔物 * 9. 支持分组条目的分割线 * * @property startVisible 在[GridLayoutManager]/[StaggeredGridLayoutManager]中控制上下是否显示分割线, 在[LinearLayoutManager]中控制顶部是否显示分割线 * @property endVisible 在[GridLayoutManager]/[StaggeredGridLayoutManager]中控制左右是否显示分割线, 在[LinearLayoutManager]中控制底部是否显示分割线 * @property expandVisible 控制[ItemExpand.itemExpand]为true的情况下是否显示分割线, 但当你配置[onEnabled]后则无效, 因为此字段为其默认实现所用 * @property orientation 分割线的方向, 仅支持[GridLayoutManager], 其他LayoutManager都是根据其方向自动适应 * @property typePool 集合内包含的类型才显示分割线 */ class DefaultDecoration constructor(private val context: Context) : RecyclerView.ItemDecoration() { /** * 第一个条目之前是否显示分割线, 当处于[DividerOrientation.GRID] 时水平方向顶端和末端是否显示分割线 */ var startVisible = false /** * 最后一个条目是否显示分割线, 当处于[DividerOrientation.GRID] 时垂直方向顶端和末端是否显示分割线 */ var endVisible = false var includeVisible get() = startVisible && endVisible set(value) { startVisible = value endVisible = value } /** * 展开分组条目后该条目是否显示分割线 */ var expandVisible = false /** * 大部分情况下该值只适用于[GridLayoutManager] 或其它自定义[RecyclerView.LayoutManager] * 布局管理器为[LinearLayoutManager] 和 [StaggeredGridLayoutManager] 时,该值会通过[adjustOrientation]自动调整 */ var orientation = DividerOrientation.HORIZONTAL /** * 列表是否被反转 */ private val RecyclerView.LayoutManager.isReverseLayout: Boolean get() = when (this) { is LinearLayoutManager -> reverseLayout is StaggeredGridLayoutManager -> reverseLayout else -> false } private var size = 1 private var marginStart = 0 private var marginEnd = 0 private var divider: Drawable? = null //<editor-fold desc="类型"> var typePool: MutableList<Int>? = null private var onEnabled: (BindingAdapter.BindingViewHolder.() -> Boolean)? = null /** * 根据回调函数来决定是否启用分割线 * * @param block 函数返回值决定参数[BindingAdapter.BindingViewHolder]对应的Item是否启用分割线 */ fun onEnabled(block: BindingAdapter.BindingViewHolder.() -> Boolean) { this.onEnabled = block } /** * 添加类型后只允许该类型的条目显示分割线 * 从未添加类型则默认为允许全部条目显示分割线 * * @param typeArray 布局Id, 对应[BindingAdapter.addType]中的参数 */ fun addType(@LayoutRes vararg typeArray: Int) { if (typePool == null) { typePool = mutableListOf() onEnabled = { typePool?.contains(itemViewType) ?: true } } typeArray.forEach { typePool?.add(it) } } //</editor-fold> //<editor-fold desc="图片"> /** * 将图片作为分割线, 图片宽高即分割线宽高 */ fun setDrawable(drawable: Drawable) { divider = drawable } /** * 将图片作为分割线, 图片宽高即分割线宽高 */ fun setDrawable(@DrawableRes drawableRes: Int) { val drawable = ContextCompat.getDrawable(context, drawableRes) ?: throw IllegalArgumentException("Drawable cannot be find") divider = drawable } //</editor-fold> //<editor-fold desc="颜色"> /** * 设置分割线颜色, 如果不设置分割线宽度[setDivider]则分割线宽度默认为1px * 所谓分割线宽度指的是分割线的粗细, 而非水平宽度 */ fun setColor(@ColorInt color: Int) { divider = ColorDrawable(color) } /** * 设置分割线颜色, 如果不设置分割线宽度[setDivider]则分割线宽度默认为1px * 所谓分割线宽度指的是分割线的粗细, 而非水平宽度 * * @param color 16进制的颜色值字符串 */ fun setColor(color: String) { val parseColor = Color.parseColor(color) divider = ColorDrawable(parseColor) } /** * 设置分割线颜色, 如果不设置分割线宽度[setDivider]则分割线宽度默认为1px * 所谓分割线宽度指的是分割线的粗细, 而非水平宽度 * * @param color 颜色资源Id */ fun setColorRes(@ColorRes color: Int) { val colorRes = ContextCompat.getColor(context, color) divider = ColorDrawable(colorRes) } private var background = Color.TRANSPARENT /** * 分割线背景色 * 分割线有时候会存在间距(例如配置[setMargin])或属于虚线, 这个时候暴露出来的是RecyclerView的背景色, 所以我们可以设置一个背景色来调整 * 可以设置背景色解决不统一的问题, 默认为透明[Color.TRANSPARENT] */ fun setBackground(@ColorInt color: Int) { background = color } /** * 分割线背景色 * 分割线有时候会存在间距(例如配置[setMargin])或属于虚线, 这个时候暴露出来的是RecyclerView的背景色, 所以我们可以设置一个背景色来调整 * 可以设置背景色解决不统一的问题, 默认为透明[Color.TRANSPARENT] * * @param colorString 颜色的16进制字符串 */ fun setBackground(colorString: String) { try { background = Color.parseColor(colorString) } catch (e: Exception) { throw IllegalArgumentException("Unknown color: $colorString") } } /** * 分割线背景色 * 分割线有时候会存在间距(例如配置[setMargin])或属于虚线, 这个时候暴露出来的是RecyclerView的背景色, 所以我们可以设置一个背景色来调整 * 可以设置背景色解决不统一的问题, 默认为透明[Color.TRANSPARENT] * */ fun setBackgroundRes(@ColorRes color: Int) { background = ContextCompat.getColor(context, color) } //</editor-fold> //<editor-fold desc="间距"> /** * 设置分割线宽度 * 如果使用[setDrawable]则无效 * @param width 分割线的尺寸 (分割线垂直时为宽, 水平时为高 ) * @param dp 是否单位为dp, 默认为false即使用像素单位 */ fun setDivider(width: Int = 1, dp: Boolean = false) { if (!dp) { this.size = width } else { val density = context.resources.displayMetrics.density this.size = (density * width).roundToInt() } } /** * 设置分隔左右或上下间距, 依据分割线为垂直或者水平决定具体方向间距 * * @param start 分割线为水平则是左间距, 垂直则为上间距 * @param end 分割线为水平则是右间距, 垂直则为下间距 * @param dp 是否单位为dp, 默认为true即使用dp单位 */ fun setMargin(start: Int = 0, end: Int = 0, dp: Boolean = true) { if (!dp) { this.marginStart = start this.marginEnd = end } else { val density = context.resources.displayMetrics.density this.marginStart = (start * density).roundToInt() this.marginEnd = (end * density).roundToInt() } } //</editor-fold> //<editor-fold desc="覆写"> override fun getItemOffsets( outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State ) { val layoutManager = parent.layoutManager ?: return onEnabled?.let { val vh = parent.findContainingViewHolder(view) as BindingAdapter.BindingViewHolder val modelOrNull = vh.getModelOrNull<Any>() if (!expandVisible && modelOrNull != null && modelOrNull is ItemExpand && modelOrNull.itemExpand) return if (!it.invoke(vh)) return } val position = parent.getChildAdapterPosition(view) val height = when { divider == null -> size divider?.intrinsicHeight != -1 -> divider!!.intrinsicHeight divider?.intrinsicWidth != -1 -> divider!!.intrinsicWidth else -> size } val width = when { divider == null -> size divider?.intrinsicWidth != -1 -> divider!!.intrinsicWidth divider?.intrinsicHeight != -1 -> divider!!.intrinsicHeight else -> size } val reverseLayout = layoutManager.isReverseLayout val edge = computeEdge(position, layoutManager, reverseLayout) adjustOrientation(layoutManager) when (orientation) { DividerOrientation.HORIZONTAL -> { val top = if (reverseLayout){ if ((endVisible && edge.top) || !edge.top) height else 0 } else { if (startVisible && edge.top) height else 0 } val bottom = if (reverseLayout){ if (startVisible && edge.bottom) height else 0 } else { if ((endVisible && edge.bottom) || !edge.bottom) height else 0 } outRect.set(0, top, 0, bottom) } DividerOrientation.VERTICAL -> { val left = if (startVisible && edge.left) width else 0 val right = if ((endVisible && edge.right) || !edge.right) width else 0 outRect.set(left, 0, right, 0) } DividerOrientation.GRID -> { val spanCount = when (layoutManager) { is GridLayoutManager -> layoutManager.spanCount is StaggeredGridLayoutManager -> layoutManager.spanCount else -> 1 } val spanGroupCount = when (layoutManager) { is GridLayoutManager -> layoutManager.spanSizeLookup.getSpanGroupIndex(state.itemCount - 1, spanCount) + 1 is StaggeredGridLayoutManager -> ceil(state.itemCount / spanCount.toFloat()).toInt() else -> 1 } val spanIndex = when (layoutManager) { is GridLayoutManager -> layoutManager.spanSizeLookup.getSpanIndex(position, spanCount) is StaggeredGridLayoutManager -> (layoutManager.findViewByPosition(position)!!.layoutParams as StaggeredGridLayoutManager.LayoutParams).spanIndex else -> 0 } val spanGroupIndex = when (layoutManager) { is GridLayoutManager -> layoutManager.spanSizeLookup.getSpanGroupIndex(position, spanCount) is StaggeredGridLayoutManager -> ceil((position + 1) / spanCount.toFloat()).toInt() - 1 else -> 0 } val spanSize = when (layoutManager) { is GridLayoutManager -> layoutManager.spanSizeLookup.getSpanSize(position) else -> 1 } val orientation = when (layoutManager) { is GridLayoutManager -> layoutManager.orientation is StaggeredGridLayoutManager -> layoutManager.orientation else -> RecyclerView.VERTICAL } val left = when { endVisible && orientation == RecyclerView.VERTICAL -> width - spanIndex * width / spanCount startVisible && orientation == RecyclerView.HORIZONTAL -> width - spanIndex * width / spanCount else -> spanIndex * width / spanCount } val right = when { endVisible && orientation == RecyclerView.VERTICAL -> (spanIndex + spanSize) * width / spanCount startVisible && orientation == RecyclerView.HORIZONTAL -> (spanIndex + spanSize) * width / spanCount else -> width - (spanIndex + spanSize) * width / spanCount } val top = when { layoutManager is StaggeredGridLayoutManager -> { if (orientation == RecyclerView.VERTICAL) { if (edge.top) if (startVisible) height else 0 else 0 } else { if (edge.left) if (endVisible) width else 0 else 0 } } startVisible && orientation == RecyclerView.VERTICAL -> if (reverseLayout){ (spanGroupIndex + 1) * height / spanGroupCount } else { height - spanGroupIndex * height / spanGroupCount } else -> if (reverseLayout){ height - (spanGroupIndex + 1) * height / spanGroupCount }else{ spanGroupIndex * height / spanGroupCount } } val bottom = when { layoutManager is StaggeredGridLayoutManager -> { if (orientation == RecyclerView.VERTICAL) { if (edge.bottom) if (startVisible) height else 0 else height } else { if (edge.right) if (endVisible) width else 0 else height } } startVisible && orientation == RecyclerView.VERTICAL -> if (reverseLayout){ height - spanGroupIndex * height / spanGroupCount } else { (spanGroupIndex + 1) * height / spanGroupCount } else -> if (reverseLayout){ spanGroupIndex * height / spanGroupCount }else{ height - (spanGroupIndex + 1) * height / spanGroupCount } } if (orientation == RecyclerView.VERTICAL) { outRect.set(left, top, right, bottom) } else outRect.set(top, left, bottom, right) } } } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { val layoutManager = parent.layoutManager if (layoutManager == null || divider == null) return adjustOrientation(layoutManager) val reverseLayout = layoutManager.isReverseLayout when (orientation) { DividerOrientation.HORIZONTAL -> drawHorizontal(canvas, parent, reverseLayout) DividerOrientation.VERTICAL -> drawVertical(canvas, parent, reverseLayout) DividerOrientation.GRID -> drawGrid(canvas, parent, reverseLayout) } } //</editor-fold> /** * 自动调整不同布局管理器应该对应的[orientation] */ private fun adjustOrientation(layoutManager: RecyclerView.LayoutManager) { if (layoutManager !is GridLayoutManager && layoutManager is LinearLayoutManager) { orientation = if ((layoutManager as? LinearLayoutManager)?.orientation == RecyclerView.VERTICAL) DividerOrientation.HORIZONTAL else DividerOrientation.VERTICAL } else if (layoutManager is StaggeredGridLayoutManager) { orientation = DividerOrientation.GRID } } /** * 绘制水平分割线 */ private fun drawHorizontal(canvas: Canvas, parent: RecyclerView, reverseLayout: Boolean) { canvas.save() val left: Int val right: Int if (parent.clipToPadding) { left = parent.paddingLeft + this.marginStart right = parent.width - parent.paddingRight - marginEnd } else { left = 0 + this.marginStart right = parent.width - marginEnd } loop@ for (i in 0 until parent.childCount) { val child = parent.getChildAt(i) if (onEnabled != null) { val vh = parent.getChildViewHolder(child) as BindingAdapter.BindingViewHolder val modelOrNull = vh.getModelOrNull<Any>() if (!expandVisible && modelOrNull != null && modelOrNull is ItemExpand && modelOrNull.itemExpand) continue@loop val enabled = onEnabled?.invoke(vh) ?: true if (!enabled) continue@loop } val position = parent.getChildAdapterPosition(child) val layoutManager = parent.layoutManager ?: return val edge = computeEdge(position, layoutManager, reverseLayout) if (orientation != DividerOrientation.GRID && !endVisible && (if (reverseLayout) edge.top else edge.bottom)) { continue@loop } divider?.apply { val decoratedBounds = Rect() parent.getDecoratedBoundsWithMargins(child, decoratedBounds) val firstTop: Int val firstBottom: Int if (reverseLayout){ firstBottom = decoratedBounds.bottom firstTop = if (intrinsicHeight == -1) firstBottom - size else firstBottom - intrinsicHeight } else { firstTop = decoratedBounds.top firstBottom = if (intrinsicHeight == -1) firstTop + size else firstTop + intrinsicHeight } val top: Int val bottom: Int if (reverseLayout){ top = decoratedBounds.top bottom = if (intrinsicHeight == -1) top + size else top + intrinsicHeight } else { bottom = decoratedBounds.bottom top = if (intrinsicHeight == -1) bottom - size else bottom - intrinsicHeight } if (background != Color.TRANSPARENT) { val paint = Paint() paint.color = background paint.style = Paint.Style.FILL if (startVisible && if (reverseLayout) edge.bottom else edge.top) { val firstRect = Rect(parent.paddingLeft, firstTop, parent.width - parent.paddingRight, firstBottom) canvas.drawRect(firstRect, paint) } val rect = Rect(parent.paddingLeft, top, parent.width - parent.paddingRight, bottom) canvas.drawRect(rect, paint) } if (startVisible && if (reverseLayout) edge.bottom else edge.top) { setBounds(left, firstTop, right, firstBottom) draw(canvas) } setBounds(left, top, right, bottom) draw(canvas) } } canvas.restore() } /** * 绘制垂直分割线 */ private fun drawVertical(canvas: Canvas, parent: RecyclerView, reverseLayout: Boolean) { canvas.save() val top: Int val bottom: Int if (parent.clipToPadding) { top = parent.paddingTop + marginStart bottom = parent.height - parent.paddingBottom - marginEnd } else { top = 0 + marginStart bottom = parent.height - marginEnd } val childCount = parent.childCount loop@ for (i in 0 until childCount) { val child = parent.getChildAt(i) if (onEnabled != null) { val vh = parent.getChildViewHolder(child) as BindingAdapter.BindingViewHolder val modelOrNull = vh.getModelOrNull<Any>() if (!expandVisible && modelOrNull != null && modelOrNull is ItemExpand && modelOrNull.itemExpand) continue@loop val enabled = onEnabled?.invoke(vh) ?: true if (!enabled) continue@loop } val position = parent.getChildAdapterPosition(child) val layoutManager = parent.layoutManager ?: return val edge = computeEdge(position, layoutManager, reverseLayout) if (orientation != DividerOrientation.GRID && !endVisible && edge.right) { continue@loop } divider?.apply { val decoratedBounds = Rect() parent.getDecoratedBoundsWithMargins(child, decoratedBounds) val firstRight = if (intrinsicWidth == -1) decoratedBounds.left + size else decoratedBounds.left + intrinsicWidth val firstLeft = decoratedBounds.left val right = (decoratedBounds.right + child.translationX).roundToInt() val left = if (intrinsicWidth == -1) right - size else right - intrinsicWidth if (background != Color.TRANSPARENT) { val paint = Paint() paint.color = background paint.style = Paint.Style.FILL if (startVisible && edge.left) { val firstRect = Rect(firstLeft, parent.paddingTop, firstRight, parent.height - parent.paddingBottom) canvas.drawRect(firstRect, paint) } val rect = Rect(left, parent.paddingTop, right, parent.height - parent.paddingBottom) canvas.drawRect(rect, paint) } if (startVisible && edge.left) { setBounds(firstLeft, top, firstRight, bottom) draw(canvas) } setBounds(left, top, right, bottom) draw(canvas) } } canvas.restore() } /** * 绘制网格分割线 */ private fun drawGrid(canvas: Canvas, parent: RecyclerView, reverseLayout: Boolean) { canvas.save() val childCount = parent.childCount loop@ for (i in 0 until childCount) { val child = parent.getChildAt(i) if (onEnabled != null) { val vh = parent.getChildViewHolder(child) as BindingAdapter.BindingViewHolder val modelOrNull = vh.getModelOrNull<Any>() if (!expandVisible && modelOrNull != null && modelOrNull is ItemExpand && modelOrNull.itemExpand) continue@loop val enabled = onEnabled?.invoke(vh) ?: true if (!enabled) continue@loop } val position = parent.getChildAdapterPosition(child) val layoutManager = parent.layoutManager ?: return val edge = computeEdge(position, layoutManager, reverseLayout) val height = when { divider == null -> size divider?.intrinsicHeight != -1 -> divider!!.intrinsicHeight divider?.intrinsicWidth != -1 -> divider!!.intrinsicWidth else -> size } val width = when { divider == null -> size divider?.intrinsicWidth != -1 -> divider!!.intrinsicWidth divider?.intrinsicHeight != -1 -> divider!!.intrinsicHeight else -> size } divider?.apply { val layoutParams = child.layoutParams as RecyclerView.LayoutParams val bounds = Rect( child.left + layoutParams.leftMargin, child.top + layoutParams.topMargin, child.right + layoutParams.rightMargin, child.bottom + layoutParams.bottomMargin ) // top if (!endVisible && edge.right) { setBounds(bounds.left - width, bounds.top - height, bounds.right - marginEnd, bounds.top) draw(canvas) } else if (!endVisible && !edge.top && edge.left) { setBounds(bounds.left + marginStart, bounds.top - height, bounds.right + width, bounds.top) draw(canvas) } else if (!edge.top || (startVisible && edge.top)) { setBounds(bounds.left - width, bounds.top - height, bounds.right + width, bounds.top) draw(canvas) } // bottom if (!endVisible && edge.right) { setBounds(bounds.left - width, bounds.bottom, bounds.right - marginEnd, bounds.bottom + height) draw(canvas) } else if (!endVisible && !edge.bottom && edge.left) { setBounds(bounds.left + marginStart, bounds.bottom, bounds.right + width, bounds.bottom + height) draw(canvas) } else if (!edge.bottom || (startVisible && edge.bottom)) { setBounds(bounds.left - width, bounds.bottom, bounds.right + width, bounds.bottom + height) draw(canvas) } // left if (edge.top && !endVisible && !edge.left) { setBounds(bounds.left - width, bounds.top + marginStart, bounds.left, bounds.bottom) draw(canvas) } else if (edge.bottom && !endVisible && !edge.left) { setBounds(bounds.left - width, bounds.top, bounds.left, bounds.bottom - marginEnd) draw(canvas) } else if (!edge.left || (endVisible && edge.left)) { setBounds(bounds.left - width, bounds.top, bounds.left, bounds.bottom) draw(canvas) } // right if (edge.top && !endVisible && !edge.right) { setBounds(bounds.right, bounds.top + marginStart, bounds.right + width, bounds.bottom) draw(canvas) } else if (edge.bottom && !endVisible && !edge.right) { setBounds(bounds.right, bounds.top, bounds.right + width, bounds.bottom - marginEnd) draw(canvas) } else if (!edge.right || (endVisible && edge.right)) { setBounds(bounds.right, bounds.top, bounds.right + width, bounds.bottom) draw(canvas) } } } canvas.restore() } /** * 列表条目是否靠近边缘的结算结果 * * @param left 是否靠左 * @param right 是否靠左 * @param top 是否靠顶 * @param bottom 是否靠底 */ data class Edge( var left: Boolean = false, var top: Boolean = false, var right: Boolean = false, var bottom: Boolean = false ) { companion object { /** * 计算指定条目的边缘位置 * @param position 指定计算的Item索引 * @param layoutManager 当前列表的LayoutManager */ fun computeEdge(position: Int, layoutManager: RecyclerView.LayoutManager, reverseLayout: Boolean): Edge { val index = position + 1 val itemCount = layoutManager.itemCount return Edge().apply { when (layoutManager) { is StaggeredGridLayoutManager -> { val spanCount = layoutManager.spanCount val spanIndex = (layoutManager.findViewByPosition(position)!!.layoutParams as StaggeredGridLayoutManager.LayoutParams).spanIndex + 1 if (layoutManager.orientation == RecyclerView.VERTICAL) { left = spanIndex == 1 right = spanIndex == spanCount top = if (reverseLayout) index > itemCount - spanCount else index <= spanCount bottom = if (reverseLayout) index <= spanCount else index > itemCount - spanCount } else { left = index <= spanCount right = index > itemCount - spanCount top = if (reverseLayout) spanIndex == spanCount else spanIndex == 1 bottom = if (reverseLayout) spanIndex == 1 else spanIndex == spanCount } } is GridLayoutManager -> { val spanSizeLookup = layoutManager.spanSizeLookup val spanCount = layoutManager.spanCount val spanGroupIndex = spanSizeLookup.getSpanGroupIndex(position, spanCount) val maxSpanGroupIndex = ceil(itemCount / spanCount.toFloat()).toInt() val spanIndex = spanSizeLookup.getSpanIndex(position, spanCount) + 1 val spanSize = spanSizeLookup.getSpanSize(position) if (layoutManager.orientation == RecyclerView.VERTICAL) { left = spanIndex == 1 right = spanIndex + spanSize - 1 == spanCount top = if (reverseLayout) { spanGroupIndex == maxSpanGroupIndex - 1 } else { index <= spanCount && spanGroupIndex == spanSizeLookup.getSpanGroupIndex( position - 1, spanCount ) } bottom = if (reverseLayout) { index <= spanCount && spanGroupIndex == spanSizeLookup.getSpanGroupIndex( position - 1, spanCount ) } else { spanGroupIndex == maxSpanGroupIndex - 1 } } else { left = spanGroupIndex == 0 right = spanGroupIndex == maxSpanGroupIndex - 1 top = if (reverseLayout) spanIndex + spanSize - 1 == spanCount else spanIndex == 1 bottom = if (reverseLayout) spanIndex == 1 else spanIndex + spanSize - 1 == spanCount } } is LinearLayoutManager -> { if (layoutManager.orientation == RecyclerView.VERTICAL) { left = true right = true top = if (reverseLayout) index == itemCount else index == 1 bottom = if (reverseLayout) index == 1 else index == itemCount } else { left = index == 1 right = index == itemCount top = true bottom = true } } } } } } } }
0
null
0
1
335f9e1f11e9c5eb65ff3ee5f70bc1762544117a
33,467
BRV
Apache License 2.0
app/src/main/java/com/ibrajix/nftapp/network/Resource.kt
ibrajix
470,727,913
false
{"Kotlin": 23585}
/* * Created by <NAME> on 17/03/2022, 7:43 PM * https://linktr.ee/Ibrajix * Copyright (c) 2022. * All rights reserved. */ package com.ibrajix.nftapp.network import okhttp3.ResponseBody sealed class Resource<out T> { data class Success<out T>(val value: T) : Resource<T>() data class Failure( val isNetworkError: Boolean, val errorCode: Int?, val errorBody: ResponseBody? ) : Resource<Nothing>() object Loading : Resource<Nothing>() }
0
Kotlin
11
80
94eb98747ccda23b3c333efc6fc24961be769516
504
NftApp
Apache License 2.0
app/src/test/java/com/roomedia/dakku/ExtensionsUnitTest.kt
roomedia
345,097,188
false
null
package com.roomedia.dakku import com.roomedia.dakku.persistence.Diary import com.roomedia.dakku.ui.util.splitByWeek import com.roomedia.dakku.ui.util.toWeekString import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test import java.text.SimpleDateFormat class ExtensionsUnitTest { private val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd") @Test fun isInSameWeek_isTrue() { val data1 = Diary(simpleDateFormat.parse("2021-03-07")!!.time, "") val data2 = Diary(simpleDateFormat.parse("2021-03-10")!!.time, "") assertTrue(data1.isInSameWeek(data2)) } @Test fun splitByWeek_isCorrect() { val dataset = listOf( Diary(simpleDateFormat.parse("2021-02-10")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-10")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-13")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-14")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-15")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-18")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-20")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-21")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-21")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-27")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-01")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-02")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-04")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-04")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-05")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-06")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-08")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-10")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-12")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-13")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-14")!!.time, ""), ) val expected = listOf( listOf( Diary(simpleDateFormat.parse("2021-02-10")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-10")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-13")!!.time, ""), ), listOf( Diary(simpleDateFormat.parse("2021-02-14")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-15")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-18")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-20")!!.time, ""), ), listOf( Diary(simpleDateFormat.parse("2021-02-21")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-21")!!.time, ""), Diary(simpleDateFormat.parse("2021-02-27")!!.time, ""), ), listOf( Diary(simpleDateFormat.parse("2021-03-01")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-02")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-04")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-04")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-05")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-06")!!.time, ""), ), listOf( Diary(simpleDateFormat.parse("2021-03-08")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-10")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-12")!!.time, ""), Diary(simpleDateFormat.parse("2021-03-13")!!.time, ""), ), listOf( Diary(simpleDateFormat.parse("2021-03-14")!!.time, ""), ), ) val actual = dataset.splitByWeek() assertEquals(expected, actual) } @Test fun toWeekString_isCorrect() { val localeDateFormat = SimpleDateFormat("MM월 dd일") val actual = listOf( Diary(SimpleDateFormat("yyyy-MM-dd").parse("2021-03-10")!!.time, "") ).toWeekString(localeDateFormat) assertEquals("03월 07일 - 03월 13일", actual) } }
1
Kotlin
1
2
fe13a1d9ac8efc0d3a43ecb0b05329e0f766ea2d
4,323
dakku
MIT License
core-spotify/src/main/java/com/clipfinder/core/spotify/usecase/GetNewReleases.kt
tosoba
133,674,301
false
null
package com.clipfinder.core.spotify.usecase import com.clipfinder.core.model.Paged import com.clipfinder.core.model.Resource import com.clipfinder.core.model.UseCaseWithArgs import com.clipfinder.core.spotify.model.ISpotifySimplifiedAlbum import com.clipfinder.core.spotify.repo.ISpotifyRepo import io.reactivex.Single class GetNewReleases(private val remote: ISpotifyRepo) : UseCaseWithArgs<Int, Single<Resource<Paged<List<ISpotifySimplifiedAlbum>>>>> { override fun run(args: Int): Single<Resource<Paged<List<ISpotifySimplifiedAlbum>>>> = remote.getNewReleases(offset = args) }
0
Kotlin
0
1
84ae309c8c059308c16902ee43b0cdfd2740794c
598
ClipFinder
MIT License
app/src/main/java/com/example/knucseapp/ui/board/noticeboard/NoticeBoardFragment.kt
KNU-CSE-APP
382,007,598
false
null
package com.example.knucseapp.ui.board.noticeboard import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import com.example.knucseapp.R import com.example.knucseapp.data.repository.BoardRepository import com.example.knucseapp.databinding.NoticeBoardFragmentBinding import com.example.knucseapp.ui.board.BoardViewModel import com.example.knucseapp.ui.board.BoardViewModelFactory import com.example.knucseapp.ui.util.MyApplication import com.example.knucseapp.ui.util.NetworkConnection import com.example.knucseapp.ui.util.NetworkStatus class NoticeBoardFragment : Fragment() { private lateinit var viewModel: BoardViewModel private lateinit var viewModelFactory: BoardViewModelFactory private lateinit var binding : NoticeBoardFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = DataBindingUtil.inflate(inflater, R.layout.notice_board_fragment,container,false) viewModelFactory = BoardViewModelFactory(BoardRepository()) viewModel = ViewModelProvider(this, viewModelFactory).get(BoardViewModel::class.java) binding.viewModel= viewModel binding.lifecycleOwner = this return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // activity?.onBackPressedDispatcher?.addCallback(backPressedDispatcher) setviewModel() // setRecyclerView() val connection = NetworkConnection(MyApplication.instance.context()) connection.observe(viewLifecycleOwner) { isConnected -> if (isConnected) { binding.connectedLayout.visibility = View.VISIBLE binding.disconnectedLayout.visibility = View.GONE NetworkStatus.status = true } else { binding.connectedLayout.visibility = View.GONE binding.disconnectedLayout.visibility = View.VISIBLE NetworkStatus.status = false } } } fun setviewModel() { } }
2
Kotlin
2
3
6d84ad36d6ea742cfc4e8cfb0d3dcb8df4e6c229
2,363
Android
MIT License
src/test/kotlin/org/rust/ide/inspections/RsLiftInspectionTest.kt
intellij-rust
42,619,487
false
{"Kotlin": 11390660, "Rust": 176571, "Python": 109964, "HTML": 23157, "Lex": 12605, "ANTLR": 3304, "Java": 688, "Shell": 377, "RenderScript": 343}
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.inspections import org.rust.CheckTestmarkHit import org.rust.SkipTestWrapping class RsLiftInspectionTest : RsInspectionsTestBase(RsLiftInspection::class) { fun `test lift return in if 1`() = checkFixByText("Lift return out of 'if'", """ fn foo(x: bool) -> i32 { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*caret*//*weak_warning**/ x { println("Hello!"); return 1 } else { return 0 } } """, """ fn foo(x: bool) -> i32 { return if x { println("Hello!"); 1 } else { 0 } } """, checkWeakWarn = true) fun `test lift return in if 2`() = checkFixByText("Lift return out of 'if'", """ fn foo(x: bool) -> i32 { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*caret*//*weak_warning**/ x { return 1; } else { return 0; }; } """, """ fn foo(x: bool) -> i32 { return if x { 1 } else { 0 }; } """, checkWeakWarn = true) fun `test lift return in if unavailable`() = checkFixIsUnavailable("Lift return out of 'if'", """ fn foo(x: bool) -> i32 { if/*caret*/ x { 1 } else { return 0; }; return 1; } """, checkWeakWarn = true) @SkipTestWrapping // TODO remove after enabling quick-fixes @CheckTestmarkHit(RsLiftInspection.Testmarks.InsideRetExpr::class) fun `test lift return in if with return`() = checkFixByText("Lift return out of 'if'", """ fn foo(x: bool) -> i32 { return /*weak_warning descr="Return can be lifted out of 'if'"*/if/*caret*//*weak_warning**/ x { return 1; } else { return 0; }; } """, """ fn foo(x: bool) -> i32 { return if x { 1 } else { 0 }; } """, checkWeakWarn = true) fun `test lift return in else if`() = checkFixIsUnavailable("Lift return out of 'if'", """ fn get_char(n: u32) -> char { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*weak_warning**/ n == 0 { return 'a' } else /*caret*/if n == 1 { return 'b' } else { return 'c' } } """, checkWeakWarn = true) fun `test lift return in if with else if`() = checkFixByText("Lift return out of 'if'", """ fn get_char(n: u32) -> char { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*caret*//*weak_warning**/ n == 0 { return 'a' } else if n == 1 { return 'b' } else if n == 2 { return 'c' } else { return 'd' } } """, """ fn get_char(n: u32) -> char { return if n == 0 { 'a' } else if n == 1 { 'b' } else if n == 2 { 'c' } else { 'd' } } """, checkWeakWarn = true) fun `test lift return in match 1`() = checkFixByText("Lift return out of 'match'", """ fn foo(x: bool) -> i32 { /*weak_warning descr="Return can be lifted out of 'match'"*/match/*caret*//*weak_warning**/ x { true => return 1, false => return 0 } } """, """ fn foo(x: bool) -> i32 { return match x { true => 1, false => 0 } } """, checkWeakWarn = true) fun `test lift return in match 2`() = checkFixByText("Lift return out of 'match'", """ fn foo(x: bool) -> i32 { /*weak_warning descr="Return can be lifted out of 'match'"*/match/*caret*//*weak_warning**/ x { true => { return 1 }, false => { return 0; } } } """, """ fn foo(x: bool) -> i32 { return match x { true => { 1 }, false => { 0 } } } """, checkWeakWarn = true) fun `test lift return in match unavailable`() = checkFixIsUnavailable("Lift return out of 'if'", """ fn foo(x: bool) -> i32 { match x/*caret*/ { true => return 1, false => { println("Oops"); } } return 0; } """, checkWeakWarn = true) fun `test lift return from nested blocks`() = checkFixByText("Lift return out of 'if'", """ fn foo(x: bool, y: bool, z: bool) -> i32 { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*caret*//*weak_warning**/ x { /*weak_warning descr="Return can be lifted out of 'match'"*/match/*weak_warning**/ y { true => return 1, false => { return 2; } } } else { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*weak_warning**/ z { return 3; } else { { return 4 } } } } """, """ fn foo(x: bool, y: bool, z: bool) -> i32 { return if x { match y { true => 1, false => { 2 } } } else { if z { 3 } else { { 4 } } } } """, checkWeakWarn = true) fun `test inspection doesn't trigger on return without expression`() = checkFixIsUnavailable("Lift return out of 'if'", """ fn foo(x: i32) { if/*caret*/ x < 0 { println!("< 0"); return; } else { println!("> 0"); return; } } """, checkWeakWarn = true) fun `test keep comments`() = checkFixByText("Lift return out of 'if'", """ fn foo(x: i32) -> bool { /*weak_warning descr="Return can be lifted out of 'if'"*/if/*caret*//*weak_warning**/ x < 0 { return true; // comment 1 } else { return false // comment 2 } } """, """ fn foo(x: i32) -> bool { return if x < 0 { true // comment 1 } else { false // comment 2 } } """, checkWeakWarn = true) fun `test lift return in empty match unavailable`() = checkFixIsUnavailable("Lift return out of 'match'", """ fn foo() { match/*caret*/ true { } let x = 1; } """, checkWeakWarn = true) fun `test lift return in match arm without comma`() = checkFixByText("Lift return out of 'match'", """ fn foo() -> isize { /*weak_warning descr="Return can be lifted out of 'match'"*/match/*weak_warning**/ Some(0) { Some(x) => /*weak_warning descr="Return can be lifted out of 'match'"*//*caret*/match/*weak_warning**/ x { 0 => return 1, _ => return 0, } None => return -1, } } """, """ fn foo() -> isize { match Some(0) { Some(x) => return match x { 0 => 1, _ => 0, }, None => return -1, } } """, checkWeakWarn = true) fun `test lift return in match arm with comma`() = checkFixByText("Lift return out of 'match'", """ fn foo() -> isize { /*weak_warning descr="Return can be lifted out of 'match'"*/match/*weak_warning**/ Some(0) { Some(x) => /*weak_warning descr="Return can be lifted out of 'match'"*//*caret*/match/*weak_warning**/ x { 0 => return 1, _ => return 0, }, None => return -1, } } """, """ fn foo() -> isize { match Some(0) { Some(x) => return match x { 0 => 1, _ => 0, }, None => return -1, } } """, checkWeakWarn = true) fun `test lift return in last match arm without comma`() = checkFixByText("Lift return out of 'match'", """ fn foo() -> isize { /*weak_warning descr="Return can be lifted out of 'match'"*/match/*weak_warning**/ Some(0) { None => return -1, Some(x) => /*weak_warning descr="Return can be lifted out of 'match'"*//*caret*/match/*weak_warning**/ x { 0 => return 1, _ => return 0, } } } """, """ fn foo() -> isize { match Some(0) { None => return -1, Some(x) => return match x { 0 => 1, _ => 0, } } } """, checkWeakWarn = true) }
1,843
Kotlin
392
4,524
c6657c02bb62075bf7b7ceb84d000f93dda34dc1
9,880
intellij-rust
MIT License
app/src/main/java/com/implizstudio/android/app/pitzz/ui/bnv/favorite/FavoriteFragment.kt
fajaragungpramana
222,623,193
false
null
package com.implizstudio.android.app.pitzz.ui.bnv.favorite import android.os.Bundle import android.view.* import androidx.fragment.app.Fragment import com.implizstudio.android.app.pitzz.R import com.implizstudio.android.app.pitzz.ui.adapter.TabAdapter import com.implizstudio.android.app.pitzz.ui.tab.movie.FavoriteMovieTab import com.implizstudio.android.app.pitzz.ui.tab.television.FavoriteTelevisionTab import kotlinx.android.synthetic.main.fragment_favorite.* class FavoriteFragment : Fragment() { override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_favorite, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setHasOptionsMenu(true) activity?.title = getString(R.string.favorites) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) vp_favorite.let { it.adapter = TabAdapter(childFragmentManager).apply { setup(FavoriteMovieTab(), getString(R.string.movies)) setup(FavoriteTelevisionTab(), getString(R.string.televisions)) } tl_favorite.setupWithViewPager(it) } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) menu.findItem(R.id.action_search).isVisible = false } }
0
Kotlin
0
3
0bfaaf0be4c3fa62a9fb920ff3bb8c7e1a88bae1
1,551
android.pitzz.cinema
Apache License 2.0
src/main/kotlin/eu/mc80/java/fizzbuzz/CommandLineParserParametersExtractor.kt
clavelm
45,032,281
false
{"Kotlin": 2411, "Groovy": 2045, "Java": 1452}
package eu.mc80.java.fizzbuzz import org.apache.commons.cli.DefaultParser import org.apache.commons.cli.Option import org.apache.commons.cli.Options import org.apache.commons.cli.ParseException class CommandLineParserParametersExtractor : ParametersExtractor { override fun getEnd(vararg args: String): Int? { val endOption = Option.builder("e").required().longOpt("end").hasArg().build() val options = Options() options.addOption(endOption) val parser = DefaultParser() val cmd = try { parser.parse(options, args) } catch (_: ParseException) { return null } return try { Integer.parseInt(cmd.getOptionValue(endOption.opt)) } catch (_: NumberFormatException) { null } } }
0
Kotlin
0
0
b7b480767a2800030b015746cf63e18cfe0da5d6
812
FizzBuzz
Creative Commons Zero v1.0 Universal
sample/src/jsMain/kotlin/main.js.kt
eqoty-labs
473,021,738
false
{"Kotlin": 212859, "Swift": 3532, "JavaScript": 427}
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.NoLiveLiterals import androidx.compose.ui.Modifier import androidx.compose.ui.window.Window import io.eqoty.secretk.client.SigningCosmWasmClient import io.eqoty.utils.KeplrEnigmaUtils import io.eqoty.wallet.MetaMaskWalletWrapper import io.eqoty.wallet.OfflineSignerOnlyAminoWalletWrapper import jslib.walletconnect.* import jslibs.secretjs.MetaMaskWallet import kotlinx.browser.window import kotlinx.coroutines.MainScope import kotlinx.coroutines.await import kotlinx.coroutines.delay import kotlinx.coroutines.launch import org.jetbrains.skiko.wasm.onWasmReady import org.khronos.webgl.Uint8Array import org.w3c.dom.get import web3.Web3 import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine import kotlin.js.Promise @NoLiveLiterals fun main() { application { val chain = Chain.Pulsar3 // val client = getClientWithMetamaskWallet(Chain.Pulsar2) // val client = setupEthWalletConnectAndGetWallet(Chain.Pulsar2) val wallet = getClientWithKeplrWallet(chain) // val client = setupCosmosWalletConnectAndGetWallet(Chain.Secret4, WalletConnectModal.Keplr) val accAddress = wallet.getAccounts()[0].address println(accAddress) val enigmaUtils = when (wallet) { is OfflineSignerOnlyAminoWalletWrapper -> KeplrEnigmaUtils(wallet.keplr, chain.id) else -> { TODO() } } val client = SigningCosmWasmClient.init( chain.grpcGatewayEndpoint, wallet, enigmaUtils = enigmaUtils ) console.log(client) onWasmReady { Window("secretk demo") { Column(modifier = Modifier.fillMaxSize()) { SampleApp(client, accAddress) { Row { Button({ if (client.wallet is OfflineSignerOnlyAminoWalletWrapper) { val keplr = (client.wallet as OfflineSignerOnlyAminoWalletWrapper).keplr (keplr.suggestToken( Chain.Secret4.id, "<KEY>", "the_viewing_key", true ) as Promise<Unit>).then { console.log("token suggested") } } }) { Text("Suggest token") } } Row { Button({ if (client.wallet is OfflineSignerOnlyAminoWalletWrapper) { val keplr = (client.wallet as OfflineSignerOnlyAminoWalletWrapper).keplr (keplr.getSecret20QueryAuthorization( Chain.Secret4.id, "<KEY>", ) as Promise<dynamic>).then { result: dynamic -> console.log("Get Query Authorization: ${JSON.stringify(result)}") } } }) { Text("Get Query Authorization") } } } } } } } } fun application(block: suspend () -> Unit) { MainScope().launch { block() } } suspend fun getClientWithKeplrWallet( chain: Chain, keplr: dynamic = null, suggestChain: Boolean = true ): OfflineSignerOnlyAminoWalletWrapper { @Suppress("NAME_SHADOWING") val keplr = if (keplr == null) { while ( window.asDynamic().keplr == null || window.asDynamic().getOfflineSignerOnlyAmino == null || window.asDynamic().getEnigmaUtils == null ) { delay(10) } window.asDynamic().keplr } else { keplr } if (suggestChain) { val chainId = chain.id val chainName = "Local Testnet" //Anything you want val lcdUrl = chain.grpcGatewayEndpoint val rpcUrl = chain.rpcEndpoint val denom = "SCRT" val minimalDenom = "uscrt" val suggestion: dynamic = JSON.parse( """{ "chainId": "$chainId", "chainName": "$chainName", "rpc": "$rpcUrl", "rest": "$lcdUrl", "bip44": { "coinType": 529 }, "alternativeBIP44s": [ { "coinType": 118 } ], "coinType": 529, "stakeCurrency": { "coinDenom": "$denom", "coinMinimalDenom": "$minimalDenom", "coinDecimals": 6, "coinGeckoId": "secret", "coinImageUrl": "https://dhj8dql1kzq2v.cloudfront.net/white/secret.png" }, "bech32Config": { "bech32PrefixAccAddr": "secret", "bech32PrefixAccPub": "secretpub", "bech32PrefixValAddr": "secretvaloper", "bech32PrefixValPub": "secretvaloperpub", "bech32PrefixConsAddr": "secretvalcons", "bech32PrefixConsPub": "secretvalconspub" }, "currencies": [ { "coinDenom": "$denom", "coinMinimalDenom": "$minimalDenom", "coinDecimals": 6, "coinGeckoId": "secret", "coinImageUrl": "https://dhj8dql1kzq2v.cloudfront.net/white/secret.png" } ], "feeCurrencies": [ { "coinDenom": "$denom", "coinMinimalDenom": "$minimalDenom", "coinDecimals": 6, "coinGeckoId": "secret", "coinImageUrl": "https://dhj8dql1kzq2v.cloudfront.net/white/secret.png", "gasPriceStep": { "low": 0.1, "average": 0.25, "high": 0.4 } } ], "chainSymbolImageUrl": "https://dhj8dql1kzq2v.cloudfront.net/white/secret.png", "features": ["secretwasm", "ibc-go", "ibc-transfer"] }""" ) console.log(suggestion) val suggestChainPromise: Promise<dynamic> = keplr.experimentalSuggestChain(suggestion) as Promise<dynamic> suggestChainPromise.await() } val enablePromise: Promise<dynamic> = keplr.enable(chain.id) as Promise<dynamic> enablePromise.await() return OfflineSignerOnlyAminoWalletWrapper(keplr, chain.id) } suspend fun getClientWithMetamaskWallet(chain: Chain): MetaMaskWalletWrapper { val provider = window["ethereum"] val web3 = Web3(provider).apply { eth.handleRevert = true } val account = web3.eth.requestAccounts().await().firstOrNull()!! return MetaMaskWalletWrapper(MetaMaskWallet.create(provider, account).await()) } enum class WalletConnectModal(val signingMethods: Array<String>, val qrcodeModal: IQRCodeModal) { Keplr( signingMethods = arrayOf( "keplr_enable_wallet_connect_v1", "keplr_sign_amino_wallet_connect_v1", ), qrcodeModal = KeplrQRCodeModalV1() ), Cosmostation( signingMethods = arrayOf( // "cosmostation_enable_wallet_connect_v1", // "cosmostation_sign_amino_wallet_connect_v1", "cosmostation_wc_accounts_v1", "cosmostation_wc_sign_tx_v1", ), qrcodeModal = CosmostationWCModal() ) } suspend fun setupCosmosWalletConnectAndGetWallet( chain: Chain, wcModal: WalletConnectModal ): OfflineSignerOnlyAminoWalletWrapper { val connector = WalletConnect( IWalletConnectOptionsInstance( bridge = "https://bridge.walletconnect.org", // Required signingMethods = wcModal.signingMethods, qrcodeModal = wcModal.qrcodeModal, ) ) val keplr = if (!connector.connected) { connector.createSession().await() suspendCoroutine<KeplrWalletConnectV1> { continuation -> connector.on("connect") { error, payload -> if (error != null) { continuation.resumeWithException(error) } else { val keplr = KeplrWalletConnectV1(connector, KeplrWalletConnectV1OptionsInstance(null) { a, b, c -> console.log("SEND TX CALLED") Promise.resolve(Uint8Array(1)) } ) continuation.resume(keplr) } } } } else { KeplrWalletConnectV1(connector, KeplrWalletConnectV1OptionsInstance(null) { a, b, c -> console.log("SEND TX CALLED") Promise.resolve(Uint8Array(1)) } ) } // experimentalSuggestChain not implemented yet on WalletConnect // https://github.com/chainapsis/keplr-wallet/blob/682c8402ccd09b35cecf9f028d97635b6a5cd015/packages/wc-client/src/index.ts#L275 return getClientWithKeplrWallet(chain, keplr, false) } suspend fun setupEthWalletConnectAndGetWallet(chain: Chain): MetaMaskWalletWrapper { val provider = WalletConnectProvider( IWalletConnectProviderOptionsInstance( infuraId = "YOUR_ID", ) ) try { (provider as WalletConnectProvider).enable().await() } catch (t: Throwable) { println("WalletConnectProvider.enable() returned error ${t.message}") } val web3 = Web3(provider).apply { eth.handleRevert = true } val account = web3.eth.getAccounts().await().firstOrNull()!! return MetaMaskWalletWrapper(MetaMaskWallet.create(provider, account).await()) }
6
Kotlin
2
11
b534eee367d9b874ec125c8c9b8999dbbbb6052d
10,582
secretk
MIT License
src/main/java/com/p2p/lending/controller/LoignController.kt
lordqyxz
209,478,108
false
{"Kotlin": 245038, "Java": 773}
package com.p2p.lending.controller import com.p2p.lending.service.BidService import com.p2p.lending.service.UsersService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.RequestMapping import javax.annotation.Resource /** * @author 周旗 2017-2-23 10:19:37 网站消息通知控制层 */ @Controller @RequestMapping("log") class LoignController { @Resource private val bidService: BidService? = null @Autowired private val usersService: UsersService? = null @RequestMapping("tologin") fun tologin(model: Model): String { val i = bidService!!.tosize() val j = bidService.tosizew() //查询所有新用户 model.addAttribute("tos", i) model.addAttribute("tow", j) model.addAttribute("tou", usersService!!.userList().size) model.addAttribute("tob", bidService.tosizeb()) return "WEB-INF/view/bk_index" } }
0
Kotlin
0
0
166a224e41c4385634adb75c87f493524a679a71
1,050
lending
MIT License
petsearch-shared/domain/home/src/commonTest/kotlin/com/msa/petsearch/shared/domain/home/testfake/FakeData.kt
msa1422
534,594,528
false
{"Kotlin": 219918, "Swift": 46183, "Ruby": 1969}
package com.msa.petsearch.shared.domain.home.testfake import com.msa.petsearch.shared.core.entity.PetSearchParams import com.msa.petsearch.shared.core.entity.PetType import com.msa.petsearch.shared.core.entity.petinfo.PetInfo import com.msa.petsearch.shared.core.entity.petinfo.enum.PetAge import com.msa.petsearch.shared.core.entity.petinfo.enum.PetCoat import com.msa.petsearch.shared.core.entity.petinfo.enum.PetGender import com.msa.petsearch.shared.core.entity.petinfo.enum.PetSize import com.msa.petsearch.shared.core.entity.petinfo.enum.PetStatus import com.msa.petsearch.shared.core.entity.response.PaginationInfo import com.msa.petsearch.shared.core.entity.response.PetTypesResponse import com.msa.petsearch.shared.core.entity.response.SearchPetResponse internal object FakeData { val petTypesResponse = PetTypesResponse( types = listOf( PetType( name = "Dog", coats = listOf("DogCoat0", "DogCoat1", "DogCoat2", "DogCoat3"), colors = listOf( "DogColor0", "DogColor1", "DogColor2", "DogColor3", "DogColor4" ), genders = listOf("Male", "Female") ), PetType( name = "Cat", coats = listOf("CatCoat0", "CatCoat1", "CatCoat2", "CatCoat3"), colors = listOf( "CatColor0", "CatColor1", "CatColor2", "CatColor3", "CatColor4" ), genders = listOf("Male", "Female") ), PetType( name = "Horse", coats = listOf("HorseCoat0", "HorseCoat1", "HorseCoat2", "HorseCoat3"), colors = listOf( "HorseColor0", "HorseColor1", "HorseColor2", "HorseColor3", "HorseColor4" ), genders = listOf("Male", "Female") ) ) ) val petSearchResponse = SearchPetResponse( animals = listOf( PetInfo( id = 0, organizationId = "0", url = "someUrl", type = "Dog", species = "Werewolf", breeds = null, colors = null, age = PetAge.ADULT, gender = PetGender.MALE, size = PetSize.MEDIUM, coat = PetCoat.SHORT, name = "Dracula", description = "Wanders at night in search of prey, Beware!", shortDescription = "Adult Male, Werewolf", photos = listOf(), videos = listOf(), status = PetStatus.FOUND, attributes = null, environment = null, tags = listOf("Dangerous", "Fast"), contact = null, publishedAt = "Somewhere around midnight", distance = 1.0 ) ), pagination = PaginationInfo( countPerPage = 20, totalCount = 100, currentPage = 1, totalPages = 5 ) ) val searchParams = PetSearchParams( breed = listOf("Breed0", "Breed2"), size = listOf(PetSize.SMALL, PetSize.MEDIUM), gender = listOf(PetGender.MALE, PetGender.MALE), age = listOf(PetAge.ADULT), color = listOf("PetColor0", "PetColor1"), coat = listOf(PetCoat.CURLY, PetCoat.SHORT), status = listOf(PetStatus.ADOPTABLE), goodWithChildren = false, goodWithDogs = true, goodWithCats = false, houseTrained = false, declawed = false, specialNeeds = false ) }
0
Kotlin
0
19
b67e8e287e0d2b3fc0f2d3feaf3d0a21fd525c88
3,899
KMM-Arch-PetSearch
MIT License
app-data/src/main/java/me/dmba/teamworkboards/data/keyvalue/KeyValue.kt
dmba
141,046,741
false
{"Kotlin": 86040}
package me.dmba.teamworkboards.data.keyvalue import me.dmba.teamworkboards.common.utils.EMPTY /** * Created by dmba on 7/16/18. */ interface KeyValue { fun put(key: String, value: Any) fun contains(key: String): Boolean fun getString(key: String, defaultValue: String = EMPTY): String fun getBool(key: String, defaultValue: Boolean = false): Boolean fun getInt(key: String, defaultValue: Int = Int.MIN_VALUE): Int fun getLong(key: String, defaultValue: Long = Long.MIN_VALUE): Long fun getFloat(key: String, defaultValue: Float = Float.MIN_VALUE): Float }
3
Kotlin
0
0
a3d31225ebad80ae15158ca18ca0780b81c5726f
596
teamwork-boards
Apache License 2.0
api_viewing/src/main/kotlin/com/madness/collision/unit/api_viewing/util/PrefUtil.kt
cliuff
231,891,447
false
{"Kotlin": 1532215}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.madness.collision.unit.api_viewing.util import com.madness.collision.unit.api_viewing.MyUnit import com.madness.collision.unit.api_viewing.main.MainStatus internal object PrefUtil { const val AV_TAGS = "AvTags" const val API_APK_PRELOAD = "apiAPKPreload" const val API_APK_PRELOAD_DEFAULT = false const val API_CIRCULAR_ICON = "SDKCircularIcon" // render round icon only when user specifies const val API_CIRCULAR_ICON_DEFAULT = false const val API_PACKAGE_ROUND_ICON = "APIPackageRoundIcon" const val API_PACKAGE_ROUND_ICON_DEFAULT = false const val AV_CLIP_ROUND = "AVClip2Round" const val AV_CLIP_ROUND_DEFAULT = true const val AV_SWEET = "AVSweet" const val AV_SWEET_DEFAULT = true const val AV_VIEWING_TARGET = "AVViewingTarget" const val AV_VIEWING_TARGET_DEFAULT = true const val AV_INCLUDE_DISABLED = "AVIncludeDisabled" const val AV_INCLUDE_DISABLED_DEFAULT = false const val AV_SORT_ITEM = "SDKCheckSortSpinnerSelection" const val AV_SORT_ITEM_DEFAULT = MyUnit.SORT_POSITION_API_TIME const val AV_LIST_SRC_ITEM = "SDKCheckDisplaySpinnerSelection" const val AV_LIST_SRC_ITEM_DEFAULT = MainStatus.DISPLAY_APPS_USER }
0
Kotlin
9
97
bf61e5587039098c3161f8d1a8cd5c7398cb1b82
1,816
boundo
Apache License 2.0
generator/src/main/kotlin/com/infinum/collar/generator/models/AnalyticsModel.kt
infinum
242,731,077
false
null
package com.infinum.collar.generator.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable internal data class AnalyticsModel( @SerialName("screens") val screens: List<Screen>? = null, @SerialName("events") val events: List<Event>? = null, @SerialName("userProperties") val properties: List<Property>? = null )
2
Kotlin
2
21
d77ebc8d43caf766cf7bb6f62cedba698212ebe1
389
android-collar
Apache License 2.0
theme/theme-react/src/main/kotlin/tz/co/asoft/ThemeContext.kt
aSoft-Ltd
258,530,471
false
null
package tz.co.asoft import kotlinx.coroutines.flow.MutableStateFlow import react.RBuilder import react.createContext val currentTheme by lazy { MutableStateFlow(AquaGreenTheme) } val ThemeContext by lazy { createContext(currentTheme.value) } fun RBuilder.ThemeConsumer(handler: RBuilder.(Theme) -> Unit) = ThemeContext.Consumer(handler)
0
Kotlin
3
1
8233558139144a26c40ae30526bfd0b26bc7b3cb
341
kotlin
MIT License
examples/src/main/kotlin/histogram/StackedHistogram.kt
SciProgCentre
186,020,000
false
{"Kotlin": 394147}
package histogram import space.kscience.dataforge.meta.invoke import space.kscience.plotly.Plotly import space.kscience.plotly.makeFile import space.kscience.plotly.models.BarMode import space.kscience.plotly.models.Histogram import java.util.* fun main() { val rnd = Random() val k = List(500) { rnd.nextDouble() } val x1 = k.map { it }.toList() val x2 = k.map { it / 2 }.toList() val trace1 = Histogram { x.set(x1) opacity = 0.5 marker { color("green") } } val trace2 = Histogram { x.set(x2) opacity = 0.5 marker { color("orange") } } val plot = Plotly.plot { traces(trace1, trace2) layout { title = "Stacked Histogram" barmode = BarMode.stack } } plot.makeFile() }
10
Kotlin
21
142
a7d2611513c5f50c2f4a9c99b9ccb33cb486f07d
854
plotly.kt
Apache License 2.0
app/src/main/java/com/marcdonald/hibi/screens/settings/updatedialog/UpdateDialogViewModel.kt
MarcDonald
163,665,694
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marcdonald.hibi.screens.settings.updatedialog import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.marcdonald.hibi.data.network.NoConnectivityException import com.marcdonald.hibi.data.network.github.GithubRateLimitExceededException import com.marcdonald.hibi.internal.utils.UpdateUtils import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import timber.log.Timber import java.net.SocketTimeoutException class UpdateDialogViewModel(private val updateUtils: UpdateUtils) : ViewModel() { private val _displayDismiss = MutableLiveData<Boolean>() val displayDismiss: LiveData<Boolean> get() = _displayDismiss private val _displayOpenButton = MutableLiveData<Boolean>() val displayOpenButton: LiveData<Boolean> get() = _displayOpenButton private val _displayLoading = MutableLiveData<Boolean>() val displayLoading: LiveData<Boolean> get() = _displayLoading private val _displayNoConnection = MutableLiveData<Boolean>() val displayNoConnection: LiveData<Boolean> get() = _displayNoConnection private val _displayRateLimitError = MutableLiveData<Boolean>() val displayRateLimitError: LiveData<Boolean> get() = _displayRateLimitError private val _displayNoUpdateAvailable = MutableLiveData<Boolean>() val displayNoUpdateAvailable: LiveData<Boolean> get() = _displayNoUpdateAvailable private val _newVersionName = MutableLiveData<String>() val newVersionName: LiveData<String> get() = _newVersionName private val _displayError = MutableLiveData<Boolean>() val displayError: LiveData<Boolean> get() = _displayError init { _displayOpenButton.value = false _displayNoConnection.value = false _displayNoUpdateAvailable.value = false _displayDismiss.value = true } fun check() { viewModelScope.launch(Dispatchers.Default) { _displayLoading.postValue(true) try { val newestVersion = updateUtils.checkForUpdate() if(newestVersion != null) { _newVersionName.postValue(newestVersion.name) _displayOpenButton.postValue(true) _displayNoUpdateAvailable.postValue(false) } else { _displayNoUpdateAvailable.postValue(true) } } catch(e: GithubRateLimitExceededException) { _displayRateLimitError.postValue(true) } catch(e: NoConnectivityException) { _displayNoConnection.postValue(true) } catch(e: Exception) { _displayError.postValue(true) Timber.e("Log: updateDialogViewModel: check: ${e.message}") } finally { _displayLoading.postValue(false) } } } }
2
Kotlin
4
38
eabf13cc335381d66a128b3baad174a96fdfad64
3,197
Hibi
Apache License 2.0
envoy-control-tests/src/main/kotlin/pl/allegro/tech/servicemesh/envoycontrol/config/envoycontrol/EnvoyControlTestApp.kt
allegro
209,142,074
false
{"Kotlin": 1302186, "Java": 56670, "Lua": 39201, "Shell": 2720, "Dockerfile": 2692}
package pl.allegro.tech.servicemesh.envoycontrol.config.envoycontrol import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.node.ObjectNode import com.fasterxml.jackson.module.kotlin.KotlinModule import io.micrometer.core.instrument.MeterRegistry import okhttp3.Credentials import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.Response import org.springframework.boot.actuate.health.Status import org.springframework.boot.builder.SpringApplicationBuilder import org.springframework.http.HttpStatus import pl.allegro.tech.servicemesh.envoycontrol.EnvoyControl import pl.allegro.tech.servicemesh.envoycontrol.chaos.api.NetworkDelay import pl.allegro.tech.servicemesh.envoycontrol.config.envoy.HttpResponseCloser.addToCloseableResponses import pl.allegro.tech.servicemesh.envoycontrol.logger import pl.allegro.tech.servicemesh.envoycontrol.services.ServicesState import pl.allegro.tech.servicemesh.envoycontrol.snapshot.debug.Versions import pl.allegro.tech.servicemesh.envoycontrol.utils.Ports import java.time.Duration interface EnvoyControlTestApp { val appPort: Int val grpcPort: Int val appName: String fun run() fun stop() fun isHealthy(): Boolean fun getState(): ServicesState fun getSnapshot(nodeJson: String): SnapshotDebugResponse fun getGlobalSnapshot(xds: Boolean?): SnapshotDebugResponse fun getHealthStatus(): Health fun postChaosFaultRequest( username: String = "user", password: String = "<PASSWORD>", networkDelay: NetworkDelay ): Response fun getExperimentsListRequest( username: String = "user", password: String = "<PASSWORD>" ): Response fun deleteChaosFaultRequest( username: String = "user", password: String = "<PASSWORD>", faultId: String ): Response fun meterRegistry(): MeterRegistry } class EnvoyControlRunnerTestApp( val propertiesProvider: () -> Map<String, Any> = { mapOf() }, val consulPort: Int, val objectMapper: ObjectMapper = ObjectMapper() .registerModule(KotlinModule.Builder().build()) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false), override val grpcPort: Int = Ports.nextAvailable(), override val appPort: Int = Ports.nextAvailable() ) : EnvoyControlTestApp { override val appName = "envoy-control" private lateinit var app: SpringApplicationBuilder private val baseProperties = mapOf( "spring.profiles.active" to "test", "spring.jmx.enabled" to false, "envoy-control.source.consul.port" to consulPort, "envoy-control.envoy.snapshot.outgoing-permissions.enabled" to true, "envoy-control.sync.polling-interval" to Duration.ofSeconds(1).seconds, "envoy-control.server.port" to grpcPort, // Round robin gives much more predictable results in tests than LEAST_REQUEST "envoy-control.envoy.snapshot.load-balancing.policy" to "ROUND_ROBIN" ) override fun run() { app = SpringApplicationBuilder(EnvoyControl::class.java).properties(baseProperties + propertiesProvider()) app.run("--server.port=$appPort", "-e test") logger.info("starting EC on port $appPort, grpc: $grpcPort, consul: $consulPort") } override fun stop() { app.context().close() } override fun isHealthy(): Boolean = getApplicationStatusResponse().use { it.isSuccessful } override fun getHealthStatus(): Health { val response = getApplicationStatusResponse() return objectMapper.readValue(response.body?.use { it.string() }, Health::class.java) } override fun getState(): ServicesState { val response = httpClient .newCall( Request.Builder() .get() .url("http://localhost:$appPort/state") .build() ) .execute().addToCloseableResponses() return objectMapper.readValue(response.body?.use { it.string() }, ServicesState::class.java) } override fun getSnapshot(nodeJson: String): SnapshotDebugResponse { val response = httpClient.newCall( Request.Builder() .addHeader("Accept", "application/v3+json") .post(RequestBody.create("application/json".toMediaType(), nodeJson)) .url("http://localhost:$appPort/snapshot") .build() ).execute().addToCloseableResponses() if (response.code == HttpStatus.NOT_FOUND.value()) { return SnapshotDebugResponse(found = false) } else if (!response.isSuccessful) { throw SnapshotDebugResponseInvalidStatusException(response.code) } return response.body ?.use { objectMapper.readValue(it.byteStream(), SnapshotDebugResponse::class.java) } ?.copy(found = true) ?: throw SnapshotDebugResponseMissingException() } override fun getGlobalSnapshot(xds: Boolean?): SnapshotDebugResponse { var url = "http://localhost:$appPort/snapshot-global" if (xds != null) { url += "?xds=$xds" } val response = httpClient.newCall( Request.Builder() .get() .url(url) .build() ).execute().addToCloseableResponses() if (response.code == HttpStatus.NOT_FOUND.value()) { return SnapshotDebugResponse(found = false) } else if (!response.isSuccessful) { throw SnapshotDebugResponseInvalidStatusException(response.code) } return response.body ?.use { objectMapper.readValue(it.byteStream(), SnapshotDebugResponse::class.java) } ?.copy(found = true) ?: throw SnapshotDebugResponseMissingException() } class SnapshotDebugResponseMissingException : RuntimeException("Expected snapshot debug in response body but got none") class SnapshotDebugResponseInvalidStatusException(status: Int) : RuntimeException("Invalid snapshot debug response status: $status") private fun getApplicationStatusResponse(): Response = httpClient .newCall( Request.Builder() .get() .url("http://localhost:$appPort/actuator/health") .build() ) .execute().addToCloseableResponses() override fun postChaosFaultRequest( username: String, password: String, networkDelay: NetworkDelay ): Response { val credentials = Credentials.basic(username, password) val request = objectMapper.writeValueAsString(networkDelay) val requestBody = RequestBody.create("application/json".toMediaType(), request) return httpClient .newCall( Request.Builder() .header("Authorization", credentials) .post(requestBody) .url("http://localhost:$appPort/chaos/fault/read-network-delay") .build() ) .execute().addToCloseableResponses() } override fun getExperimentsListRequest( username: String, password: String ): Response { val credentials = Credentials.basic(username, password) return httpClient .newCall( Request.Builder() .header("Authorization", credentials) .get() .url("http://localhost:$appPort/chaos/fault/read-network-delay") .build() ) .execute().addToCloseableResponses() } override fun deleteChaosFaultRequest( username: String, password: String, faultId: String ): Response { val credentials = Credentials.basic(username, password) return httpClient .newCall( Request.Builder() .header("Authorization", credentials) .delete() .url("http://localhost:$appPort/chaos/fault/read-network-delay/$faultId") .build() ) .execute().addToCloseableResponses() } override fun meterRegistry() = app.context().getBean(MeterRegistry::class.java) ?: throw IllegalStateException("MeterRegistry bean not found in the context") companion object { val logger by logger() private val httpClient = OkHttpClient.Builder() .build() } } data class Health( val status: Status, val components: Map<String, HealthDetails> ) data class HealthDetails( val status: Status ) data class SnapshotDebugResponse( val found: Boolean, val versions: Versions? = null, val snapshot: ObjectNode? = null )
45
Kotlin
31
95
76427f4b8a28ff47b6fbc95266a2b21770b77e01
8,955
envoy-control
Apache License 2.0
app/src/main/java/com/example/lorenzodwishlist/ItemAdapter.kt
LorenzoDitarantoNJIT
610,594,409
false
null
package com.example.lorenzodwishlist import android.content.Intent import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView class ItemAdapter(private val itemList: List<Item>) : RecyclerView.Adapter<ItemAdapter.ViewHolder>() { class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { // TODO: Create member variables for any view that will be set val senderTextView: TextView val titleTextView: TextView val summaryTextView: TextView init { // TODO: Store each of the layout's views into // the public final member variables created above senderTextView = itemView.findViewById(R.id.sender) titleTextView = itemView.findViewById(R.id.title) summaryTextView = itemView.findViewById(R.id.summary) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val context = parent.context val inflater = LayoutInflater.from(context) val contactView = inflater.inflate(R.layout.insidewishlist, parent, false) return ViewHolder(contactView) } override fun getItemCount(): Int { return itemList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val currItem = itemList.get(position) // Set item views based on views and data model holder.senderTextView.text = currItem.Name holder.titleTextView.text = currItem.Price holder.summaryTextView.text = currItem.Link } }
1
Kotlin
0
0
c5c0114eaec91dac085c105c977ff8b659ab8a1c
1,828
LorenzoDBitFitP1
Apache License 2.0
api/src/commonMain/kotlin/mailer/EmailMessage.kt
picortex
546,065,516
false
{"Kotlin": 25081}
@file:JsExport @file:Suppress("NON_EXPORTABLE_TYPE") package mailer import kollections.List import kollections.iListOf import kotlinx.serialization.Serializable import kotlin.js.JsExport data class EmailMessage( val subject: String, val from: AddressInfo, val to: List<AddressInfo>, val body: String, val attachments: List<EmailAttachment<Any?>> = iListOf(), val status: List<EmailStatus> )
0
Kotlin
0
2
1e2a20bcaee2cdc1f79af96c482c766a42d9dbe8
417
mailer
MIT License
app/src/main/java/com/steleot/jetpackcompose/playground/compose/materialiconsextended/ExtendedOutlinedScreen.kt
Sagar19RaoRane
410,922,276
true
{"Kotlin": 887894}
package com.steleot.jetpackcompose.playground.compose.materialiconsextended import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.GridCells import androidx.compose.foundation.lazy.LazyVerticalGrid import androidx.compose.foundation.lazy.items import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.steleot.jetpackcompose.playground.compose.reusable.DefaultScaffold import com.steleot.jetpackcompose.playground.navigation.MaterialIconsExtendedNavRoutes private const val Url = "materialiconsextended/ExtendedOutlinedScreen.kt" @Composable fun ExtendedOutlinedScreen() { DefaultScaffold( title = MaterialIconsExtendedNavRoutes.ExtendedOutlined, link = Url, ) { ExtendedOutlinedGrid() } } private val list = listOf( Icons.Outlined._3dRotation, Icons.Outlined._4k, Icons.Outlined._5g, Icons.Outlined._6FtApart, Icons.Outlined._360, Icons.Outlined.AccessAlarm, Icons.Outlined.AccessAlarms, Icons.Outlined.Accessibility, Icons.Outlined.AccessibilityNew, Icons.Outlined.AccessibleForward, Icons.Outlined.Accessible, Icons.Outlined.AccessTime, Icons.Outlined.AccountBalance, Icons.Outlined.AccountBalanceWallet, Icons.Outlined.AccountTree, Icons.Outlined.AcUnit, Icons.Outlined.Adb, Icons.Outlined.AddAlarm, Icons.Outlined.AddAlert, Icons.Outlined.AddAPhoto, Icons.Outlined.AddBox, Icons.Outlined.AddBusiness, Icons.Outlined.Addchart, Icons.Outlined.AddCircleOutline, Icons.Outlined.AddComment, Icons.Outlined.AddIcCall, Icons.Outlined.AddLocation, Icons.Outlined.AddLocationAlt, Icons.Outlined.AddPhotoAlternate, Icons.Outlined.AddRoad, Icons.Outlined.AddShoppingCart, Icons.Outlined.AddTask, Icons.Outlined.AddToHomeScreen, Icons.Outlined.AddToPhotos, Icons.Outlined.AddToQueue, Icons.Outlined.Adjust, Icons.Outlined.AdminPanelSettings, Icons.Outlined.AdUnits, Icons.Outlined.Agriculture, Icons.Outlined.AirlineSeatFlatAngled, Icons.Outlined.AirlineSeatFlat, Icons.Outlined.AirlineSeatIndividualSuite, Icons.Outlined.AirlineSeatLegroomExtra, Icons.Outlined.AirlineSeatLegroomNormal, Icons.Outlined.AirlineSeatLegroomReduced, Icons.Outlined.AirlineSeatReclineExtra, Icons.Outlined.AirlineSeatReclineNormal, Icons.Outlined.AirplanemodeActive, Icons.Outlined.AirplanemodeInactive, Icons.Outlined.Airplay, Icons.Outlined.AirportShuttle, Icons.Outlined.AlarmAdd, Icons.Outlined.Alarm, Icons.Outlined.AlarmOff, Icons.Outlined.AlarmOn, Icons.Outlined.Album, Icons.Outlined.AlignHorizontalCenter, Icons.Outlined.AlignHorizontalLeft, Icons.Outlined.AlignHorizontalRight, Icons.Outlined.AlignVerticalBottom, Icons.Outlined.AlignVerticalCenter, Icons.Outlined.AlignVerticalTop, Icons.Outlined.AllInbox, Icons.Outlined.AllInclusive, Icons.Outlined.AltRoute, Icons.Outlined.AmpStories, Icons.Outlined.Analytics, Icons.Outlined.Anchor, Icons.Outlined.Android, Icons.Outlined.Announcement, Icons.Outlined.Apartment, Icons.Outlined.Api, Icons.Outlined.AppBlocking, Icons.Outlined.AppSettingsAlt, Icons.Outlined.Apps, Icons.Outlined.Architecture, Icons.Outlined.Archive, Icons.Outlined.ArrowBackIos, Icons.Outlined.ArrowCircleDown, Icons.Outlined.ArrowCircleUp, Icons.Outlined.ArrowDownward, Icons.Outlined.ArrowDropDownCircle, Icons.Outlined.ArrowDropUp, Icons.Outlined.ArrowForwardIos, Icons.Outlined.ArrowLeft, Icons.Outlined.ArrowRightAlt, Icons.Outlined.ArrowRight, Icons.Outlined.ArrowUpward, Icons.Outlined.Article, Icons.Outlined.ArtTrack, Icons.Outlined.AspectRatio, Icons.Outlined.Assessment, Icons.Outlined.AssignmentInd, Icons.Outlined.Assignment, Icons.Outlined.AssignmentLate, Icons.Outlined.AssignmentReturned, Icons.Outlined.AssignmentReturn, Icons.Outlined.AssignmentTurnedIn, Icons.Outlined.Assistant, Icons.Outlined.AssistantPhoto, Icons.Outlined.Atm, Icons.Outlined.AttachEmail, Icons.Outlined.AttachFile, Icons.Outlined.Attachment, Icons.Outlined.AttachMoney, Icons.Outlined.Audiotrack, Icons.Outlined.AutoDelete, Icons.Outlined.Autorenew, Icons.Outlined.AvTimer, Icons.Outlined.BabyChangingStation, Icons.Outlined.Backpack, Icons.Outlined.Backspace, Icons.Outlined.Backup, Icons.Outlined.BackupTable, Icons.Outlined.Badge, Icons.Outlined.BakeryDining, Icons.Outlined.Balcony, Icons.Outlined.Ballot, Icons.Outlined.BarChart, Icons.Outlined.BatchPrediction, Icons.Outlined.Bathroom, Icons.Outlined.Bathtub, Icons.Outlined.BatteryAlert, Icons.Outlined.BatteryChargingFull, Icons.Outlined.BatteryFull, Icons.Outlined.BatterySaver, Icons.Outlined.BatteryStd, Icons.Outlined.BatteryUnknown, Icons.Outlined.BeachAccess, Icons.Outlined.Bed, Icons.Outlined.BedroomBaby, Icons.Outlined.BedroomChild, Icons.Outlined.BedroomParent, Icons.Outlined.Bedtime, Icons.Outlined.Beenhere, Icons.Outlined.Bento, Icons.Outlined.BikeScooter, Icons.Outlined.Biotech, Icons.Outlined.Blender, Icons.Outlined.Block, Icons.Outlined.Bloodtype, Icons.Outlined.BluetoothAudio, Icons.Outlined.BluetoothConnected, Icons.Outlined.BluetoothDisabled, Icons.Outlined.BluetoothDrive, Icons.Outlined.Bluetooth, Icons.Outlined.BluetoothSearching, Icons.Outlined.BlurCircular, Icons.Outlined.BlurLinear, Icons.Outlined.BlurOff, Icons.Outlined.BlurOn, Icons.Outlined.Bolt, Icons.Outlined.Book, Icons.Outlined.BookmarkAdded, Icons.Outlined.BookmarkAdd, Icons.Outlined.BookmarkBorder, Icons.Outlined.Bookmark, Icons.Outlined.BookmarkRemove, Icons.Outlined.Bookmarks, Icons.Outlined.BookOnline, Icons.Outlined.BorderAll, Icons.Outlined.BorderBottom, Icons.Outlined.BorderClear, Icons.Outlined.BorderColor, Icons.Outlined.BorderHorizontal, Icons.Outlined.BorderInner, Icons.Outlined.BorderLeft, Icons.Outlined.BorderOuter, Icons.Outlined.BorderRight, Icons.Outlined.BorderStyle, Icons.Outlined.BorderTop, Icons.Outlined.BorderVertical, Icons.Outlined.BrandingWatermark, Icons.Outlined.BreakfastDining, Icons.Outlined.Brightness1, Icons.Outlined.Brightness2, Icons.Outlined.Brightness3, Icons.Outlined.Brightness4, Icons.Outlined.Brightness5, Icons.Outlined.Brightness6, Icons.Outlined.Brightness7, Icons.Outlined.BrightnessAuto, Icons.Outlined.BrightnessHigh, Icons.Outlined.BrightnessLow, Icons.Outlined.BrightnessMedium, Icons.Outlined.BrokenImage, Icons.Outlined.BrowserNotSupported, Icons.Outlined.BrunchDining, Icons.Outlined.Brush, Icons.Outlined.BubbleChart, Icons.Outlined.BugReport, Icons.Outlined.BuildCircle, Icons.Outlined.Bungalow, Icons.Outlined.BurstMode, Icons.Outlined.BusAlert, Icons.Outlined.BusinessCenter, Icons.Outlined.Business, ) @Preview @OptIn(ExperimentalFoundationApi::class) @Composable private fun ExtendedOutlinedGrid() { LazyVerticalGrid( GridCells.Adaptive(60.dp) ) { items(list) { Icon(imageVector = it, contentDescription = "", modifier = Modifier.padding(8.dp)) } } }
0
null
0
1
91d0a3571031a97a437e13ab103a6cd7092f1598
7,785
Jetpack-Compose-Playground
Apache License 2.0
common-query-builder/src/main/java/ro/andob/outofroom/querybuilder/QueryBuilderDefaults.kt
andob
363,221,615
false
{"Kotlin": 90848, "Java": 2407, "Shell": 444}
package ro.andob.outofroom.querybuilder object QueryBuilderDefaults { var isPaginationEnabled : Boolean = false }
0
Kotlin
0
4
d18a9797f2e0cce47e27a5a106b3b0a35674ee5d
119
OutOfROOM
Apache License 2.0
kmm/shared/src/commonMain/kotlin/ui/catalog/WatchablePager.kt
barabasizsolt
524,965,150
false
null
package ui.catalog import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Favorite import androidx.compose.material.icons.filled.PlayCircle import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import kotlinx.coroutines.delay import movie.model.Movie import ui.theme.AppTheme import ui.util.ImageType import ui.util.getImageKey import ui.util.withShadow @OptIn(ExperimentalFoundationApi::class) @Composable internal fun WatchablePager( modifier: Modifier = Modifier, pagerContent: List<Movie>, genres: Map<Long, String>, onClick: (Int) -> Unit, onPlayButtonClicked: () -> Unit, onAddToFavouriteButtonClicked: () -> Unit ) { val pagerState = rememberPagerState() LaunchedEffect(Unit) { while (true) { delay(timeMillis = 5000) if (pagerContent.isNotEmpty()) { pagerState.animateScrollToPage(page = (pagerState.currentPage + 1) % (pagerContent.size)) } } } Column(horizontalAlignment = Alignment.CenterHorizontally) { HorizontalPager( modifier = modifier.fillMaxWidth(), pageCount = pagerContent.size, state = pagerState ) { page -> PagerItem( item = pagerContent[page], onClick = { onClick(pagerContent[page].id.toInt()) }, onPlayButtonClicked = onPlayButtonClicked, onAddToFavouriteButtonClicked = onAddToFavouriteButtonClicked, genres = genres ) } HorizontalPagerIndicator( pagerState = pagerState, indicatorCount = pagerContent.size, itemCount = pagerContent.size, modifier = Modifier.padding(horizontal = AppTheme.dimens.screenPadding) ) } } @Composable internal fun PagerItem( modifier: Modifier = Modifier, item: Movie, genres: Map<Long, String>, onClick: () -> Unit, onPlayButtonClicked: () -> Unit, onAddToFavouriteButtonClicked: () -> Unit ) { Box(modifier = modifier .fillMaxWidth() .clickable { onClick() }) { MovaImage( imageUrl = item.posterPath?.getImageKey(imageType = ImageType.ORIGINAL).orEmpty(), contentScale = ContentScale.Crop, modifier = Modifier .fillMaxWidth() .aspectRatio(ratio = 0.7f) ) GradientOverlay( maxHeightFraction = 0.5f, colors = listOf( Color.Transparent, Color.Transparent, AppTheme.colors.primary.copy(alpha = 0.8f), AppTheme.colors.primary ) ) PagerItemInfo( item = item, genres = genres, modifier = Modifier.align(alignment = Alignment.BottomStart), onPlayButtonClicked = onPlayButtonClicked, onAddToFavouriteButtonClicked = onAddToFavouriteButtonClicked ) } } @Composable internal fun PagerItemInfo( modifier: Modifier = Modifier, item: Movie, genres: Map<Long, String>, onPlayButtonClicked: () -> Unit, onAddToFavouriteButtonClicked: () -> Unit ) = Column( modifier = modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(space = AppTheme.dimens.contentPadding) ) { Text( text = item.title, style = AppTheme.typography.h6.withShadow(), fontWeight = FontWeight.Bold, color = Color.White, modifier = Modifier.padding(horizontal = AppTheme.dimens.screenPadding) ) LazyRow( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, contentPadding = PaddingValues(horizontal = AppTheme.dimens.screenPadding) ) { itemsIndexed(items = item.genreIds.map { genre -> genres[genre.toLong()].orEmpty() }) { index, genre -> PagerGenreItem( text = genre, shouldShowSeparator = index != item.genreIds.lastIndex ) } } PagerItemButtons( onPlayButtonClicked = onPlayButtonClicked, onAddToFavouriteButtonClicked = onAddToFavouriteButtonClicked, modifier = Modifier.padding( start = AppTheme.dimens.screenPadding, bottom = AppTheme.dimens.screenPadding ) ) } @Composable internal fun PagerGenreItem( modifier: Modifier = Modifier, text: String, shouldShowSeparator: Boolean ) = Text( text = if (shouldShowSeparator) "$text • " else text, style = AppTheme.typography.body2.withShadow(), fontWeight = FontWeight.Bold, overflow = TextOverflow.Ellipsis, color = Color.White, modifier = modifier ) @Composable internal fun PagerItemButtons( modifier: Modifier = Modifier, onPlayButtonClicked: () -> Unit, onAddToFavouriteButtonClicked: () -> Unit ) = Row( modifier = modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(space = AppTheme.dimens.contentPadding * 2) ) { MovaFilledButton( text = AppTheme.strings.trailer, icon = Icons.Filled.PlayCircle, onClick = onPlayButtonClicked ) MovaOutlinedButton( text = AppTheme.strings.favourites, icon = Icons.Filled.Favorite, contentColor = AppTheme.colors.secondary, onClick = onAddToFavouriteButtonClicked ) }
0
Kotlin
0
0
acf4e021200c670dbc7bc2a38240d019f2a4a3a2
6,533
Mova
GNU General Public License v3.0 or later
core/descriptor.loader.java/src/org/jetbrains/kotlin/load/kotlin/DeserializationComponentsForJava.kt
dotlin
55,273,718
true
{"Java": 17625136, "Kotlin": 13963251, "JavaScript": 177557, "Protocol Buffer": 42724, "HTML": 32771, "Lex": 17840, "ANTLR": 9689, "CSS": 9358, "Groovy": 7182, "IDL": 5010, "Shell": 4704, "Batchfile": 3703}
/* * Copyright 2010-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.load.kotlin import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.incremental.components.LookupTracker import org.jetbrains.kotlin.load.java.lazy.LazyJavaPackageFragmentProvider import org.jetbrains.kotlin.serialization.deserialization.* import org.jetbrains.kotlin.storage.StorageManager // This class is needed only for easier injection: exact types of needed components are specified in the constructor here. // Otherwise injector generator is not smart enough to deduce, for example, which package fragment provider DeserializationComponents needs class DeserializationComponentsForJava( storageManager: StorageManager, moduleDescriptor: ModuleDescriptor, classDataFinder: JavaClassDataFinder, annotationAndConstantLoader: BinaryClassAnnotationAndConstantLoaderImpl, packageFragmentProvider: LazyJavaPackageFragmentProvider, notFoundClasses: NotFoundClasses, errorReporter: ErrorReporter, lookupTracker: LookupTracker ) { val components: DeserializationComponents init { val localClassResolver = LocalClassResolverImpl() components = DeserializationComponents( storageManager, moduleDescriptor, classDataFinder, annotationAndConstantLoader, packageFragmentProvider, localClassResolver, errorReporter, lookupTracker, JavaFlexibleTypeCapabilitiesDeserializer, ClassDescriptorFactory.EMPTY, notFoundClasses, JavaTypeCapabilitiesLoader, additionalSupertypes = BuiltInClassesAreSerializableOnJvm(moduleDescriptor) ) localClassResolver.setDeserializationComponents(components) } }
0
Java
0
0
f3f1aa8a15d647ed846d66537cff7bee156ee4aa
2,316
kotlin
Apache License 2.0
src/main/kotlin/com/grapefruit/aid/domain/purchase/service/impl/DeletePurchaseServiceImpl.kt
Team-GrapeFruit
621,363,100
false
null
package com.grapefruit.aid.domain.purchase.service.impl import com.grapefruit.aid.domain.purchase.repository.PurchaseRepository import com.grapefruit.aid.domain.purchase.service.DeletePurchaseService import com.grapefruit.aid.domain.seat.exception.SeatNotFoundException import com.grapefruit.aid.domain.seat.repository.SeatRepository import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service @Transactional(rollbackFor = [Exception::class]) class DeletePurchaseServiceImpl( private val seatRepository: SeatRepository, private val purchaseRepository: PurchaseRepository ): DeletePurchaseService { override fun execute(seatId: Long) { val seat = seatRepository.findByIdOrNull(seatId) ?: throw SeatNotFoundException() val purchases = purchaseRepository.findAllBySeat(seat) purchaseRepository.deleteAll(purchases) } }
0
Kotlin
0
0
5c4ea42e5656709e9b596089c852de2485dafde0
975
Aid-Backend-User
MIT License
app/src/main/java/io/davedavis/todora/ui/home/HomeViewModelFactory.kt
davedavis
355,332,948
false
{"Kotlin": 79198}
package io.davedavis.todora.ui.home import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider // This factory is used to pass parameters/objects in to my view models. // Shared preferences in view models need to be accessed this way. @Suppress("UNCHECKED_CAST") @SuppressWarnings("unchecked") class HomeViewModelFactory : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(HomeViewModel::class.java)) { return HomeViewModel() as T } throw IllegalArgumentException("Unknown ViewModel class") } }
8
Kotlin
0
1
3e3ccc8898e7d300a742d7b9af4c70bbc744df1f
636
ToDoRa
Apache License 2.0
iptvservicecommunicator/src/main/java/com/bytecoders/iptvservicecommunicator/net/Network.kt
jtorrestobena
234,900,466
false
{"Java": 337396, "Kotlin": 200244}
package com.bytecoders.iptvservicecommunicator.net import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import java.io.InputStream object Network { private fun getResponse(url: String): Response { val client = OkHttpClient() val request: Request = Request.Builder() .url(url) .build() return client.newCall(request).execute() } fun inputStreamforURL(url: String): InputStream { return getResponse(url).body!!.byteStream() } fun inputStreamAndLength(url: String): Pair<InputStream, Long> { val response = getResponse(url) return Pair(response.body!!.byteStream(), response.body!!.contentLength()) } }
0
Java
1
1
6acec6101501a10e86c30497688b4eb0fc7dcea7
729
androidiptvservice
Apache License 2.0
examples/spring-boot/src/main/kotlin/xyz/chrisime/springboot/service/business/EfghService.kt
chrisime
318,823,804
false
{"Kotlin": 42864}
package xyz.chrisime.springboot.service.business import org.springframework.stereotype.Service import xyz.chrisime.springboot.domain.EfghDomain import xyz.chrisime.springboot.service.persistence.EfghRepository import java.util.* import java.util.stream.Stream @Service class EfghService(private val efghRepository: EfghRepository) { fun getAll(): Stream<EfghDomain> { return efghRepository.find() } fun getByIdentifier(identifier: UUID): EfghDomain { return efghRepository.findByIdentifier(identifier) } fun update(identifier: String, email: String): Int { return efghRepository.updateByIdentifier(UUID.fromString(identifier), email) } fun delete(identifier: UUID): Int { return efghRepository.deleteByIdentifier(identifier) } fun existsByPk(pk: UUID): Boolean { return efghRepository.existsById(pk) } }
0
Kotlin
0
1
8928ef38a891d697973790d354793fd07db16dc2
892
CRooD
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/memoir/generated/equip3000021.kt
pointillion
428,683,199
true
{"Kotlin": 1212476, "HTML": 26704, "CSS": 26127, "JavaScript": 1640}
package xyz.qwewqa.relive.simulator.core.presets.memoir.generated import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.autoskill.EffectTag import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.memoir.CutinBlueprint import xyz.qwewqa.relive.simulator.core.stage.memoir.PartialMemoirBlueprint val equip3000021 = PartialMemoirBlueprint( id = 3000021, name = "この空間の絶対的アイドル", rarity = 3, baseStats = StatData( hp = 147, actPower = 0, normalDefense = 0, specialDefense = 12, ), growthStats = StatData( hp = 19173, actPower = 0, normalDefense = 0, specialDefense = 1643, ), additionalTags = listOf(EffectTag.Ichie, EffectTag.Yuyuko) )
0
Kotlin
0
0
53479fe3d1f4a067682509376afd87bdd205d19d
814
relive-simulator
MIT License
core/src/main/java/com/ymy/core/utils/DensityUtil.kt
hybridappnest
409,475,593
false
{"Java": 3496922, "Kotlin": 641137, "JavaScript": 5699}
package com.ymy.core.utils import android.content.Context import com.ymy.core.Ktx /** * Created on 2020/7/9 20:18. * @author:hanxueqiang * @version: 1.0.0 * @desc: */ object DensityUtil { fun dip2px(context: Context, dpValue: Float): Int { val scale = context.resources.displayMetrics.density return (dpValue * scale + 0.5f).toInt() } /** * 获得x方向的dp转像素 * @param dpvalue * @return */ fun dip2pxX(dpvalue: Float): Int { return (dpvalue * Ktx.app.getResources() .getDisplayMetrics().xdpi / 160 + 0.5f).toInt() } /** * 根据手机的分辨率从 px(像素) 的单位 转成为 dp */ fun px2dip(pxValue: Float): Int { val scale = Ktx.app.resources.displayMetrics.density return (pxValue / scale + 0.5f).toInt() } fun px2sp(context: Context, pxValue: Float): Int { val fontScale = context.resources.displayMetrics.scaledDensity return (pxValue / fontScale + 0.5f).toInt() } /** * 获得y方向的dp转像素 * @param dpvalue * @return */ fun dip2pxY(dpvalue: Float): Int { return (dpvalue * Ktx.app.getResources() .getDisplayMetrics().ydpi / 160 + 0.5f).toInt() } }
0
Java
6
11
b1fd25a909463f631e4c98cdfdd27e77d82164f7
1,277
AppNestAndroid
Apache License 2.0
feature-settings-impl/src/main/java/io/novafoundation/nova/feature_settings_impl/presentation/settings/di/SettingsComponent.kt
novasamatech
415,834,480
false
{"Kotlin": 8656332, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.feature_settings_impl.presentation.settings.di import androidx.fragment.app.Fragment import dagger.BindsInstance import dagger.Subcomponent import io.novafoundation.nova.common.di.scope.ScreenScope @Subcomponent( modules = [ SettingsModule::class ] ) @ScreenScope interface SettingsComponent { @Subcomponent.Factory interface Factory { fun create( @BindsInstance fragment: Fragment, ): SettingsComponent } fun inject(settingsFragment: io.novafoundation.nova.feature_settings_impl.presentation.settings.SettingsFragment) }
18
Kotlin
6
15
547f9966ee3aec864b864d6689dc83b6193f5c15
618
nova-wallet-android
Apache License 2.0
app/src/main/java/ethiopia/covid/android/ui/fragment/QuestionPageFragment.kt
brookmg
249,926,845
false
null
package ethiopia.covid.android.ui.fragment import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import ethiopia.covid.android.R import ethiopia.covid.android.data.QuestionItem import ethiopia.covid.android.data.QuestionnaireItem.QuestionType import ethiopia.covid.android.databinding.QuestionPageFragmentBinding import ethiopia.covid.android.ui.adapter.CheckBoxQuestionRecyclerAdapter import ethiopia.covid.android.ui.adapter.OnQuestionItemSelected import ethiopia.covid.android.ui.adapter.SingleChoiceQuestionRecyclerAdapter /** * Created by BrookMG on 3/23/2020 in ethiopia.covid.android.ui.fragment * inside the project CoVidEt . */ class QuestionPageFragment( private val questionTitle: String?, private val type: QuestionType?, private val questionItems: List<QuestionItem>, private val onQuestionItemSelected: OnQuestionItemSelected? ) : BaseFragment() { private lateinit var questionPageFragmentBinding: QuestionPageFragmentBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { questionPageFragmentBinding = QuestionPageFragmentBinding.inflate(layoutInflater) questionPageFragmentBinding.textView1.text = questionTitle when (type) { QuestionType.SINGLE_CHOICE_QUESTION -> { questionPageFragmentBinding.recyclerView.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) questionPageFragmentBinding.recyclerView.adapter = CheckBoxQuestionRecyclerAdapter(questionItems, true, onQuestionItemSelected) } QuestionType.SINGLE_MULTIPLE_CHOICE_QUESTION -> { questionPageFragmentBinding.recyclerView.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false) questionPageFragmentBinding.recyclerView.adapter = CheckBoxQuestionRecyclerAdapter(questionItems, onQuestionItemSelected) } QuestionType.SINGLE_BLOCK_QUESTION -> { questionPageFragmentBinding.recyclerView.layoutManager = GridLayoutManager(activity, 2) questionPageFragmentBinding.recyclerView.adapter = SingleChoiceQuestionRecyclerAdapter(questionItems, onQuestionItemSelected) } } return questionPageFragmentBinding.root } companion object { fun newInstance( questionTitle: String?, type: QuestionType?, items: List<QuestionItem>, onQuestionItemSelected: OnQuestionItemSelected? ): QuestionPageFragment { val args = Bundle() val fragment = QuestionPageFragment(questionTitle, type, items, onQuestionItemSelected) fragment.arguments = args return fragment } } }
14
Kotlin
5
18
2feaf0f03d316c4fc08c2ebea1d77ee773eaa5b6
3,080
CovidAndroid
Apache License 2.0
PdfiumAndroid/arrow/src/main/java/io/legere/pdfiumandroid/arrow/PdfTextPageKtF.kt
johngray1965
650,684,167
false
{"C": 389954, "Kotlin": 160440, "C++": 85192, "CMake": 3269, "Python": 1354}
@file:Suppress("unused") package io.legere.pdfiumandroid.arrow import android.graphics.RectF import arrow.core.Either import io.legere.pdfiumandroid.PdfTextPage import kotlinx.coroutines.CoroutineDispatcher import java.io.Closeable /** * PdfTextPageKtF represents a single text page of a PDF file. * @property page the [PdfTextPage] to wrap * @property dispatcher the [CoroutineDispatcher] to use for suspending calls */ @Suppress("TooManyFunctions") class PdfTextPageKtF(val page: PdfTextPage, private val dispatcher: CoroutineDispatcher) : Closeable { /** * suspend version of [PdfTextPage.textPageCountChars] */ suspend fun textPageCountChars(): Either<PdfiumKtFErrors, Int> { return wrapEither(dispatcher) { page.textPageCountChars() } } /** * suspend version of [PdfTextPage.textPageGetText] */ suspend fun textPageGetText( startIndex: Int, length: Int ): Either<PdfiumKtFErrors, String?> { return wrapEither(dispatcher) { page.textPageGetText(startIndex, length) } } /** * suspend version of [PdfTextPage.textPageGetUnicode] */ suspend fun textPageGetUnicode(index: Int): Either<PdfiumKtFErrors, Char> { return wrapEither(dispatcher) { page.textPageGetUnicode(index) } } /** * suspend version of [PdfTextPage.textPageGetCharBox] */ suspend fun textPageGetCharBox(index: Int): Either<PdfiumKtFErrors, RectF?> { return wrapEither(dispatcher) { page.textPageGetCharBox(index) } } /** * suspend version of [PdfTextPage.textPageGetCharIndexAtPos] */ suspend fun textPageGetCharIndexAtPos( x: Double, y: Double, xTolerance: Double, yTolerance: Double ): Either<PdfiumKtFErrors, Int> { return wrapEither(dispatcher) { page.textPageGetCharIndexAtPos(x, y, xTolerance, yTolerance) } } /** * suspend version of [PdfTextPage.textPageCountRects] */ suspend fun textPageCountRects( startIndex: Int, count: Int ): Either<PdfiumKtFErrors, Int> { return wrapEither(dispatcher) { page.textPageCountRects(startIndex, count) } } /** * suspend version of [PdfTextPage.textPageGetRect] */ suspend fun textPageGetRect(rectIndex: Int): Either<PdfiumKtFErrors, RectF?> { return wrapEither(dispatcher) { page.textPageGetRect(rectIndex) } } /** * suspend version of [PdfTextPage.textPageGetBoundedText] */ suspend fun textPageGetBoundedText( rect: RectF, length: Int ): Either<PdfiumKtFErrors, String?> { return wrapEither(dispatcher) { page.textPageGetBoundedText(rect, length) } } /** * suspend version of [PdfTextPage.getFontSize] */ suspend fun getFontSize(charIndex: Int): Either<PdfiumKtFErrors, Double> { return wrapEither(dispatcher) { page.getFontSize(charIndex) } } /** * Close the page and free all resources. */ override fun close() { page.close() } fun safeClose(): Either<PdfiumKtFErrors, Boolean> { return Either.catch { page.close() true }.mapLeft { exceptionToPdfiumKtFError(it) } } }
5
C
4
10
66a443458c5fffe1f6101b200df787aceac6a319
3,424
PdfiumAndroidKt
Apache License 2.0
updater-mapper-standard/src/main/java/org/runestar/client/updater/mapper/std/classes/SpriteMask.kt
Tachyon97
228,674,958
true
{"Kotlin": 1392478, "Java": 27806}
package org.runestar.client.updater.mapper.std.classes import org.objectweb.asm.Type.BOOLEAN_TYPE import org.objectweb.asm.Type.INT_TYPE import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.DependsOn import org.runestar.client.updater.mapper.MethodParameters import org.runestar.client.updater.mapper.and import org.runestar.client.updater.mapper.predicateOf import org.runestar.client.updater.mapper.type import org.runestar.client.updater.mapper.std.SpriteMaskConstructorField import org.runestar.client.updater.mapper.Class2 import org.runestar.client.updater.mapper.Method2 @DependsOn(DualNode::class) class SpriteMask : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { it.superType == type<DualNode>() } .and { it.instanceFields.count { it.type == IntArray::class.type } == 2 } .and { it.instanceFields.count { it.type == INT_TYPE } == 2 } .and { it.instanceMethods.size == 1 } class width : SpriteMaskConstructorField(INT_TYPE, 0) class height : SpriteMaskConstructorField(INT_TYPE, 1) class xWidths : SpriteMaskConstructorField(IntArray::class.type, 0) class xStarts : SpriteMaskConstructorField(IntArray::class.type, 1) @MethodParameters("x", "y") class contains : IdentityMapper.InstanceMethod() { override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE } } }
0
Kotlin
0
0
d02e7a382a34af117279be02f9f54a6a70fc012b
1,440
client
MIT License
app/src/main/java/com/bell/youtubeplayer/models/YouTubeSnippet.kt
zaidbintariq89
296,460,988
false
null
package com.bell.youtubeplayer.models import android.os.Parcelable import com.google.gson.annotations.SerializedName import kotlinx.android.parcel.Parcelize @Parcelize data class YouTubeSnippet( val channelId: String? = null, val title: String, val description: String? = null, val channelTitle: String? = null, val thumbnails: ThumbnailModel? = null ) : Parcelable @Parcelize data class ThumbnailModel( @SerializedName("default") val defaultImage: ImagesModel? = null, @SerializedName("medium") val mediumImage: ImagesModel? = null, @SerializedName("high") val highImage: ImagesModel? = null ) : Parcelable
0
Kotlin
0
0
f88002002a0cf6f546652ebdbea4fa91be14061f
654
MusicAlbum
Apache License 2.0
SampleServices/app/src/main/java/com/gorrotowi/sampleservices/LocationLcService.kt
gorrotowi
276,680,120
false
null
package com.gorrotowi.sampleservices import android.Manifest import android.content.Context import android.content.pm.PackageManager import android.location.Location import android.location.LocationListener import android.location.LocationManager import android.os.Bundle import android.util.Log import android.widget.Toast import androidx.core.app.ActivityCompat import androidx.lifecycle.LifecycleService import androidx.lifecycle.MutableLiveData class LocationLcService : LifecycleService(), LocationListener { private lateinit var locationManager: LocationManager private var destroyFrom = "SO" companion object { val liveData = MutableLiveData<String>() } override fun onCreate() { super.onCreate() locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager requestLocations() startForeground(320, createNotification()) } private fun requestLocations() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { Log.e("", "requestLocations: Not Granted") Toast.makeText(this, "Aprueba los permisos de localización", Toast.LENGTH_SHORT).show() destroyFrom = "NOT GRANTED PERMISSIONS STOPSELF" stopSelf() } else { try { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 100F, this) } catch (e: Exception) { destroyFrom = "TRYCATCH" e.printStackTrace() stopSelf() } } } override fun onLocationChanged(location: Location?) { Log.i("LOCATION", "${location?.toString()}") if (liveData.hasActiveObservers()) { liveData.value = location.toString() } } override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) { Log.d( "STATUSCHANGED", """ Provider $provider Status $status BundleExtras ${extras?.keySet()?.map { it }} """.trimIndent() ) } override fun onProviderEnabled(provider: String?) { Log.w("onProviderEnabled", "$provider") } override fun onProviderDisabled(provider: String?) { Log.wtf("onProviderDisabled", "$provider") } }
0
Kotlin
0
1
10d731be1a2809d4fc253539eac1ae2577e582e7
2,633
CursoKMMXCertificacion
MIT License
src/main/kotlin/net/lomeli/minewell/core/util/RangeUtil.kt
Lomeli12
151,324,372
false
null
package net.lomeli.minewell.core.util import net.lomeli.minewell.block.tile.TileEndWell import net.lomeli.minewell.lib.MAX_DISTANCE import net.minecraft.entity.Entity import net.minecraft.entity.player.EntityPlayer import net.minecraft.util.math.AxisAlignedBB import net.minecraft.util.math.BlockPos import net.minecraft.util.math.MathHelper import net.minecraft.world.World object RangeUtil { fun isEntityNearWell(entity: Entity, activeWell: Boolean): BlockPos? { val distance = MAX_DISTANCE.toInt() for (x in -distance..distance) for (y in -distance..distance) for (z in -distance..distance) { val newX = entity.posX + x val newY = entity.posY + y val newZ = entity.posZ + z val pos = BlockPos(newX, newY, newZ) val tile = entity.world.getTileEntity(pos) if (tile is TileEndWell) { var playerDistance = -1.0 if (activeWell) { if (tile.isWellActivated()) playerDistance = entity.getDistance(newX, newY - 2, newZ) } else playerDistance = entity.getDistance(newX, newY, newZ) if (playerDistance != -1.0 && playerDistance <= MAX_DISTANCE) return pos } } return null } fun get2DDistance(x: Double, y: Double, targetX: Double, targetY: Double): Double { val d0 = targetX - x val d1 = targetY - y return MathHelper.sqrt(d0 * d0 + d1 * d1).toDouble() } fun getPlayersInRange(maxRange: Double, pos: BlockPos, world: World): ArrayList<EntityPlayer> { val list = ArrayList<EntityPlayer>() val range = AxisAlignedBB(pos.x.toDouble(), pos.y - 2.0, pos.z.toDouble(), pos.x + 1.0, pos.y - 1.0, pos.z + 1.0) .grow(maxRange) val playerList = world.getEntitiesWithinAABB(EntityPlayer::class.java, range) if (playerList.isNotEmpty()) { for (player in playerList) { val distance = player.getDistance(pos.x.toDouble(), pos.y - 2.0, pos.z.toDouble()) if (distance <= maxRange) list.add(player) } } return list } }
0
Kotlin
0
0
4378a86bba82ac8772dd9bbc7c28f3964a964630
2,385
Minewell
MIT License