text:
Q: java.lang.IllegalArgumentException: Cannot round NaN value I'm developing a Jetpack Compose application, and I think a Slider is causing an error java.lang.IllegalArgumentException: Cannot round NaN value which causes my app to crash.
However, it doesn't give me any hints as to where or what is causing it to happen, beyond that it seems like it may be related to a Box composable. Furthermore, if I remove the Slider from my view, it looks like it isn't happening, so it seems like it is because of this Composable.
The slider is getting updated periodically and gets a value from an externally determined factor.
Is there something obviously wrong, or what can I do to debug or identify the problem?
My library versions are:
androidx-activity = "1.4.0"
androidx-appcompat="1.4.0"
androidxAnnotation="1.2.0"
androidx-core="1.7.0"
compose="1.1.1"

Here is my code
@Composable
fun MyComposable(
    modifier: Modifier = Modifier,
    viewModel: MyViewModel? = hiltViewModel<MyViewModel>()
) {
    LaunchedEffect(true) {
        viewModel.init()
    }
    Box(modifier = modifier.fillMaxSize()) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .align(Alignment.BottomCenter)
                    .padding(bottom = 20.dp)
                    .padding(horizontal = 20.dp)
            ) {
                Slider(
                    modifier = Modifier.fillMaxWidth(),
                    value = viewModel.sliderPosition,
                    onValueChange = viewModel::onSliderValueChange
                )
            }
        }
    }
}

@HiltViewModel
class MyViewModel {
    var sliderPosition: Float by mutableStateOf(0f)
    fun onSliderValueChange(value: Float) {
        sliderPosition = value
    }

    private fun tickerFlow(period: Duration, initialDelay: Duration = Duration.ZERO) = flow {
        delay(initialDelay)
        while (true) {
            emit(Unit)
            delay(period)
        }
    }

    fun init() {
        tickerFlow(period = .1.seconds, initialDelay = 0.seconds)
        .onEach {
            sliderPosition = getExternallyDeterminedSliderPositionValue()
        }
        .launchIn(viewModelScope)
    }
}

error:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.mycompany.app.android, PID: 29210
    java.lang.IllegalArgumentException: Cannot round NaN value.
        at kotlin.math.MathKt__MathJVMKt.roundToInt(MathJVM.kt:1132)
        at androidx.compose.ui.unit.Density$DefaultImpls.roundToPx-0680j_4(Density.kt:73)
        at androidx.compose.ui.layout.IntrinsicMeasureScope$DefaultImpls.roundToPx-0680j_4(IntrinsicMeasureScope.kt:25)
        at androidx.compose.ui.layout.MeasureScope$DefaultImpls.roundToPx-0680j_4(MeasureScope.kt:25)
        at androidx.compose.ui.node.LayoutNode$measureScope$1.roundToPx-0680j_4(LayoutNode.kt:493)
        at androidx.compose.foundation.layout.PaddingModifier.measure-3p2s80s(Padding.kt:361)
        at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:99)
        at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:98)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:126)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:88)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeMeasureSnapshotReads$ui_release(OwnerSnapshotObserver.kt:76)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:98)
        at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release(LayoutNode.kt:1317)
        at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release$default(LayoutNode.kt:1313)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.doRemeasure(MeasureAndLayoutDelegate.kt:170)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:228)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.forceMeasureTheSubtree(MeasureAndLayoutDelegate.kt:271)
        at androidx.compose.ui.platform.AndroidComposeView.forceMeasureTheSubtree(AndroidComposeView.android.kt:670)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:118)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.measure-BRTryo0(OuterMeasurablePlaceable.kt:75)
        at androidx.compose.ui.node.LayoutNode.measure-BRTryo0(LayoutNode.kt:1308)
        at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1.measure-3p2s80s(Box.kt:115)
        at androidx.compose.foundation.layout.BoxWithConstraintsKt$BoxWithConstraints$1$1.invoke-0kLqBqw(BoxWithConstraints.kt:67)
        at androidx.compose.foundation.layout.BoxWithConstraintsKt$BoxWithConstraints$1$1.invoke(BoxWithConstraints.kt:64)
        at androidx.compose.ui.layout.SubcomposeLayoutState$createMeasurePolicy$1.measure-3p2s80s(SubcomposeLayout.kt:355)
        at androidx.compose.ui.node.InnerPlaceable.measure-BRTryo0(InnerPlaceable.kt:55)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
2022-03-31 10:27:00.606 29210-29210/com.mycompany.app.android E/AndroidRuntime:     at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
        at androidx.compose.foundation.layout.SizeModifier.measure-3p2s80s(Size.kt:781)
        at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
        at androidx.compose.material.MinimumTouchTargetModifier.measure-3p2s80s(TouchTarget.kt:74)
        at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
        at androidx.compose.foundation.layout.FillModifier.measure-3p2s80s(Size.kt:658)
        at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
        at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:99)
        at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:98)
        at androidx.compose.runtime.snapshots.Snapshot$Companion.observe(Snapshot.kt:1798)
        at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:121)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:88)
        at androidx.compose.ui.node.OwnerSnapshotObserver.observeMeasureSnapshotReads$ui_release(OwnerSnapshotObserver.kt:76)
        at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:98)
        at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release(LayoutNode.kt:1317)
        at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release$default(LayoutNode.kt:1313)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.doRemeasure(MeasureAndLayoutDelegate.kt:170)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:228)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.access$remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:38)
        at androidx.compose.ui.node.MeasureAndLayoutDelegate.measureAndLayout(MeasureAndLayoutDelegate.kt:201)
        at androidx.compose.ui.platform.AndroidComposeView.measureAndLayout(AndroidComposeView.android.kt:662)
        at androidx.compose.ui.node.Owner$DefaultImpls.measureAndLayout$default(Owner.kt:182)
        at androidx.compose.ui.platform.AndroidComposeView.dispatchDraw(AndroidComposeView.android.kt:846)
        at android.view.View.draw(View.java:21884)
        at android.view.View.updateDisplayListIfDirty(View.java:20754)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
        at android.view.View.updateDisplayListIfDirty(View.java:20709)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
        at android.view.View.updateDisplayListIfDirty(View.java:20709)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
        at android.view.View.updateDisplayListIfDirty(View.java:20709)
        at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
        at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
        at android.view.View.updateDisplayListIfDirty(View.java:20709)
        at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:725)
        at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:731)
        at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:840)
        at android.view.ViewRootImpl.draw(ViewRootImpl.java:3944)
        at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3718)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3026)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1885)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8508)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
2022-03-31 10:27:00.606 29210-29210/com.mycompany.app.android E/AndroidRuntime:     at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7050)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler: java.lang.IllegalArgumentException: Cannot round NaN value.
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at kotlin.math.MathKt__MathJVMKt.roundToInt(MathJVM.kt:1132)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.unit.Density$DefaultImpls.roundToPx-0680j_4(Density.kt:73)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.layout.IntrinsicMeasureScope$DefaultImpls.roundToPx-0680j_4(IntrinsicMeasureScope.kt:25)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.layout.MeasureScope$DefaultImpls.roundToPx-0680j_4(MeasureScope.kt:25)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.LayoutNode$measureScope$1.roundToPx-0680j_4(LayoutNode.kt:493)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.foundation.layout.PaddingModifier.measure-3p2s80s(Padding.kt:361)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
2022-03-31 10:27:00.610 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:99)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:98)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:126)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:88)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OwnerSnapshotObserver.observeMeasureSnapshotReads$ui_release(OwnerSnapshotObserver.kt:76)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:98)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release(LayoutNode.kt:1317)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release$default(LayoutNode.kt:1313)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.doRemeasure(MeasureAndLayoutDelegate.kt:170)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:228)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.forceMeasureTheSubtree(MeasureAndLayoutDelegate.kt:271)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.platform.AndroidComposeView.forceMeasureTheSubtree(AndroidComposeView.android.kt:670)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:118)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable.measure-BRTryo0(OuterMeasurablePlaceable.kt:75)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.LayoutNode.measure-BRTryo0(LayoutNode.kt:1308)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.foundation.layout.BoxKt$boxMeasurePolicy$1.measure-3p2s80s(Box.kt:115)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.foundation.layout.BoxWithConstraintsKt$BoxWithConstraints$1$1.invoke-0kLqBqw(BoxWithConstraints.kt:67)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.foundation.layout.BoxWithConstraintsKt$BoxWithConstraints$1$1.invoke(BoxWithConstraints.kt:64)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.layout.SubcomposeLayoutState$createMeasurePolicy$1.measure-3p2s80s(SubcomposeLayout.kt:355)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.InnerPlaceable.measure-BRTryo0(InnerPlaceable.kt:55)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.DelegatingLayoutNodeWrapper.measure-BRTryo0(DelegatingLayoutNodeWrapper.kt:131)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.foundation.layout.SizeModifier.measure-3p2s80s(Size.kt:781)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.material.MinimumTouchTargetModifier.measure-3p2s80s(TouchTarget.kt:74)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.foundation.layout.FillModifier.measure-3p2s80s(Size.kt:658)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.ModifiedLayoutNode.measure-BRTryo0(ModifiedLayoutNode.kt:39)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:99)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable$remeasure$2.invoke(OuterMeasurablePlaceable.kt:98)
2022-03-31 10:27:00.611 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.runtime.snapshots.Snapshot$Companion.observe(Snapshot.kt:1798)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.runtime.snapshots.SnapshotStateObserver.observeReads(SnapshotStateObserver.kt:121)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OwnerSnapshotObserver.observeReads$ui_release(OwnerSnapshotObserver.kt:88)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OwnerSnapshotObserver.observeMeasureSnapshotReads$ui_release(OwnerSnapshotObserver.kt:76)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.OuterMeasurablePlaceable.remeasure-BRTryo0(OuterMeasurablePlaceable.kt:98)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release(LayoutNode.kt:1317)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.LayoutNode.remeasure-_Sx5XlM$ui_release$default(LayoutNode.kt:1313)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.doRemeasure(MeasureAndLayoutDelegate.kt:170)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:228)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.access$remeasureAndRelayoutIfNeeded(MeasureAndLayoutDelegate.kt:38)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.MeasureAndLayoutDelegate.measureAndLayout(MeasureAndLayoutDelegate.kt:201)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.platform.AndroidComposeView.measureAndLayout(AndroidComposeView.android.kt:662)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.node.Owner$DefaultImpls.measureAndLayout$default(Owner.kt:182)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at androidx.compose.ui.platform.AndroidComposeView.dispatchDraw(AndroidComposeView.android.kt:846)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.View.draw(View.java:21884)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.View.updateDisplayListIfDirty(View.java:20754)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.View.updateDisplayListIfDirty(View.java:20709)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.View.updateDisplayListIfDirty(View.java:20709)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.View.updateDisplayListIfDirty(View.java:20709)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.recreateChildDisplayList(ViewGroup.java:4542)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewGroup.dispatchGetDisplayList(ViewGroup.java:4514)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.View.updateDisplayListIfDirty(View.java:20709)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ThreadedRenderer.updateViewTreeDisplayList(ThreadedRenderer.java:725)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ThreadedRenderer.updateRootDisplayList(ThreadedRenderer.java:731)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ThreadedRenderer.draw(ThreadedRenderer.java:840)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewRootImpl.draw(ViewRootImpl.java:3944)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:3718)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:3026)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1885)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:8508)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.Choreographer.doCallbacks(Choreographer.java:761)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.Choreographer.doFrame(Choreographer.java:696)
2022-03-31 10:27:00.612 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.os.Handler.handleCallback(Handler.java:873)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.os.Handler.dispatchMessage(Handler.java:99)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.os.Looper.loop(Looper.java:214)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at android.app.ActivityThread.main(ActivityThread.java:7050)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at java.lang.reflect.Method.invoke(Native Method)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
2022-03-31 10:27:00.613 29210-29210/com.mycompany.app.android E/UncaughtExceptionHandler:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

A: The solution is that I didn't realize Floats can be NaN, and a NaN value was being returned from the getExternallyDeterminedSliderPositionValue function.


text:
Q: Facebook namespace problem causing invalid code I have seen various articles on this site and on google about how to make facebook code valid, but none of the solutions seem to work for me.
I think the problem lies in my doc type decleration:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"  xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/"  >

...
<meta property="og:site_name" content="my site name" />
<meta property="og:title" content="Buy...

Can anyone point me in the right direction please?
John

A: I'm having a similar problem.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:og="http://ogp.me/ns#" xml:lang="nl-NL">
...
<meta property="og:type" content="book" />

That's how almost all examples are like, and strangely it validates on w3c's validator, however all other validators including CSE Html validator and http://check.rdfa.info need a og prefix in front of the meta tag:
<og:meta property="og:type" content="book" />

That validates in almost anything except the official w3c validator. Not sure if facebook will parse it either. Why they chose not to use "name" is a big mystery for me. What a fine mess!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get items from list where index in () I have a list of CustomClassItem. I have several ints which are the indexes of the items I want to retrieve.
What is the quickest / most efficient way to get them? Something in the spirit of the index operator with more than one index or maybe myList.GetWhereIndexIs(myIntsList)?

A: You may use Linq:
List<CustomClassItem> items = myIntsList.Select(i => myList[i]).ToList();

Make sure that myIntsList.All(i => i >= 0 && i < myList.Count);
Edit:
If an index doesn't exist in the list, ignore this index:
List<CustomClassItem> items = myIntsList.Where(i => i >= 0 && i < myList.Count)
                                        .Select(i => myList[i]).ToList();

A: I think a nice and efficient solution would be to use yield in combination with an extension method:
public static IList<T> SelectByIndex<T>(this IList<T> src, IEnumerable<int> indices)
{
    foreach (var index in indices) {
        yield return src[index];
    }
}

Now you can do: myList.SelectByIndex(new [] { 0, 1, 4 });
You could also use a params object:
public static IList<T> SelectByIndexParams<T>(this IList<T> src, params int[] indices)
{
    foreach (var index in indices) {
        yield return src[index];
    }
}

Now you can do: myList.SelectByIndexParams(0, 1, 4);

A: What you want (if I'm reading correctly) is the following:
var indices = [ 1, 5, 7, 9 ];
list.Where((obj, ind) => indices.Contains(ind)).ToList();

That will give you a List<CustomClassItem> containing all those items whose indices are in your list.
Almost all of the LINQ extension methods accept a function taking a T and an int, that is the index of T in the Enumerable.  It's really handy.

A: Another approach using Enumerable.Join:
var result = myList.Select((Item, Index) => new { Item, Index })
    .Join(indices, x => x.Index, index => index, (x, index) => x.Item);

More efficient and safe(ensures that the indices exist) but less readable than other approaches.
Demo
Perhaps you want to create an extension which increases readability and reusability:
public static IEnumerable<T> GetIndices<T>(this IEnumerable<T> inputSequence, IEnumerable<int> indices)
{
    var items = inputSequence.Select((Item, Index) => new { Item, Index })
       .Join(indices, x => x.Index, index => index, (x, index) => x.Item);
    foreach (T item in items)
        yield return item;
}

Then you could use it in this way:
var indices = new[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var first5 = myList.GetIndices(indices).Take(5);

Used Take to demonstrate that linq's deferred execution still works here.


text:
Q: Prolog Counter Problem I am trying to write a procedure order(List,Result) that has a List as input and returns a list Result of ordered pairs such that:

*

*the first element of the ordered pair is the position of the pair in the list, and

*the second element of the ordered pair is the element from List n the corresponding             position.

Example:
if List = [a,b,c,d], the procedure order(List,Result) outputs the list:
Result = [(1,a), (2,b),(3,c),(4,d)].
I am struggling with the counter for the position of the pair in the list. I have made attempts such as:
increment(Accum,Total):-
        Total is Accum + 1.
order([],[]).
order([Head|Tail],Result):-
        order(Tail, NewTail),
        NewCount is Count + 1,
        increment(NewCount,Count),
        Result = [(Count,Head)|NewTail].

Please help anyone?

A: The two clauses: NewCount is Count + 1 and increment(NewCount,Count) basically have the same meaning. You didn't make clear that Count is an input variable and it has a base case of 1, so Prolog didn't know where to start unifying values for it. For example, you should use Count as an input argument as follows (it doesn't change much if compared with your version):
order([],[], _).
order([Head|Tail],[(Count,Head)|NewTail], Count):-
        NewCount is Count + 1,
        order(Tail, NewTail, NewCount).

order(List, Result ):- order(List, Result, 1).

A: If you're OK with using findall/3 then this is probably the simplest solution:
order(List, Result) :-
    findall(Index-Elem, nth1(Index, List, Elem), Result).

Note that here the key-value pairs are represented using the term -/2, which is how pairs are usually represented in Prolog, e.g. this is what keysort/2 expects.

A:
order(List,Result) :-
        findall((N,E),(
                    append(L0,[E|_],List),
                    length([_|L0],N)),
                Result).


text:
Q: HTML5 with Microsoft Visual Studio 2010 I tried to create a video tag in ASP.NET 4 in MVS 2010 but it didn't work. Is HTML5 already applied to Microsoft Visual Studio 2010? or do i need to install some kind of a software to make it function? I am asking about a safe Microsoft add-on or any other valid way.

A: http://visualstudiogallery.msdn.microsoft.com/en-us/d771cbc8-d60a-40b0-a1d8-f19fc393127d


text:
Q: Access kubectl explain kubectl explain tells explains attribute of an object in kubectl. E.g. k explain pod.spec.volumes.secret gives you some insight about how to mount secrets into your pod.
I would like to write a wrapper for this in Go. How do I access explain? Afaik the go client lib cannot access this, because explain is a feature of kubectl and not the cluster itself. I would like to avoid writing a bash script, executing this from go and parsing the output.

A: You could use the os/exec package.
Using that package you can execute your kubectl command and parse the output.
func main() {
    cmd := exec.Command("kubectl", "arg1", "arg2")

    var out bytes.Buffer
    cmd.Stdout = &out

    err := cmd.Run()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf(string(out.Bytes()))
}

Please find the documentation of that package here
Alternatively, you could try to import the important bits of the kubectl package and call these functions from within your code. This could work, as kubectl is written in Go.
Have a look at that repo: https://github.com/kubernetes/kubectl
I have never tried that, so i can't give further hints.


text:
Q: Changing firebase database I have an android project which is connected to a firebase database, is there any way that I can unlink my project from current database and connect my app to a new firebase database?

A: If you meant to link your android project to a different firebase project, then of course you can.
At the android side the "connection" is merely a json file stored at
yourProject/app/google-services.json.
You can simply replace it with another file that you may download from the settings page of your new firebase project.


text:
Q: Modify the algorithm to overcome the problem with the minimax for the game Players move in turns. A player moves first. Any player can move to an unoccupied
adjacent square, or can teleport from one end of the board to the other end, given that the other end is not occupied. For example, if A is at second node, and B is at node 5 can go to both 4 and 1. If B wins (occupies 1 cell), game is valued as -1, If A wins (occupies 5 cell), game is valued as +1.
However, there is a problem of loops in this problem, how to modify the algorithm or maybe the heuristic to avoid the problem with this game?
The image of the game:

A: Given the number of states is so small, it's easy just to brute-force this -- set won/loss states to +1 or -1, then repeatedly set any state to +1 if there's a move to a +1 state to +1 or -1 if all moves are to -1 states. Once there's no more changes, you have a solution and any undecided state is a draw by repetition.
Here's a program that does this. You can be a bit cleverer and exploit the symmetry between A and B to both reduce the number of states (and make the code a bit shorter), but this is the straightforward code:
def all_states():
    for p in range(2):
        for i in range(5):
            for j in range(5):
                if i == j: continue
                if i == 4 and j == 0: continue # impossible
                yield (p, i, j)

states = list(all_states())

def moves(s):
    p, i, j = s
    if p == 1:
        for p2, i2, j2 in moves((0, 4-j, 4-i)):
            yield 0, 4-j2, 4-i2
    else:
        for i2 in ((i-1)%5, (i+1)%5):
            if i2 != j:
                yield 1-p, i2, j

SCORE = {s: 1 if s[1] == 4 else -1 if s[2] == 0 else 0 for s in states}

change = True
while change:
    change = False
    for s in states:
        if SCORE[s] != 0: continue
        scores = [SCORE[s2] for s2 in moves(s)]
        if s[0] == 0 and 1 in scores:
            SCORE[s] = 1
            change = True
        elif s[0] == 0 and max(scores) == -1:
            SCORE[s] = -1
            change = True
        elif s[0] == 1 and -1 in scores:
            SCORE[s] = -1
            change = True
        elif s[0] == 1 and min(scores) == 1:
            SCORE[s] = 1
            change = True

def board(i, j):
    return ' '.join('A' if n==i else 'B' if n==j else 'x' for n in range(5))

for (p, i, j), sc in SCORE.items():
    print('AB'[p], 'to move: ', board(i, j), ' --', ['B wins', 'draw', 'A wins'][sc+1])

Output:
A to move:  A B x x x  -- A wins
A to move:  A x B x x  -- A wins
A to move:  A x x B x  -- A wins
A to move:  A x x x B  -- B wins
A to move:  B A x x x  -- B wins
A to move:  x A B x x  -- A wins
A to move:  x A x B x  -- B wins
A to move:  x A x x B  -- A wins
A to move:  B x A x x  -- B wins
A to move:  x B A x x  -- B wins
A to move:  x x A B x  -- A wins
A to move:  x x A x B  -- B wins
A to move:  B x x A x  -- B wins
A to move:  x B x A x  -- A wins
A to move:  x x B A x  -- A wins
A to move:  x x x A B  -- B wins
A to move:  x B x x A  -- A wins
A to move:  x x B x A  -- A wins
A to move:  x x x B A  -- A wins
B to move:  A B x x x  -- A wins
B to move:  A x B x x  -- A wins
B to move:  A x x B x  -- B wins
B to move:  A x x x B  -- A wins
B to move:  B A x x x  -- B wins
B to move:  x A B x x  -- B wins
B to move:  x A x B x  -- A wins
B to move:  x A x x B  -- B wins
B to move:  B x A x x  -- B wins
B to move:  x B A x x  -- B wins
B to move:  x x A B x  -- B wins
B to move:  x x A x B  -- B wins
B to move:  B x x A x  -- B wins
B to move:  x B x A x  -- B wins
B to move:  x x B A x  -- A wins
B to move:  x x x A B  -- B wins
B to move:  x B x x A  -- A wins
B to move:  x x B x A  -- A wins
B to move:  x x x B A  -- A wins

A: We can make the following observations:

*

*There are at most two valid moves at each turn.

*If the players start such that A is at the left of B, then the one who can make the teleporting move first wins the game. So the best move for them is to walk towards their teleporting square. If they are already there, they should teleport, or if that is not possible, perform the only remaining move (in which case the other player can win on their next move).

*If the players start such that A is at the right of B, the one who reaches their winning square first wins the game. So the best move for them is to walk towards their target square.
In other words, the player's best "strategy" is:
Don't play the (non-teleporting) move towards the opponent unless that is the only possible move.
So there is no reason to do minimax, not even a search. The best move can be known immediately from the current game state.


text:
Q: How to implemet isTimerRunning() for this class I have this code, which basically provides a custom timer for my application.
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

public class SMSFirewallTimer {
    private static Logger logger = Logger.getLogger(SMSFirewallTimer.class);
    Timer timer;
    String timerId;

    public SMSFirewallTimer(int seconds, String string) {
        timer = new Timer();
        timerId = string;
        logger.debug("SMSFirewallTimer: timer started for: "+seconds +"seconds");
        timer.schedule(new Timeout(string), seconds*1000);
    }

    public void cancelTimer()
    {
        this.timer.cancel();
        logger.debug("SMSFirewallTimer: Cancelling timer for : " + this.timerId);
    }

    class Timeout extends TimerTask {
        private String string;
        public Timeout(String string) {
            this.string = string;

        }
        @Override
        public void run() {
            logger.debug("SMSFirewallTimer: Time's up! for: " + this.string );
            timer.cancel(); //Terminate the timer thread
        }
    }
}

Now the problem arises that I want a isRunning() method in SMSFirewallTimer which will tell me that if the timer is still running or not, and it should also keep timeout in mind.
If I just declare a boolean as isTimer in this class it only holds good if we use cancelTimer(), but it wont come to know if timer expired, as its another scheduled method new Timeout(string).

A: Try this
import java.util.Timer;
import java.util.TimerTask;

import org.apache.log4j.Logger;

public class SMSFirewallTimer {
    private static Logger logger = Logger.getLogger(SMSFirewallTimer.class);
    Timer timer;
    String timerId;
    private Boolean isRunning;

    public SMSFirewallTimer(int seconds, String string) {
        timer = new Timer();
        timerId = string;
        logger.debug("SMSFirewallTimer: timer started for: "+seconds +"seconds");
        isRunning = true;
        timer.schedule(new Timeout(string), seconds*1000);
    }

    public void cancelTimer()
    {
        isRunning = false;
        this.timer.cancel();
        logger.debug("SMSFirewallTimer: Cancelling timer for : " + this.timerId);
    }

    public boolean isRunning() {
        return isRunning;
    }

    class Timeout extends TimerTask {
        private String string;
        public Timeout(String string) {
            this.string = string;

        }
        @Override
        public void run() {
            logger.debug("SMSFirewallTimer: Time's up! for: " + this.string );
            isRunning = false;
            timer.cancel(); //Terminate the timer thread
        }
    }
}

Also you can keep reference for Timeout if you don't want to have access from your Timeout to your SMSFirewallTimer isRunning field.

A: Timeout is an inner class of SMSFirewallTimer which means that each instance of SMSFirewallTimer is tied to a specific instance of SMSFirewallTimer and that is has access to its fields and methods.
It should be sufficient to replace:
        timer.cancel(); //Terminate the timer thread

with
        cancelTimer(); //Terminate the timer thread

in the run method of Timeout.


text:
Q: Add Colour Gradient to Circular Progress Bar iOS I am having difficulty adding a colour gradient to my circular progress bar

My setup:

*

*Storyboard: ViewController with an empty view designated as the Class CircularProgressBar

*Custom class for the CircularProgressBar

Steps Taken:

*

*I am able to load circular progress bar

*In earlier attempts I created a gradient shape layer & set it to be masked by the bounds of the BarLayer, however the gradient shape layer draw a rectangle starting from the centre of my circle & extend to the bottom right so only that portion of the BarLayer would have a gradient

*When I moved the origin of the gradient layer rectangle it shifted the Barlayer off the TrackLayer with it

How do I:
Have the gradient layer cover the entire circular progress bar & mask it to the BarLayer
class CircularProgressBar: UIView {

let shapeLayer = CAShapeLayer()
let trackLayer = CAShapeLayer()

override init(frame: CGRect) {
super.init(frame: frame)
    addProgressBar(radius: 5, progress: 0)
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
    addProgressBar(radius: 5, progress: 0)
}

func addProgressBar(radius: CGFloat, progress: CGFloat) {

    let lineWidth = radius*0.080

    let circularPath = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat.pi*2, clockwise: true)

    //TrackLayer
    trackLayer.path = circularPath.cgPath
    trackLayer.fillColor = UIColor.lightGray.cgColor
    trackLayer.strokeColor = UIColor.clear.cgColor
    trackLayer.opacity = 0.5
    trackLayer.lineWidth = lineWidth
    trackLayer.lineCap = CAShapeLayerLineCap.round

    //BarLayer
    shapeLayer.path = circularPath.cgPath
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.strokeColor = UIColor.systemGreen.cgColor
    shapeLayer.lineWidth = lineWidth
    shapeLayer.strokeEnd = 0
    shapeLayer.lineCap = CAShapeLayerLineCap.round

    //Rotate Shape Layer
    shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)

//Shape Shadow
    shapeLayer.shadowColor = UIColor.black.cgColor
    shapeLayer.shadowOffset = CGSize(width: -7, height: 7)
    shapeLayer.shadowRadius = 1
    shapeLayer.shadowOpacity = 0.5

    //Animation
    loadProgress(percentage: progress)

    //LoadLayers
    layer.addSublayer(trackLayer)
    layer.addSublayer(shapeLayer)

}
func loadProgress(percentage: CGFloat) {

    let basicAnimation = CABasicAnimation(keyPath: "strokeEnd")
    basicAnimation.fromValue = 0
    basicAnimation.duration = 2
    basicAnimation.fillMode = CAMediaTimingFillMode.forwards
    basicAnimation.isRemovedOnCompletion = false
    shapeLayer.strokeEnd = percentage
    shapeLayer.add(basicAnimation, forKey: "basicStroke")

}

ViewController
class HomeViewController: UIViewController {

@IBOutlet weak var containerView: UIView!

var circularProgressBar = CircularProgressBar()
var radius: CGFloat!
var progress: CGFloat!

var answeredCorrect = 0
var totalQuestions = 0

override func viewDidLoad() {
    super.viewDidLoad()

    answeredCorrect = 50
    totalQuestions = 100

    //Configure Progress Bar
    radius = (containerView.frame.height)/2.60
    progress = CGFloat(answeredCorrect) / CGFloat (totalQuestions)
    circularProgressBar.addProgressBar(radius: radius, progress: progress)
    circularProgressBar.center = containerView.center

    //Adding view
    containerView.addSubview(circularProgressBar)

}
}

A: If you are looking for something like this

You need to update your code
import UIKit
@IBDesignable
class CircularProgressBar: UIView {

let shapeLayer = CAShapeLayer()
let trackLayer = CAShapeLayer()

override init(frame: CGRect) {
super.init(frame: frame)
   // addProgressBar(radius: 50, progress: 50)
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
   // addProgressBar(radius: 50, progress: 50)
}
  override func layoutSubviews() {
    addProgressBar(radius: 50, progress: 50)
  }
func addProgressBar(radius: CGFloat, progress: CGFloat) {

  let lineWidth = CGFloat(10.0)//radius*0.080

    let circularPath = UIBezierPath(arcCenter: CGPoint(x: bounds.midX, y: bounds.midY), radius: radius, startAngle: 0, endAngle: CGFloat.pi*2, clockwise: true)

    //TrackLayer
    trackLayer.path = circularPath.cgPath
    trackLayer.fillColor = UIColor.lightGray.cgColor
    trackLayer.strokeColor = UIColor.clear.cgColor
    trackLayer.lineWidth = lineWidth
    trackLayer.lineCap = CAShapeLayerLineCap.round

    //BarLayer
    shapeLayer.path = circularPath.cgPath
    shapeLayer.fillColor = UIColor.black.cgColor
    shapeLayer.strokeColor = UIColor.systemGreen.cgColor
    shapeLayer.lineWidth = lineWidth*2
    //shapeLayer.strokeEnd = 0
    shapeLayer.lineCap = CAShapeLayerLineCap.round

    //Rotate Shape Layer
   // shapeLayer.transform = CATransform3DMakeRotation(-CGFloat.pi/2, 0, 0, 1)

    //Animation
   // loadProgress(percentage: progress)

    //LoadLayers
   layer.addSublayer(trackLayer)
   self.addGradient()

  // layer.addSublayer(shapeLayer)

}

  private func addGradient() {
    let gradient = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor,UIColor.purple.cgColor,UIColor.systemPink.cgColor,UIColor.blue.cgColor]
    gradient.frame = bounds
    gradient.mask = shapeLayer
    layer.addSublayer(gradient)
  }
}

And for Uniform gradient you can replace addGradient method

private func addGradient() {
    let gradient = CAGradientLayer()
    gradient.colors = [UIColor.red.cgColor,UIColor.cyan.cgColor,UIColor.brown.cgColor,UIColor.blue.cgColor]
    gradient.frame = bounds
    gradient.locations = [0.2,0.5,0.75,1]
    gradient.startPoint = CGPoint(x: 0.5, y: 0.5)
    gradient.endPoint = CGPoint(x: 0.5, y: 0)
    gradient.type = .conic
    gradient.mask = shapeLayer
    layer.addSublayer(gradient)
  }


text:
Q: Angular 5 : How to send multiple params in HttpClient Post request? I have been trying to send a POST request with httpClient in Angular5 , but it seems that nothing is working , i don't get any errors at the same time no result .
This is the way i tried :
 addProjToClient(idPerson:number,idProject:number){
    if(this.authService.getToken()==null) {
      this.authService.loadToken();
    }

    return this.http.post(this.host+"/saveProjectToClient", {
      idPerson,
      idProject,
    }, {headers:new HttpHeaders({'Authorization':this.authService.getToken()})})

  }

but the API rest in back end ( spring boot ) is not reachable this way , i tried others solutions in github , even stackoverflow but with no result , any idea ?
PS : the Api rest is working well when i try to call it with the ARC extention.
**EDIT : the API rest **
 @RequestMapping(value="/saveProjectToClient",method=RequestMethod.POST)
    public boolean saveProjectToClient(@RequestBody Dto dto){
        System.out.println("Person id : ");
        System.out.println(dto.getIdPerson());
        System.out.println("Project id : ");
       System.out.println(dto.getIdProject());

         return true;
    }


text:
Q: I cannot give the flex feature to the menuItem inside the select element I have a selector component that I will flag with to select the language option. But the picture I added does not seem to be centered from top to bottom. For this, it is enough to give displayI flex to MenuItem. But I can't write again. Why not?
```
import styles from './index.module.scss';
import Turkey from '../../icons/languages/Turkey_flat.png';
import En from '../../icons/languages/United-Kingdom_flat.png';
import Germany from '../../icons/languages/Germany_flat.png';

const LanguageSelect = props => {
  const { className, onChange, style, ...rest } = props;

  const [language, setLanguage] = React.useState("TR");

  const handleLanguageChange = event => {
    setLanguage(event.target.value);
  };

  return (
    <Select
      classes={{
        root: styles[`language-select`]
      }}
      value={language}
      onChange={handleLanguageChange}
      autoWidth
    >
      <MenuItem className={styles['display']} value="TR"> <img className={styles['language-select-flag']} src={Turkey}/>Türkçe</MenuItem>
      <MenuItem value="ENG"><img className={styles['language-select-flag']} src={En}/>İngilizce</MenuItem>
      <MenuItem value="DE"><img className={styles['language-select-flag']} src={Germany}/>Almanca</MenuItem>

    </Select>
  );
};

LanguageSelect.propTypes = {
  className: PropTypes.string,
  onChange: PropTypes.func,
  style: PropTypes.object
};

export default LanguageSelect;

index.scss
----
```
.display{
  display: flex!important;
}
```

[enter image description here][1]

  [1]: https://i.stack.imgur.com/rLKMO.png

A: When I couldn't do it with that method, I made the look I wanted with another solution. In that
      classes={{
        root: styles[`language-select`]
      }}
      value={language}
      onChange={handleLanguageChange}
      autoWidth
    >
      <MenuItem value="TR">
        <ListItemIcon>
          <img className={styles['language-select-flag']} src={Turkey}/>
          <ListItemText>Türkçe</ListItemText>
        </ListItemIcon>
      </MenuItem>
      <MenuItem value="ENG">
        <ListItemIcon>
          <img className={styles['language-select-flag']} src={En}/>
          <ListItemText>İngilizce</ListItemText>
        </ListItemIcon>
      </MenuItem>
      <MenuItem value="DE">
        <ListItemIcon>
          <img className={styles['language-select-flag']} src={Germany}/>
          <ListItemText>Almanca</ListItemText>
        </ListItemIcon>
      </MenuItem>

    </Select>````

css edit

``` flag{
        width: 20px;
        height: 20px;
        margin: auto 4px;
      }```


text:
Q: HighStocks Array Series Im creating a singleline series chart using dates and closing prices from yahoo. I have converted the dates into JS timestamps and put them in an array named timeStampArray and put the closing prices into an array named closePrices.
I can populate the chart with data like so:
data : [
          [ 1361750400000, 442.80],
          [ 1361491200000, 450.81]

       ],

I wish to use the data from my arrays and the API says to use an array with two values for x and y, like this
data: [[5, 2], [6, 3], [8, 2]]
therefore can I combine my two arrays so that they fit this format?
I can only find examples of how to combine my arrays into key-value pairs like this {'test1':'1', 'test2':'2'};
Also when I create the chart using hardcoded data it orders the dates in ascending order but I want it to keep the ordering that they are input, e.g 25th Feb before 22nd Feb as this is showing historical data.
Is there a way to correct this?
Heres the jsFiddle of my current code: http://jsfiddle.net/mXnZy/
update: ive tried
var timeClose = new Array();
for(var i=0; i<data.query.results.quote.length; i++)
            {
                   timeClose.push( [timeStampArray[i], closePrices[i]] );
            }

however this outputs [1361750400000, 442.80, 1361491200000, 450.81] which is wrong.

A: If you mean that you want them sorted in reverse order, you can use the 'reversed' property on the x axis:
http://api.highcharts.com/highstock#xAxis.reversed
If you mean that you want them listed in whatever order they're entered, without being sorted, it will be much more complicated.
You could provide ordinal x values, and provide the date as additional data.  You could then use the axis label formatter to show the dates that you wish.


text:
Q: Is it possible to create a non-ecommerce site using Magento? I have a site to develop that needs to be a kind of voucher code site. This means that the site will provide voucher codes for other sites, the user will come to my site and pick voucher codes for another site and will then redirect to the target site. In short, it does not need any Add-to-Cart functionality of magento.

An example site is shown below in link: https://www.promothecode.com/coupon/chiquito

However, the site I plan to create requires a strong Admin side for Support, so I believe Magento has a strong Admin interface and that is the reason why I am planning to choose Magento for my site. So my questions are:

*

*Is it good to use magento for developing such non e-commerce sites

*What are the best practices that should take care of when developing such sites using magento
Please share your thoughts... Thanks in advance!

A: If you want to build non-commercial website then you have to use different framework (like word-press,Joomla,Drupal), because Magento is specially designed for E-commerce based website builder platform right.

A: "Is it possible?" and "is it worth it?" are 2 different things.
But let's take them one by one:
Is it possible?
Yes. It certainly is.
I've done this in magento 1 using Colin Mollenhour's Magento Lite: https://github.com/colinmollenhour/magento-lite
For magento 2 is a little more difficult because of all the dependency checks and the circular module dependencies. SO you cannot remove some modules without removing the full circle of dependencies.
I did a presentation in 2016 about exactly this... stripping down all the modules you don't need so you end up with only the framework and CMS functionality and build on top of that. It may be outdated because magento changed a lot since then, but it may help you if you decide to start on this adventure: https://github.com/tzyganu/MageTitansIt2016/blob/master/Magento-2-as-a-CMS.pdf.
Is it worth it?
My personal opinion is NO.

*

*Magento was designed to work for e-commerce websites and it centers around the products and categories.

*You will have some (if not a lot) of troubles removing unnecessary modules from magento to make the code cleaner.

*If you don't want to clean it up and decide to use it like it is and just hide from frontend and backend the links to modules you don't need you will end up with useless code that only adds overhead to the performance.

*Magento 2 does not play well with a shared host. You may decide that your website is simple enough and does not require a dedicated hosing that may cost way more than a shared one.

*you will have to do your custom entities "the magento way" when in practice you may not actually need it.


text:
Q: Azure Fault Domain Selection I have a requirement to create 7 VM in availability set and maximum 2 VM servers can be rebooted at a time.
I want to create 3 Fault domain and 4 upgrade domain.

some people suggest 2 FD and 4 UD. I do not agree with them. To create 3 FD will help when 2 racks would go down at least my 1VM will alive.
Am'I correct? If not please tell me why??

A: Go for 3 FD and 4 UD. The only problem - some regions do not support 3 FD.


text:
Q: C++ convert boost multiprecision int to 64 bit length hex lets imagine that we have code:
boost::multiprecision::mpz_int one(1);

and I would like to convert that value to 64 bit (?) hex value so the result could be:
0000000000000000000000000000000000000000000000000000000000000001

I'm sure that the is solution of that but I'm not familiar with Boost
Example:
I have value:
boost::multiprecision::mpz_int value(8612844778121073626993440829679478604092771119379437256704)

and I want create 64b hex from value,
I tried
printf("%064X\n", value);

but don't work

A: Even with the extra example it is still unclear what you want to do:
a) Do you want to write the binary representation of the integer which you can think of as a string of 64 characters 0 or 1 as your first example suggests?
b) Or do you want the hex representation which would be a 16 character string?
What do you want to do if your integer does not fit into 64 bit?
I assume you want to print the hex representation of the integer filled with zeros, i.e. (b). Then the solution is as easy as (you claim to use c++)
std::cout << std::setfill('0') << std::setw( 16 ) << std::hex << value;

However this solution does not cover the unspecified behaviour of overflowing the 64 bit and it does not cover negative numbers. For this you need to be more precise...

Update:
According to the comment the output should be a 64 character string which could represent a 256 bit integer. This can be accomplished with:
std::cout << std::setfill('0') << std::setw( 64 ) << std::hex << value;

A: I don't have boost available atm but you could write a small function that formats the type for you.
If boost::multiprecision::mpz_int supports bitshift and the & operator operator this might be a solution:
template<typename T>
std::string toHex64(const T& value, size_t padding = 1)
{
    using UT = typename std::make_unsigned_t<T>;
    std::string hex;
    UT uvalue = static_cast<UT>(value);
    bool bPositive = std::is_same<T, UT>::value || value == uvalue;
    while (uvalue > UT(0))
    {
        char current = uvalue & 0xF; uvalue >>= 4;
        hex += (current < 0xA) ? (current + '0') : ((current-10) + 'A');
    }
    if (hex.size() < padding)
    {
        if (bPositive)
        {
            hex += std::string(padding - hex.size(), '0');
        }
        else
        {
            hex += std::string(padding - hex.size(), 'F');
        }
    }
    std::reverse(hex.begin(), hex.end());
    return hex;
}


text:
Q: Call [tableView realoadData] on RootViewController from AppDelegate? In my app I am making an HTTP request and waiting and updating my RootViewController with the data. The problem is, I need to make a call to [tableView reloadData] after my data collection has finished, as it stands right now the tableview will either be partially populated or not populated at all. I came across this thread:
Passing an NSDictionary to a ViewController from AppDelegate
Which included this solution for setting data in the view conroller from app delegate, but I am wondering how I can adapt this for my situation? All I need, I think, is a reference to the rootViewController in appDelegate so I can call reloadData when I need to
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil tableDataSource:(NSArray*)tableData {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
    // Custom initialization
    tableDataArray = [tableData retain];

}
return self;
}

Thanks for any ideas

A: Declare that tableView as a property such as myTableView in that class. Now reference that class and call [classObject.myTableView reloadData];
It should work.

A: You can give the appDelegate a property that receives a pointer to the RootViewController and which is set by the RootViewController when it is initialized.
- (id)initWithNibName:(NSString *)nibNameOrNil
               bundle:(NSBundle *)nibBundleOrNil
      tableDataSource:(NSArray*)tableData
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        // Custom initialization
        tableDataArray = [tableData retain];
        (MyAppDelegate *)([[UIApplication sharedApplication] delegate]).rootController = self;
    }
    return self;
}


text:
Q: google maps api geolocation doesn't update on timeout I know this is probably not the most performant code possible, but if anyone can help I'd really appreciate that.
I'm working on a web-application that's supposed to locate the user's position with the google maps api. For this I created an UI control that starts the tracking of the user's current position and starts a timeout function that should update the position of the user. Everything works fine, but I testet the app when moving around and the geolocation doesn't change with the timeout, it always just shows the position of the first loop. I have to click on the UI control again to update the position.
These are the functions I adapted from the Google developer sites:
The function to detect the position:
    //locate the user via GPS by checking geopositioning
function locateUser(geoLoc) {
  var geoSuccess = function(position, map) {
    startPos = position;
    userLat = startPos.coords.latitude;
    userLon = startPos.coords.longitude;
    geoLoc = {lat : userLat ,lng : userLon};

  };
  var geoError = function(error, map) {
    geoLoc = null;
    //console.log('Error occurred. Error code: ' + error.code);
    // error.code can be:
    //   0: unknown error
    //   1: permission denied
    //   2: position unavailable (error response from location provider)
    //   3: timed out
  };

  navigator.geolocation.getCurrentPosition(geoSuccess, geoError);

};

locateUser(geoLoc);

I'm using the variable "geoLoc" to get latitude and longitude within the map api.
This is the function that is called by a click on the UI-control and that starts the timeout:
//set the marker for the current position to the geolocation, when geolocation is possible
function setUserPosition(map, geoLoc, controlUI) {
    //get the geolocation
    locateUser(geoLoc);

    //check if the position marker for the user position is already attached
    if (positionSet == false) {
    //if the position marker is not attached (first time user hits the UI control), generate and attach it nad notify the user that it's position is tracked

       positionSet = true;

        var userpos = {
        url: "https://myhost.com/mygraphic.png", // url
        scaledSize: new google.maps.Size(45,45), // scaled size
        origin: new google.maps.Point(0,0), // origin
        anchor: new google.maps.Point(23,23) // anchor
        };

        positionMarker = new google.maps.Marker({
        position: geoLoc,
        map: map,
        zIndex: 100,
        icon: userpos
      });

    }

//Check if geolocation is possible.
//If geolocation is not possible, hide the location marker and change the UI control's state back to default, but try again in three seconds.
    if(geoLoc == null) {
      controlUI.style.backgroundColor = '#4485F8';
      controlUI.style.backgroundImage = "url('https://myhost.com/oldbackgroundimage.png')";
      moveControl = false;
    } else {

//If geolocation is possible, make the position marker visible, set it to the located position and cahnge the UI's state to "active".
        posMark = positionMarker;

        posMark.setPosition(geoLoc);

      controlUI.style.backgroundColor = '#eeeef4';
      controlUI.style.backgroundImage = "url('https://myhost.com/newbackgroundimage.png')";
      moveControl = true;

    }

   map.panTo(geoLoc);

//check if the user hit the button to start the positiontracking and loop the function if so
   if(moveControl == true) {
    timeoutControl = setTimeout(function(){setUserPosition(map, geoLoc, controlUI)}, 3000);
   } else if(moveControl == false) {
    clearTimeout(timeoutControl);
   }

}

And this is the function for the UI-control within the init-map function:
controlUI.addEventListener('click', function() {

      //check if the user tapped the UI to locate the current position
      if(moveControl == false) {
      moveControl = true;
      locateUser();

      //if geolocation is not possible, open an alert to notify the user
      if(geoLoc == null) {
        alert("No geolocation :(");
      } else {
      //if geolocation is possible, set the UI control to the "active" state and start the interval to locate the user permanently (every three seconds)
      controlUI.style.backgroundColor = '#eeeef4';
      controlUI.style.backgroundImage = "url('https://myhost.com/newbackgroundimage.png')";
      setUserPosition(map, geoLoc, controlUI);
      //Show the Position marker
      posMark.setMap(map);

      }
      //if the user has tapped the UI control and is in "location-mode" this tap stops the location mode and sets everything back into default state
      } else if(moveControl == true) {
      clearTimeout(timeoutControl);
      moveControl = false;
      controlUI.style.backgroundColor = '#4485F8';
      controlUI.style.backgroundImage = "url('https://myhost.com/oldbackgroundimage.png')";
      //Hide the Position marker
      posMark.setMap(null);
      }
  });

I ran the script with an alert to display geoLoc within the geoSucess function of the locateUser function and it gets executed every time the timeout runs over the code and always fires geoLoc with data, but always only the position the user had when he first clicked the UI control.
Can anybody help and does know why the position is not updated within the timeout or maybe know how it would be updated?
Thanks a lot & kind regards,
Philipp


text:
Q: Get ListView Item Values of row tapped Get ListView Item Values of row tapped. I am able to get the item tapped in code behind like so:
private async void Item_Tapped(object sender, ItemTappedEventArgs e)
{
    ListView listView = (ListView)sender;
    if (listView != null)
    {
       string pName = e.Item //.PNname; **<<-- This is returning my bound values (4 items) as PName, PNumber... and so on**
    }
}

I try to type the .PName it is a sub value to the e.Item list but that is invalid. I really need to grab by name because it appears the return selected row item returns values in a random way? One time PName will be first then next it might be 2nd or 3rd?
Anyway what am I missing to grab the values I need?
I'm doing a lot more visual things here but wanted to keep this code very simple to what I am actually having an issue with getting the individual values in the row.
TIA!
Cheers!
Rick...

A: e.Item is an object (datatype), if I am not mistaken. You have to cast e.Item to the right data type first:
string pName = (e.Item as Person)?.PName;

(assuming that PName is a property of the class Person)

A: Try get the itemIndex clicked and get the element in the list or use the AutomationId.


text:
Q: Android TurnBasedMutliplayer No Callbacks I have been following the guide here to add TurnBased Multiplayer to an android game. https://developers.google.com/games/services/android/turnbasedMultiplayer#before_you_begin. I have coded everything up and am able to have users login to google play services. Then using the BaseGameUtils I attempt to create a match using the following function below but I never receive a callback other than timeouts.
void CreateMatch(MatchConfig matchConfig) {
    int minAutoMatchPlayers = 2;
    int maxAutoMatchPlayers = 2;

    Bundle autoMatchCriteria = TurnBasedMatchConfig.createAutoMatchCriteria(minAutoMatchPlayers, maxAutoMatchPlayers, 0);

    TurnBasedMatchConfig curMatch = TurnBasedMatchConfig.builder()
            .setAutoMatchCriteria(autoMatchCriteria)
            .build();

    if (!googleApiClient.isConnected()) {
        Log.d(TAG, "Not connected to google api so unable to create a match");
        return;
    }

    // Attempt creating a match and set this as the callback
    Games.TurnBasedMultiplayer.createMatch(googleApiClient, curMatch).setResultCallback(this, 5, TimeUnit.SECONDS);
}

I implemented the ResultCallback<TurnBasedMultiplayer.InitiateMatchResult> in the same class, but as mentioned never get any callbacks.
public void onResult(TurnBasedMultiplayer.InitiateMatchResult initiateMatchResult) {
    Status status = initiateMatchResult.getStatus();
    Log.d(TAG, "Match creation status " + status);

Im not sure how to debug this further or why im not getting any callbacks. I have:
Setup my developer account and added/enable turnbased games. The App is in Alpha there.
Setup the OAuth key and AppId in the manifest.
Tested with signed APKs. Tested with two different google accounts on
   two different phones.
Tried using Games.TurnBasedMultiplayer.loadMatchesByStatus(googleApiClient,
   TurnBasedMatch.MATCH_TURN_STATUS_ALL).setResultCallback(this); but
   it always returns 0 matches.
Any information on how to debug this
   further would be greatly appreciated.

A: Did you try adding
Implement OnInvitationReceivedListener and OnTurnBasedMatchUpdateReceivedListener
to your activity?
Also
In onConnected(Bundle connectionHint) Games.Invitations.registerInvitationListener(mGoogleApiClient, this) and Games.TurnBasedMultiplayer.registerMatchUpdateListener(mGoogleApiClient, this)


text:
Q: Python Game: Control Square. If square reaches within 10 pixels of random spawned square it adds 1 point. Doesn't work. Why? I made a game where you control a square and a random other square spawns randomly on the map. If the first square gets within 10 pixels of the other it adds a point but the program doesn't work. Can anyone tell me why?
Here is my code:
from tkinter import *
from random import uniform, randrange
tk = Tk()
canvas = Canvas(tk, width=400, height=400,bg='black')
canvas.pack()
pointcount = -1
LENGTH = 15
WIDTH = 15
LENGTH2 = randrange(1,390)
WIDTH2 = randrange(1,390)
LENGTH3 = LENGTH2 + 15
WIDTH3 = WIDTH2 + 15
X = randrange(1,400)
Y = randrange(1,400)
Snake = canvas.create_rectangle(0,0,WIDTH,LENGTH,fill="green")
Food = canvas.create_rectangle(WIDTH2,LENGTH2,WIDTH3,LENGTH3,fill="yellow")
pos = canvas.coords(Snake)
pos2 = canvas.coords(Food)
def movement_right(event):
    canvas.move(Snake,15,0)
def movement_left(event):
    canvas.move(Snake,-15,0)
def movement_down(event):
    canvas.move(Snake,0,15)
def movement_up(event):
    canvas.move(Snake,0,-15)
for i in range(1,20):
    if pos[0] - pos2[2] == 10:
        pointcount = pointcount + 1
        print("Total points : ", pointcount)
        tk.update()

tk.bind('<Left>', movement_left)
tk.bind('<Right>', movement_right)
tk.bind('<Down>', movement_down)
tk.bind('<Up>', movement_up)

tk.mainloop()

A: You have to check it inside functions because other code is executed only once.
You can create on function to test positions and execute in all movement_ functions.
I use "cells" to set positions
import tkinter as tk
import random

# --- constants --- (UPPER_CASE names)

SCREEN_WIDTH = 400
SCREEN_HEIGHT = 400

CELL_WIDTH = 20
CELL_HEIGHT = 20

COLS = SCREEN_WIDTH/CELL_WIDTH
ROWS = SCREEN_HEIGHT/CELL_HEIGHT

# --- functions ---

def test():
    global pointcount

    snake_pos = canvas.coords(snake)
    food_pos = canvas.coords(food)

    # calculate distance
    diff_x = abs(snake_pos[0] - food_pos[0])
    diff_y = abs(snake_pos[1] - food_pos[1])

    print(diff_x, diff_y)

    # if snake eat food
    if diff_x == 0 and diff_y == 0:
        pointcount += 1
        print("Total points : ", pointcount)

        # move food to new place
        food_x1 = CELL_WIDTH * random.randrange(0, COLS)
        food_y1 = CELL_HEIGHT * random.randrange(0, ROWS)

        food_x2 = food_x1 + CELL_WIDTH
        food_y2 = food_y1 + CELL_HEIGHT

        canvas.coords(food, (food_x1, food_y1, food_x2, food_y2))

def movement_right(event):
    canvas.move(snake, CELL_WIDTH, 0)
    test()

def movement_left(event):
    canvas.move(snake, -CELL_WIDTH, 0)
    test()

def movement_down(event):
    canvas.move(snake, 0, CELL_HEIGHT)
    test()

def movement_up(event):
    canvas.move(snake, 0, -CELL_HEIGHT)
    test()

# --- other --- (lower_case names)

pointcount = 0

# --- main ---

root = tk.Tk()

canvas = tk.Canvas(root, width=SCREEN_WIDTH, height=SCREEN_HEIGHT, bg='black')
canvas.pack()

root.bind('<Left>', movement_left)
root.bind('<Right>', movement_right)
root.bind('<Down>', movement_down)
root.bind('<Up>', movement_up)

snake = canvas.create_rectangle(0, 0, CELL_WIDTH, CELL_HEIGHT, fill="green")

# create food in first random place
food_x1 = CELL_WIDTH * random.randrange(0, COLS)
food_y1 = CELL_HEIGHT * random.randrange(0, ROWS)

food_x2 = food_x1 + CELL_WIDTH
food_y2 = food_y1 + CELL_HEIGHT

food = canvas.create_rectangle(food_x1, food_y1, food_x2, food_y2, fill="yellow")

root.mainloop()


text:
Q: SASS - Grupo de cores para re-uso estou iniciando no SASS, e estou com um probleminha que não estou conseguindo resolver.
Tenho um grupo de cores, que serão utilizados em várias sessões do meu site.
Basicamente, tenho uma estrutura assim:

        SÁBADO, 17/05/2017, 20:07

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla, quam dolore nemo itaque possimus? Dolore, doloribus corporis, voluptatibus, quasi necessitatibus hic quo quia rem, asperiores libero soluta. Eveniet, optio aspernatur.

Tenho minha lista de cores assim:
$cor-regioes: #b71c1c;
$cor-esporte: #1b5e20;
$cor-saude: #f57f17;
$cor-arte: #0d47a1;

O que gostaria de "automatizar" é que quando eu colocar a class "regioes", os elementos internos daquela section pegariam as cores da minha variavel cor-regioes, como o a:hover, span, etc.
Eu tentei assim:
$cor-esporte: #1b5e20;
$cor-vida: #f57f17;
$cor-regioes: #b71c1c;

$cores: $cor-esporte, $cor-vida, $cor-regioes;

@mixin cor-elementos($cor) {
  a:hover, span.data {
    color: $cor
  }
}

@each $cor in $cores {
  section.#{$cor} {
    @include cor-elementos($cor);
  }
}

Porém, na section, ele pega como class, a cor em HEXADECIMAL,e não funciona.
Alguem pode me dar uma luz?

A: Como sugestão de implementação, utilize a função map-get(), exemplo:
$cores: ('cor-esporte' : #1b5e20,  'cor-vida': #f57f17, 'cor-regioes': #b71c1c );
$classes: cor-esporte cor-vida cor-regioes;

@mixin cor-elementos($cor) {
  a:hover, span.data {
    color: map-get($cores, '#{$cor}');
  }
}

@each $classe in $classes {
  section.#{$classe} {
    @include cor-elementos($classe);
  }
}

A: Consegui!!
Pra quem quiser, fica o codigo abaixo. Pode ser que há alguma outra forma de fazer, mas essa que fiz, já serviu para mim!
$cor-regioes: #FFCC00;
$cor-esporte: #CC0000;
$cor-vida: #CCBBCC;

@mixin config-icon-colors($colors...) {
  @each $i in $colors {

      .#{nth($i, 1)}{
        color: nth($i, 2);

        .data {
          color: nth($i, 2);
        }
        a:hover {
          h5 {
            color: nth($i, 2);
          }
        }
      }
   }
}

@include config-icon-colors(
'regioes' $cor-regioes,
'esporte' $cor-esporte,
'vida' $cor-vida);


text:
Q: Using this parent in an if statement jquery Im trying to trigger the click on the parent div only on the parents that have the checkboxes inside them checked. I cant use 'this' because that makes '.choose-plain' trigger a click on it. is there a way to use this for the element in the if statement not the click?
$('.choose-plain').click(function(){
    if ($('.option-other').is(':checked')) {
        $(the parent div of the if statement only if .option-other is checked).trigger( "click" );
    }
});

html/php

Plain

        <?= $form->input('',array('name' => 'data[Pattern][plain]','value' => 1,'class' => 'option_value option-plain', 'type' => 'checkbox',
     'label' => false,'checked' => $pattern==1?'checked':false,'div' => false));?>

Patterned

        <?= $form->input('',array('name' => 'data[Pattern][patterned]','value' => 254,'class' => 'option_value option-other', 'type' => 'checkbox',
     'label' => false,'checked' => $pattern==254?'checked':false,'div' => false));?>

Childrens

        <?= $form->input('',array('name' => 'data[Pattern][childrens]','value' => 64,'class' => 'option_value option-other', 'type' => 'checkbox',
     'label' => false,'checked' => $pattern==64?'checked':false,'div' => false));?>

because the checkboxes are hidden i have to trigger a click on the parent div, which in another part of my jquery triggers the box to check or uncheck.

A: As per your markup you have a invalid markup as you have same IDs applied on multiple divs. IDs should be unique for each element.
You can use this:
$('.choose-plain').click(function(){
     var chcked = $(this).find(':checkbox').prop('checked');
     $('.option-other').prop('checked', !chcked);
});


text:
Q: How to resolve issue with building stream-fusion I'm trying to bring in the stream-fusion library into my project. I am using Stack (LTS 5.16). I added the stream-fusion-0.1.2.5 version to my project's cabal file and also as an extra-dependency in my stack.yaml.
However, when I try to build the project I now get the following:
stream-fusion-0.1.2.5: configure
stream-fusion-0.1.2.5: build

--  While building package stream-fusion-0.1.2.5 using:
      /Users/me/.stack/setup-exe-cache/x86_64-osx/setup-Simple-Cabal-1.22.5.0-ghc-7.10.3 --builddir=.stack-work/dist/x86_64-osx/Cabal-1.22.5.0 build --ghc-options " -ddump-hi -ddump-to-file"
    Process exited with code: ExitFailure 1
    Logs have been written to: /Users/me/Haskell/hqfl/.stack-work/logs/stream-fusion-0.1.2.5.log

    Configuring stream-fusion-0.1.2.5...
    Building stream-fusion-0.1.2.5...
    Preprocessing library stream-fusion-0.1.2.5...
    [1 of 3] Compiling Data.Stream      ( Data/Stream.hs, .stack-work/dist/x86_64-osx/Cabal-1.22.5.0/build/Data/Stream.o )

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Data/Stream.hs:591:5: Warning:
        Pattern match(es) are non-exhaustive
        In an equation for 'next':
            Patterns not matched: (_ :!: (Just (L _))) :!: S2
    [2 of 3] Compiling Data.List.Stream ( Data/List/Stream.hs, .stack-work/dist/x86_64-osx/Cabal-1.22.5.0/build/Data/List/Stream.o )

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Data/List/Stream.hs:235:1: Warning:
        The import of 'seq, Int' from module 'Prelude' is redundant

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Data/List/Stream.hs:1703:10: Warning: Tab character

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Data/List/Stream.hs:2496:1: Warning:
        Rule "genericSplitAt -> fusible" may never fire
          because 'genericSplitAt' might inline first
        Probable fix: add an INLINE[n] or NOINLINE[n] pragma on 'genericSplitAt'

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Data/List/Stream.hs:2504:1: Warning:
        Rule "genericSplitAt -> splitAt/Int" may never fire
          because 'genericSplitAt' might inline first
        Probable fix: add an INLINE[n] or NOINLINE[n] pragma on 'genericSplitAt'

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Data/List/Stream.hs:2516:1: Warning:
        Rule "genericReplicate -> replicate/Int" may never fire
          because 'genericReplicate' might inline first
        Probable fix: add an INLINE[n] or NOINLINE[n] pragma on 'genericReplicate'
    [3 of 3] Compiling Control.Monad.Stream ( Control/Monad/Stream.hs, .stack-work/dist/x86_64-osx/Cabal-1.22.5.0/build/Control/Monad/Stream.o )

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Control/Monad/Stream.hs:136:10:
        Ambiguous occurrence 'MonadPlus'
        It could refer to either 'Control.Monad.Stream.MonadPlus',
                                 defined at Control/Monad/Stream.hs:124:1
                              or 'GHC.Base.MonadPlus',
                                 imported from 'GHC.Base' at Control/Monad/Stream.hs:80:1-15

    /private/var/folders/q_/qbq9bct96jj8p_c9kqbhmt840000gn/T/stack6002/stream-fusion-0.1.2.5/Control/Monad/Stream.hs:140:10:
        Ambiguous occurrence 'MonadPlus'
        It could refer to either 'Control.Monad.Stream.MonadPlus',
                                 defined at Control/Monad/Stream.hs:124:1
                              or 'GHC.Base.MonadPlus',
                                 imported from 'GHC.Base' at Control/Monad/Stream.hs:80:1-15

How can I resolve the ambiguity here?

A: you need to change the following imports in Control.Monad.Stream (line 80)
- import GHC.Base
+ import           GHC.Base hiding ( MonadPlus
+                                 , (=<<)
+                                 , ap
+                                 , join
+                                 , liftM
+                                 , liftM2
+                                 , liftM3
+                                 , liftM4
+                                 , liftM5
+                                 , mapM
+                                 , mplus
+                                 , mzero
+                                 , sequence
+                                 , when
+                                 )

Then it compiles - I don't know wether it will work as expected, this library is quite old (3 years as of now) and the tested-with section in the cabal file says 7.6.1. - I recommend using benchmarks to ensure that the benefits you hope to get from this library are real. I would guess that a lot of the ideas of this library have made it into base by now.
Could you leave a comment after you have done these benchmarks I would really be interested in them.


text:
Q: How to tell if a linear system is consistent So I have a list of equations and have made it into REF which gives me
$$\left[\begin{matrix}1 & -1 & 1 \\ 0 & 1 & -1 \\ 0 & 0 & 0\end{matrix}\middle|\begin{matrix}1 \\ 2k-k^{2} \\ -2k^{2}+k-3\end{matrix}\right]$$
How do I tell what values this is consistent for?
I think it's $k=1$, $k=3/2$ and $k=2$ however, when I put $k=1$ into the system I get the following:
$x-y+z=1$, $y-z=1$ and $0=-4$ the last part of which obviously doesn't make much sense? Some help please!
EDIT:
the original matrix was:
$$\left[\begin{matrix}1 & -1 & 1 \\ 1 & -2 & 2 \\ 2 & -1 & 1\end{matrix}\middle|\begin{matrix}1 \\ (k-1)^{2} \\ -k^{2}+3k-1\end{matrix}\right]$$

A: The system is consistent if $-2k^2 + k - 3 = 0 \iff 2k^2 - k + 3 = 0$, but this equation has no real solution since $\triangle = (-1)^2 - 4\cdot 2\cdot 3 = -23 < 0$, which means it is inconsistent.

A: When is $-2k^2 + k - 3 = 0$?
Answer that, and you'll have the value that makes the system consistent.
If there is no solution (no value of $k$ which makes the entry zero), then the system of equations is never consistent (hence, is inconsistent), whatever $k$ may happen to be.

A: The system is inconsistent if your matrix contains any of this:
$$\begin{bmatrix} 0 & 0 & 0 &| &\text{non-zero number} \end{bmatrix}$$
Thus, we need the right side to be $0$ in order to make the system consistent. Hence, we need $$-2k^2+k+3=0.$$
Solving for $k$, I used the quadratic formula (or you can factor too),
$$k = \frac{-1 \pm \sqrt{(1)^2-4(-2)(3)}}{2(-2)}=\frac{-1 \pm 5}{-4}=-\frac{3}{2},-1$$
We need $k=\boxed{-\frac{3}{2}}$ or $k=\boxed{-1}$ for this system to be consistent.


text:
Q: Heroku app database resetting After running through Getting Started with Python on Heroku, I launched my first app. Everything seems to be working fine, but after a little while (a few hours maybe), the database resets. My hypothesis of the root cause is that my django app is using the default django database (SQLite I think) and Heroku supports postgres by default. I haven't tested this because it seems like quite a lot of work to change my app to postgres and it's something I'd rather not do now if I don't have to.
In summary, my question is, is my database not saving due to my app using SQLite? And if so, why does my app work at all? if not, where is the first place I should look to solve the issue?

A: As stated by @DanielRoseman you should not use SQLite on heroku, because SQLite runs in memory, and backs up its data store in files on disk.
Let me quote from the heroku doku:

SQLite runs in memory, and backs up its data store in files on disk. While this strategy works well for development, Heroku's Cedar stack has an ephemeral filesystem. You can write to it, and you can read from it, but the contents will be cleared periodically. If you were to use SQLite on Heroku, you would lose your entire database at least once every 24 hours.
Even if Heroku's disks were persistent running SQLite would still not be a good fit. Since SQLite does not run as a service, each dyno would run a separate running copy. Each of these copies need their own disk backed store. This would mean that each dyno powering your app would have a different set of data since the disks are not synchronized.
Instead of using SQLite on Heroku you can configure your app to run on Postgres.

It is really easy to use postgres in django. You only have to change the database adapter in your settings file:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mydb',
        'USER': 'myuser',
        'PASSWORD': 'password',
        'HOST': 'localhost',                      # Empty for localhost through domain sockets or           '127.0.0.1' for localhost through TCP.
        'PORT': '',                      # Set to empty string for default.
    }
}

There is also a tutorial on how to setup a django application on herku in their docu section:
https://devcenter.heroku.com/articles/django-app-configuration


text:
Q: Test for paired proportion data I want to test for differences in the connectivity of two different brain regions (A and B) measured in 100 subjects. For each brain region, I have measured connectivity to 150 other brain regions (i.e., for each subject, there are 150 connectivity values for brain region A, and 150 connectivity values for brain region B). Each connectivity value is expressed as a proportion out of the total connectivity measured for brain region A or B (i.e, the 150 connectivity values  sum to a total 100% for region A and B separately).
So my data is 100 (subjects) x 2 (brain regions A and B) x 150 (connectivity to 150 other brain regions).
my questions are:

*

*what would be the most appropriate statistical test of whether the overall connectivity pattern to the 150 brain regions (i.e., the distribution of connectivity values) is different between brain region A and brain region B, noting that (i) each of the 150 connectivity values is measured as a proportion of the total connectivity (so, the 150 connectivity values are not independent), and (ii) the connectivity values for regions A and B are paired (i.e., they are measured from the same subject)? i considered using a one-way repeated-measures multivariate analysis of variance (MANOVA), but i am not sure if this is appropriate given the dependent variables (150 connectivity values) are expressed as proportions.

*assuming the test above shows an overall difference between region A and B, what would be the most appropriate post-hoc test to compare every one of the 150 connectivity values between region A and B? would paired t-tests (performed for each of the 150 connectivity values) be sufficient, or is it inappropriate given that the connectivity values are expressed as proportions out of the total and so aren't independent?


text:
Q: How do I enforce that every single data element in my database schema has a unique name? I've read about a principle that states the following: "Every single data element should have a unique name in your database schema." (http://bytes.com/topic/sql-server/answers/439341-name-keyword) How do you enforce that?
A usual technique consists in placing a three-character abbreviation before the meaningful name of the column. So, Employee.Name becomes Emp_Name. So far, so good. However, Employer.Name should also become Emp_Name. So, I must come up with some cryptic abbreviation for Employer that makes little sense. Let's say, "Eml". And, as the Schema becomes bigger, more and more efforts have to be devoted to avoid collision.
In my opinion, a good compromise would consist in always using sensible prefixes. This way, we avoid MOST of the collisions without using unintuitive abbreviations – like "Eml" for Employer.

A: The requirement that every data element have a unique name should not be interpreted as every column having a unique name.
Foreign keys, in particular, should have the same name based on the table they are referencing.  So, CustomerID would mean the same thing wherever it occurs.  It would be the reference to the primary key to the Customer table.  And I would call the primary key in the table CustomerID, although sometimes I also see it as just ID.
There are some other cases were duplicate names are ok.  All tables I create have metadata on each row, describing when and who created the row.  These are called CreatedAt and CreatedBy respectively.  These are in all tables, but are not part of the logical data model.
Another case of duplicate names that comes to mind is effective and end date on slowly changing dimensions.  It is usually simpler to just call these EffDate and EndDate (or whatever), rather than trying to make them unique.
Finally, I do a lot of processing using data flow methods which involve multiple staging tables.  I very intentionally keep column names the same for tracking purposes.
However, the answer to your question is to use prefixes related to the table.  The data elements unique to that table can have a short prefix so we know what they are.  For instance, Cust_Name and Addr_City are sensible names for the customer name in the customer table and the city name in the address table.


text:
Q: which kind of record this like will get? LIKE ',%,%,'

I am using above like in case statement to get record. But it's not working as expected.
My query is -
SELECT
CASE
        WHEN row_id LIKE ',%,%,'
            THEN 'A'
        WHEN row_id NOT LIKE ',%,%,'
            THEN ''
        END 'AF'
        FROM MyView WHERE row_id = '2464,2465,2466'
ORDER BY 1 DESC

Expected Output - A getting blank.

A: This like:
row_id LIKE ',%,%,'

will match every single row_id that starts and ends with a comma and has at least a comma in between.
Your query, because of the clause
WHERE row_id = '2464,2465,2466'

will always return an empty set because this row_id doesn't match the previous pattern.

A: row_id LIKE ',%,%,' means a string that starts with , and contain a , and ends with ,.
If you mean a string that contains two , or one , then try this:
SELECT
CASE
    WHEN row_id LIKE '%,%,%'
            THEN 'A'
    WHEN row_id NOT LIKE '%,%'
            THEN ''
    END 'AF'
FROM MyView WHERE row_id = '2464,2465,2466'
ORDER BY 1 DESC


text:
Q: No space left on device prevents login It seems that when you run out of disk space all remote logins are prevented [I'm using Red Hat 4.4]. Apparently this is because all non-superuser logins have to write to /var/log/auth.log
This is a common occurence when /var/tmp/cores gets filled due to (user) programs crashing, or a process generating tons of log (under /var/tmp).
What configuration changes can be made to prevent this occurring?
Can + do you:

*

*put /var/tmp on a different filesystem?

*put /var/log on different filesystem?

*enforce a strict separate of filesystems accessible user + system processes?

A: There are several things that you need to do to prevent problems and possibly system crash in the future:

*

*Create separate partitions for /var, /var/log, /tmp and possibly others to help your system survive (hopefully) in case of one partition got filled accidentally.

*Use reasonable logrotate configuration to allow a good amount of logs and not consuming a lot of space. You can also compress the logs to reduce log size.

*Run some monitoring tools to inform you early enough when you are about to exceed some configured threshold such 50% or 75% of your partition(s).

*Fix any buggy software or lower the debug level when applicable and not needed. BTW, lowering debug level will improve performance.


text:
Q: java.net.BindException: bind failed: EACCES (Permission denied) on a rooted device The following code throws "java.net.BindException: bind failed: EACCES (Permission denied)" on a rooted tablet:
 DatagramSocket ds = new DatagramSocket(67);

I thought binding to privileged port 67 was allowed on a rooted device.  Could anyone shed some light on this?

A: Just because a device is "rooted", that does not give permission to arbitrary apps to do anything they want with root privileges.  Rooted devices merely allow arbitrary apps to request to use the su command line to execute new processes with root privileges via a command line.
See this, for example.


text:
Q: How to display list of friends with its corresponding profile picture using Facebook API php sdk? I was able to get the list of friends but not their respective profile picture.
Sample output: == LIST OF FRIENDS ==
Total friends: 927.
//Dislay friends here but no profile picture.
<?php
  $friends = $facebook->api('/me/friends');

  echo "=== LIST OF FRIENDS ===";
  echo "
";

  $total_friends = count($friends['data']);

  echo 'Total friends: '.$total_friends.'.
';
  $start = 0;
  echo '
';
  while ($start < $total_friends) {
    echo $friends['data'][$start]['name'];
?>

<?php
  echo $value["data"][$start]['name'];
?>

<?php
    echo '
';
    $start++;
  }
?>

A: You can get friends image directly in IMG tag as


text:
Q: scrollbar in firefox and opera I have a little issue related to scrollbars. The question is that I have a set of boxes within a container. All the content is fixed the max width of the container and once the number of elements within the container grow, the overflow-y property start working.
In Firefox and opera, (i do not know in IE) the width of the scrollbar come up and destroy my layout passing from three columns to two.
Here i have the code: http://jsfiddle.net/domoindal/ChkRg/
If you run it in Chrome and Safari, it works fine due to the scroll bar appear over the content but in Firefox and Opera don't.
Is there any way i could avoid this effect in the quoted browsers?
Thanks.

A: I think I understand you issue, though I'm surprised it works in Chrome since it doesn't work for me. (using Chrome too)
My first thought to increase the width, so the scrollbar'll have enough space.
You can detect with javascript if the content grew too high, then resize.