How to use a background with rims and colored areas in Android

Question: I would like to have a layout in which I put other layouts (e.g. constrained layout) and those layouts should have rims and colored areas. So I guess I have to change the background but I do not know how. Here is a screenshot of my current fragment and I highlited the things that I would like to add:

Basically it should look somehow similar to Desired layout.
Here is the XML-layout file that I have
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_marginTop="@dimen/_28sdp"
        android:layout_width="@dimen/_220sdp"
        android:layout_height="@dimen/_240sdp"
        android:orientation="vertical"

        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.93"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintVertical_bias="0.75">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/_30sdp"
            android:orientation="horizontal"></LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/_190sdp"
            android:orientation="vertical"></LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/_20sdp"
            android:orientation="horizontal"></LinearLayout>
    </LinearLayout>

    <Button
        android:id="@+id/navigation_button_language"
        android:layout_width="@dimen/_31sdp"
        android:layout_height="@dimen/_31sdp"
        android:background="@drawable/navigation_buttom"
        android:text="Dummy"
        android:textAllCaps="false"
        android:textColor="#121212"
        android:textSize="@dimen/_9ssp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.95"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.02" />

    <TextView
        android:id="@+id/textView_language"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/_3ssp"
        android:text="Dummy"
        android:textColor="#121212"
        android:textSize="@dimen/_9ssp"
        app:layout_constraintEnd_toEndOf="@+id/navigation_button_language"
        app:layout_constraintStart_toStartOf="@+id/navigation_button_language"
        app:layout_constraintTop_toBottomOf="@+id/navigation_button_language" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="0dp"
        android:layout_height="@dimen/_240sdp"
        app:layout_constraintBottom_toBottomOf="@+id/linearLayout"
        app:layout_constraintEnd_toStartOf="@+id/linearLayout"
        android:layout_marginLeft="@dimen/_6sdp"
        android:layout_marginRight="@dimen/_6sdp"
        android:background="@color/colorGrey"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/linearLayout"
        app:layout_constraintVertical_bias="0.447">

        <ScrollView
            android:layout_width="47dp"
            android:layout_height="44dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" />
        </ScrollView>

        <TextView
            android:id="@+id/textView_Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Test Name"
            android:textColor="#000000"
            android:textSize="@dimen/_14ssp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_QuantityText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/_1sdp"
            android:text="Quantity: "
            android:textSize="@dimen/_9ssp"

            app:layout_constraintEnd_toEndOf="@+id/textView_Name"
            app:layout_constraintStart_toStartOf="@+id/textView_Name"
            app:layout_constraintTop_toBottomOf="@+id/textView_Name" />

        <TextView
            android:id="@+id/textView_QuantityNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2"
            android:textSize="@dimen/_9ssp"
            app:layout_constraintBottom_toBottomOf="@+id/textView_QuantityText"
            app:layout_constraintStart_toEndOf="@+id/textView_QuantityText"
            app:layout_constraintTop_toTopOf="@+id/textView_QuantityText" />

        <TextView
            android:id="@+id/textView_TableNumberText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/_1sdp"
            android:text="Table: "
            android:textSize="@dimen/_9ssp"
            app:layout_constraintEnd_toEndOf="@+id/textView_QuantityText"
            app:layout_constraintStart_toStartOf="@+id/textView_QuantityText"
            app:layout_constraintTop_toBottomOf="@+id/textView_QuantityText" />

        <TextView
            android:id="@+id/textView_TableNumberValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="3"
            android:textSize="@dimen/_9ssp"
            app:layout_constraintBottom_toBottomOf="@+id/textView_TableNumberText"
            app:layout_constraintStart_toEndOf="@+id/textView_TableNumberText"
            app:layout_constraintTop_toTopOf="@+id/textView_TableNumberText" />

        <ImageButton
            android:id="@+id/imageButton_message"
            android:layout_width="@dimen/_25sdp"
            android:layout_height="@dimen/_25sdp"
            android:layout_marginTop="8dp"
            android:background="@drawable/ic_baseline_markunread_24"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.221"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView_TableNumberText" />

        <ImageButton
            android:id="@+id/imageButton_video"
            android:layout_width="@dimen/_25sdp"
            android:layout_height="@dimen/_25sdp"
            android:background="@drawable/ic_baseline_videocam_24"
            app:layout_constraintBottom_toBottomOf="@+id/imageButton_message"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.827"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="@+id/imageButton_message" />

        <TextView
            android:id="@+id/textView_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/_1sdp"
            android:text="Message"
            app:layout_constraintEnd_toEndOf="@+id/imageButton_message"
            app:layout_constraintStart_toStartOf="@+id/imageButton_message"
            app:layout_constraintTop_toBottomOf="@+id/imageButton_message" />

        <TextView
            android:id="@+id/textView_Video"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Video"
            android:layout_marginTop="@dimen/_1sdp"
            app:layout_constraintEnd_toEndOf="@+id/imageButton_video"
            app:layout_constraintStart_toStartOf="@+id/imageButton_video"
            app:layout_constraintTop_toBottomOf="@+id/imageButton_video" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Any idea how I can do that? I'd highly appreciate every comment and would be thankful for your help.
Reminder: Does nobody have any idea how I can do that? I have seen such layouts quite often so it should not be extremely unsual what I want to do.
Comment: You want to change the background color of that specific area where your constraint layout and it's items are being shown?
Comment: Thanks Kamal for your comment. Basically there are 2 tasks. 1) Add a rim to the constrained layout (the grey area) as can be seen in the posted link of the desired layout. 2) Change the background color of the yellow highlighted area in my screenshot.
Comment: @KamalNayan: Thanks Kamal for your comment. Any comments to my last comment? I'd highly apprciate every further comment from you.
Comment: For rim you can use padding .. in constraint layout and use a background colour according to your need ... This will make your rim
Comment: I have posted the answer. Kindly have a look.
Answer: Answer:
Make a drawable -> rim.xml
    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
     <stroke
        android:width="@dimen/space_lg"
        android:height="@dimen/space_lg"
        android:color="@color/#fff"
        android:dashGap="@dimen/space_sm" />

</shape>

and in the layout just use:
 android:background="@drawable/rim"

Comment: Just add a constraint layout before the staring of existing constraint layout (means wrap the old constraint with new constraint layout ).
Comment: Thanks a lot Kamal for your answer and effort. Basically my desired layout link was just to show you how my layout should look like. I did not want to build exactly the same. Because of this I still really do not know how to implement the rim and the painted areas in my layout. I use the padding as you said but this does not create a rim. Also, you are using 2 CardViews. Why are you using them? For the colored areas?
Comment: Why do you use a cardView inside a ScrollView? Bascially the scrollView should not contain colored areas. What I basically wanted is just to add a rim to my layout and insert colored areas.
Comment: CardView is inside  constraint layout. And because in your expected layout I could see the elevation so I used CardView to get the desired output
Comment: Thanks Kamal for your answer and effort. I really appreciate it. Can I also do this without CardView? Because basically I just want to have the colored areas and not a CardView. Further, how can I create the rims? In your layout I also don't see the rims as in the desired layout. You said that I can use padding. I tried this but it did not create a rim.
Comment: And basically I have to admit that I do not understand your XML layout file at all. What do you put into the CardViews? Just some textViews into the first CardView, right? Why do you do this? And why is the CardView inside a ScrollView? I do not want the colored areas to be scrolled.
Comment: I tried to adopt your layout with the CardViews into mine but I could not manage to do it as the CardView created many errors. So is there not an easier solution to just color the areas? Maybe just have a colored area and not a CardView? The items do not have to be in a CardView (and to be totally honest, I do not see any advantages when having the items inside the CardView).
Comment: Thanks Kamal for your answer. Are you still intending to update your answer and if not do you have any comments on my last comments? I'd highly appreciate any further comment or update from you.
Comment: Yes, I have updated the answer, and by rim what I understand is a border. If not then I have posted a second layout without a border so you can pick what you need both layouts are without CardView. And sorry for the delay my exams were going on so it took more time. And feel free to ask if you need any alterations in the layout.
Comment: Thanks a lot Kamal for your answer and effort. I really appreciate it. I still see no rim in your solution. With rim I mean something like a colored frame around the whole layout. On this link (https://image.winudf.com/v2/image1/Y29tLmFwcHRpc3Quc21hcnRwb3Nfc2NyZWVuXzJfMTU0MjAwMTExMF8wNjE/screen-2.jpg?fakeurl=1&type=.jpg) you can see a colored (grey/black) rim that servers as a frame around the layout. I do not see this in your solution. Do you know how I can include it?
Comment: I have updated the answer now it's having the rim . Let me know if you need some help.
Comment: Thanks a lot Kamal for your answer and effort. I really appreciate it. I have problems adopting your layout to my posted XML code? So what I want is to paint the area in my XML code (see Screenshot) with a color. You use a constraintLayout for painting right? I also tried to insert a constraintLayout as an additional element and painted it but the imageViews and textViews were overpainted by that. How can I adjust my XML layout to have these colored areas?
Comment: Futher, I still do not understand how you inserted the rim? As far as I understand you use 2 ConstrainedLayouts within each other. I also tried to do this in my XML code but this was quite messy.  I could not manage to choose the right layout widths and heights and constraines for the outer ConstrainedLayout (that I newly added) such that it looked good. Do you have any advice how to do this?
Comment: Without having a look at the code I can't suggest...... you can use other layouts if you have a problem using Constraint Layout.
Comment: Thanks for your answer Kamal. Basically my code has been posted above in my question (the XML-layout file).
Comment: You can use Any layout instead of a constraint layout. The main approach is that you make a layout and give it a padding and set its background color (what you want to be of rim) and then inside that you again define a layout and in this, you define all your views like textview or something else.
Comment: Thanks Kamal for your answer and effort. I really appreciate it.  What you describe with any layout is how to make the rim, right? What about the colored areas? How is the basic approach there? Should I also use layouts within layouts to do this? Is there any alternative solution because I have problems with nesting layouts in each other. I use a ConstrainedLayout. Is there no element such that I can just define a colored area without using nested layouts?
Comment: I think this is the only way (having nested layout) to achieve rim as far as I know. If you find my answer helpful then kindly mark it as the correct answer and upvote it if possible so that it can help some needy in the future.
Comment: Thanks for your answer Kamal. I really appreciate it. Is there another way of making these colored areas instead of using nested layouts? Is there no such thing that can be inserted into the layout that just puts a color into the layout without using nested layouts?
Comment: Can make a drawable and will set it as the background of layout.... Will update the answer today using this method.
Comment: I have updated the answer , Kindly have a look.
Comment: Thanks Kamal for your answer and update. I really appreciate it. When using your suggested code I get 4 error messges in the XML layout file: "Cannot resolve symbol '@dimen/space_lg' ", "Cannot resolve symbol '@dimen/space_lg'", "The resource name must begin with a character" and "Cannot resolve symbol '@dimen/space_sm'"
Comment: These are dimensions , and you are getting error because you have not defined that.... Just replace that with the values you want. For example : android:width= 8dp and same for other attributes.
Comment: On top of that I am still wondering whether there is a solution for my second question about  creating colored areas within a layout without using a separate nested layout. Can I just add some elemnt inside a layout that paints a desired area? In your previous suggested solution you used nested layouts just for the purpose of creating colored areas and I am wondering whether there is also a solution without using additional nested layouts only for the coloring?
Comment: Thanks Kamal for your answer and effort. I really appreciate it. Regarding your rim solution: How can I fill the inside of the area with a certain color? So far the inside of your suggested layout element is just white while I can adjust the rim color.
Comment: You can use attribute android:background= "YOUR DESIRED COLOR". And this will give you the output as you want.
Comment: Thanks for your answer and effort Kamal. I really appreciate it. Where exactly do I have to insert `android:background= "@color/colorGrey"`? When I put it into the constrained Layout I get a duplication error (as I have already defined the rim.xml as the background). When putting it inside the rim.xml file I do not get an error but the color is not shown at all. I tried to put the attribute both inside the stroke tags and inside the shape tags. But it did not help. The background remains white.
Comment: Here you can see the code `

`
Comment: Got you point ... if you want to have another background then you need to have a nested layout and set the background of inside layout.
Comment: Thanks for your answer Kamal and your effort. I think that basically if I want to have a rim and colored areas there is no solution without nested backgrounds. So I guess I have to use this. Thanks for your tremendous help. I accepted and upvoted your answer.
Comment: Thanks @VanessaF Glad to help you.
Comment: Hi Kamal. It's me again. I had a look at your suggested code and solution and tried to use it. Unfortunately I have to admit that I don't like the solution at all. The big problem is that not only I can't change the background of the constraineyLayout when using your suggested code but also when the parent layout changes it's background, the background of the constrainedView also changes. So I can't have different background colors for the two layouts. Any solution for that problem?
Comment: If you don't know a solution for that problem of your suggested code with the rim.xml I would like to ask you
what is the easiest way of adding another contrainedLayout as a parent to an already existing constrainedLayout without having to implement everything from the beginning?
Comment: Thanks Kamal for your great help. Now I got it.
Answer: drawable -> rim.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF"/>
    <stroke
        android:width="3dp"
        android:color="#0FECFF"/>
</shape>

Then, following your desired layout (in the picture), I made a simplified corresponding layout:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/outerConstraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.35" />

    <View
        android:id="@+id/v_left_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="8dp"
        android:background="@drawable/rim"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@id/guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="Left Side"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background"
        app:layout_constraintTop_toTopOf="@id/v_left_background" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ll_navbar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@android:color/holo_green_dark"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background"
        app:layout_constraintTop_toBottomOf="@id/textView_Name">

        <ImageView
            android:id="@+id/iv_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_delete"
            app:layout_constraintEnd_toStartOf="@id/iv_2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:tint="@android:color/white" />

        <ImageView
            android:id="@+id/iv_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_delete"
            app:layout_constraintEnd_toStartOf="@id/iv_3"
            app:layout_constraintStart_toEndOf="@id/iv_1"
            app:layout_constraintTop_toTopOf="parent"
            app:tint="@android:color/white" />

        <ImageView
            android:id="@+id/iv_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_delete"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/iv_2"
            app:layout_constraintTop_toTopOf="parent"
            app:tint="@android:color/white" />

        <TextView
            android:id="@+id/tv_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Order sheet"
            android:textAlignment="center"
            android:textColor="#fff"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="@id/iv_1"
            app:layout_constraintStart_toStartOf="@id/iv_1"
            app:layout_constraintTop_toBottomOf="@id/iv_1" />

        <TextView
            android:id="@+id/tv_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Order"
            android:textAlignment="center"
            android:textColor="#fff"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="@id/iv_2"
            app:layout_constraintStart_toStartOf="@id/iv_2"
            app:layout_constraintTop_toBottomOf="@id/iv_2" />

        <TextView
            android:id="@+id/tv_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Arrange products"
            android:textAlignment="center"
            android:textColor="#fff"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="@id/iv_3"
            app:layout_constraintStart_toStartOf="@id/iv_3"
            app:layout_constraintTop_toBottomOf="@id/iv_3" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        app:layout_constraintBottom_toTopOf="@id/button_okay"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background"
        app:layout_constraintTop_toBottomOf="@id/ll_navbar" />

    <Button
        android:id="@+id/button_okay"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@android:color/holo_green_light"
        android:text="Okay"
        android:textAllCaps="false"
        android:textColor="#fff"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="@id/v_left_background"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background" />

    <View
        android:id="@+id/v_right_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/rim"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/guideline"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

The screen then looks somewhat like this:

Constraint-wise:

(You can check the previews in the xml's design tab, I hope the constraints in the code are verbose enough for you to be able to follow)
UPDATE
Code without guideline:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/outerConstraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <View
        android:id="@+id/v_left_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginEnd="8dp"
        android:background="@drawable/rim"
        app:layout_constraintHeight_percent="0.8"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent="0.35" />

    <TextView
        android:id="@+id/textView_Name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="Left Side"
        android:textAlignment="center"
        android:textColor="#000000"
        android:textSize="16sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background"
        app:layout_constraintTop_toTopOf="@id/v_left_background" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ll_navbar"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@android:color/holo_green_dark"
        android:orientation="horizontal"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background"
        app:layout_constraintTop_toBottomOf="@id/textView_Name">

        <ImageView
            android:id="@+id/iv_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_delete"
            app:layout_constraintEnd_toStartOf="@id/iv_2"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:tint="@android:color/white" />

        <ImageView
            android:id="@+id/iv_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_delete"
            app:layout_constraintEnd_toStartOf="@id/iv_3"
            app:layout_constraintStart_toEndOf="@id/iv_1"
            app:layout_constraintTop_toTopOf="parent"
            app:tint="@android:color/white" />

        <ImageView
            android:id="@+id/iv_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_delete"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@id/iv_2"
            app:layout_constraintTop_toTopOf="parent"
            app:tint="@android:color/white" />

        <TextView
            android:id="@+id/tv_1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Order sheet"
            android:textAlignment="center"
            android:textColor="#fff"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="@id/iv_1"
            app:layout_constraintStart_toStartOf="@id/iv_1"
            app:layout_constraintTop_toBottomOf="@id/iv_1" />

        <TextView
            android:id="@+id/tv_2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Order"
            android:textAlignment="center"
            android:textColor="#fff"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="@id/iv_2"
            app:layout_constraintStart_toStartOf="@id/iv_2"
            app:layout_constraintTop_toBottomOf="@id/iv_2" />

        <TextView
            android:id="@+id/tv_3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="Arrange products"
            android:textAlignment="center"
            android:textColor="#fff"
            android:textSize="12sp"
            app:layout_constraintEnd_toEndOf="@id/iv_3"
            app:layout_constraintStart_toStartOf="@id/iv_3"
            app:layout_constraintTop_toBottomOf="@id/iv_3" />
    </androidx.constraintlayout.widget.ConstraintLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_margin="8dp"
        app:layout_constraintBottom_toTopOf="@id/button_okay"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background"
        app:layout_constraintTop_toBottomOf="@id/ll_navbar" />

    <Button
        android:id="@+id/button_okay"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:background="@android:color/holo_green_light"
        android:text="Okay"
        android:textAllCaps="false"
        android:textColor="#fff"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="@id/v_left_background"
        app:layout_constraintEnd_toEndOf="@id/v_left_background"
        app:layout_constraintStart_toStartOf="@id/v_left_background" />

    <View
        android:id="@+id/v_right_background"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/rim"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHeight_percent="1"
        app:layout_constraintStart_toEndOf="@id/v_left_background"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintWidth_percent="0.6" />

</androidx.constraintlayout.widget.ConstraintLayout>

Comment: Thanks for your answer Dat Pham Tat. Can you just directly use pecentages for the two layouts instead of the guidlines (which makes it more complex) like `android:layout_width="0dp"  android:layout_height="0dp"  app:layout_constraintWidth_percent="0.5"  app:layout_constraintHeight_percent="0.15"`?
Comment: Thanks for your answer. Any comments on my last comment? I'd highly appreciate every further comment from you.


Programando para Android com múltiplas telas

Question: Quando programo para Android, penso na portabilidade com os mais diversos dispositivos do mercado. Vendo o layout da minha Activity principal, notei que em dispositivos com tela pequena (fiz o teste com tela de 2 polegadas) as views são ENORMES e em dispositivos com tela grande (fiz o teste com tela de 10 polegadas) as views são MINIATURAS.
Como eu conserto tudo isso? Quando eu escrevia códigos HTML, utilizava no CSS a unidade % para a resolução do problema.
Comment: Da uma estudada no Fragments ;)
http://blog.caelum.com.br/layouts-mais-simples-com-android-fragments/
Comment: Como está a definir o tamanho das *views*? Poste um exemplo de um *layout*.
Comment: @Gabriel, alguma solução?
Answer: Olá,
Você precisa tomar cuidado com tamanhos de tela desde o início do desenvolvimento, pois retroagir nesse sentido é ainda mais trabalhoso.
A maneira correta de lidar com isso é usando múltiplos resources para cada configuração de tela.
Observe o que diz a documentação a respeito disso:

Using configuration qualifiers
Android supports several configuration qualifiers that allow you to
  control how the system selects your alternative resources based on the
  characteristics of the current device screen. A configuration
  qualifier is a string that you can append to a resource directory in
  your Android project and specifies the configuration for which the
  resources inside are designed.
To use a configuration qualifier:
Create a new directory in your project's res/ directory and name it
  using the format: -  is the
  standard resource name (such as drawable or layout).  is a
  configuration qualifier from table 1, below, specifying the screen
  configuration for which these resources are to be used (such as hdpi
  or xlarge). You can use more than one  at a time—simply
  separate each qualifier with a dash. Save the appropriate
  configuration-specific resources in this new directory. The resource
  files must be named exactly the same as the default resource files.
  For example, xlarge is a configuration qualifier for extra-large
  screens. When you append this string to a resource directory name
  (such as layout-xlarge), it indicates to the system that these
  resources are to be used on devices that have an extra-large screen.

Ou seja, você terá que ter dentro do seu projeto pastas dentro de resources específicas para cada configuração de tela seguindo o padrão <resources_name>-<qualifier>.
Algo semelhante a isso:

Para mais informações acesse o link abaixo. Ele contém toda informação necessária a respeito deste tema.
http://developer.android.com/guide/practices/screens_support.html
Espero ter ajudado.
Abraço.
Answer: Gabriel
Temos algumas maneiras disponíveis para realizar essa manipulação de layouts em diferentes dispositivos.
Drawable
Disponibiliza os seguintes tamanhos

ldpi (low) ~120dpi
mdpi (medium) ~160dpi
hdpi (high) ~240dpi
xhdpi (extra-high) ~320dpi
xxhdpi (extra-extra-high) ~480dpi
xxxhdpi(extra-extra-extra-high) ~640dpi

Com isso cada arquivo dentro dessas pastas ira tratar um diferente tamanho de tela.
Dimens.xml
Esse xml que deve estar em res/values/dimens.xml nos possibilita realizar customizações tais como:

Tamanho das views
Tamanho de fontes
Espaços entre margens (vide xml exemplo abaixo)
Entre outros.
 <resources>

    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>

 </resources>

Nota: Resumidamente SP para tipografia e DP para todo o resto.
Fragments
Temos desde a versão 3.0 HoneyComb  o uso de Fragments para a criação e layouts dinâmicos, pensando nos diversos tamanhos de tela que existem atualmente(Tablets e celulares com telas diferentes).
Nota: Você pode utilizar a biblioteca de suporte para versões inferiores, cuidado na hora do import deve ser:
android.support.v4.app.Fragment

A imagem acima demonstra os fragments em ação, por exemplo nos tablets a tela pode exibir por completo seu layout, quando você clicar em algum item da lista, sera carregado ao lado sem precisar mudar a iteração das telas, na figura do lado direito temos o uso dos fragments em dispositivos com telas menores onde temos fragment A que ao ser clicado direciona para o fragment B, C ou quantos forem necessários para montar sua tela.
Exemplo para inflar seu fragment retirado da documentação
public static class ExampleFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.example_fragment, container, false);
    }
}

Para inflar os Fragments precisamos dar um Override no metodo onCreateView e retornar a view inflada, porém nada impede de usar também o método OnCreatesó precisa ficar atento ao ciclo de vida do Fragment.
Ciclo de vida dos Fragments
onAttach(activity) - Esse método é chamado logo depois de o fragment ser associado com a activity
onCreate(bundle) - Esse método é chamado apenas uam vez e quando o fragment está sendo criado. Ele ira receber o Bundle que foi salvo durante o método onSaveInstanceState(state)
onCreateView(inflater, viewgroup,bundle) - Nesse método, o fragment precisa criar a view que será inserida no layout da activity>
onActivityCreated(bundle) - Esse método é chamado logo após o onCreate() da activity ter sido finalizado.
onDestroyView() - Esse método é chamado quando a view do fragment foi removida e não pertence mais ao fragment.
onDestroy() - Chamado para indicar que o fragment não está mais sendo utilizado.
OnDetach() - Oposto do método onAttach(activity).
Comment: A resposta citando fragments vai ao encontro da preocupação do AP, mas ele também dá a entender que o tamanho das views deveria ser proporcional à dimensão física da tela, e isso pode ser obtido independente do uso de fragments. Vide a outra resposta.
Comment: @Piovezan concordo com você, existe as duas possibilidades, qual abordagem você acha mais efetiva? trabalhar com todos os drawable ou ir direto para o uso dos fragments?
Comment: Primeiro acho que falta o autor da pergunta esclarecer o que quer exatamente. O que eu acho que falta complementar na resposta é que além dos drawable é possível definir dimensões diversas (tamanho das views, dos espaços entre elas, das fontes, etc.) conforme o tamanho da tela (em `res/values/dimens.xml`), dimensões essas que devem ser definidas em `dp` ou `sp` conforme o caso.
Comment: @Piovezan, dei uma complementada, se ele aparecer e explicar um pouco mais eu poderia deixar muito melhor a resposta.


How to stop escaping field name in smarty?

Question: My code is -
{html_checkboxes name=ms_fields['company_type'] options=$comp_type separator='
'}

Which is generating -
<input type="checkbox" name="ms_fields[\'company_type\'][]" value="0">

How can i get the name be - name="ms_fields['company_type'][]"?
If it is ok then no problem. New to smarty, so little confused. Thank you.
Answer: Put the value for argument name into quotes:
{html_checkboxes name="ms_fields['company_type']" options=$comp_type separator='
'}

Even better, also remove the apostrophes; you don't need them and they make difficult getting the values from $_POST[] on the script that processes the form:
{html_checkboxes name="ms_fields[company_type]" options=$comp_type separator='
'}

Comment: WHat about setting the `id` with the values of that array?


VirtualBox bridged adapter can ping but can't curl

Question: There is a dedicated server running Ubuntu Server 12.04.2. There are 4 useable IPs for this server: A, B, C, D. The server itself takes A.
The server is now running two VirtualBox guests, both with "Bridged adapter" network type. One guest is running Windows Server 2003, using IP address B. Another one is running Arch Linux (Live CD), using IP address C.

In the Ubuntu host, the network is fine. I can apt-get and the downloading speed is good.
In Windows guest, I can ping www.google.com in cmd.exe, but I cannot visit www.google.com in IE6.
In Arch Linux guest, I can ping www.google.com in zsh, but curl -v www.google.com does not work. I can also telnet www.google.com 80, which means at least 80/tcp and 53/udp ports are working. (There is no iptables firewall on the server, actually.)
In Arch Linux guest, I can even ssh to another machine! (using standard 22/tcp )
In Arch Linux guest, I try to wget some https site, it stuck at "Connecting to XXX.XXX.XXX.XXX:443... connected".

I've tried changing --nictype1 setting for the VM and/or setting different MTUs in the guest OS, but the problem continues.
Can anyone help me?
Addtional information: When changing "Bridged adapter" to "NAT", the guest OS can curl www.google.com. Everything is fine. But since I need public IP, I have to use "Bridged adapter" for guest OS.
Addtional informationi 2: In guest OS with "Bridged adapter", I can ssh other host using 22/tcp, I can dig some domain using 53/udp, but I cannot wget or curl websites using 80/tcp or 443/tcp, but telnet www.google.com 80 or telnet www.google.com 443 is fine. When using "NAT" , everything is fine.
Comment: Are you behind a transparent proxy or something like this ?
Comment: @Bertera No, I figured out why... See my own answer below.
Comment: @MichaelHampton This is not a production environment, so I do not think there is anything wrong with VirtualBox...
Answer: Well, I figured out this by myself.
I by accident found that I can curl google.com but cannot curl www.google.com and since the first one is rather smaller, I think this is a problem with MTU or something, causing the guest OS being unable to transfer large segment of data.
After googling "virtual bridged mtu" I found this post: https://forums.virtualbox.org/viewtopic.php?f=7&t=30632&start=0
Then I tried ethtool -K eth2 sg off rx off tx off tso off in the Ubuntu Server (eth2 is the bridged interface), and... it works like a charm! Instantly
Comment: Of the 4 settings that tries to change, two are successful, but the other two return errors for: `Cannot change scatter-gather` and `Cannot change tcp-segmentation-offload`.  So the problem persists.
Comment: Wow, I would not have made the connection to the MTU being the problem. Good thinking!
Answer: I have encountered the same problem.
the default MTU of bridged nic in vm is 1500. but when I use the ping with DF flag to detect the actual MTU, it turn out to be the 1498.
So, this problem could be solved by typing sudo ifconfig eth0 mtu 1498 in my host.


Position: Sticky CSS ou JS

Question: Olá,
Seguindo exatamente o exemplo abaixo, alguém pode me ajudar a trabalhar o position:sticky
Hoje, a próxima data está se posicionando em cima da data atual.
Desta forma, a opacidade e a sombra da data está ficando em 100%, gerando uma visão grotesca, caso haja muitas datas.
Eu quero que a data anterior, suba com o scroll e dê lugar para a próxima data.
Se eu adicionar a data e os dialogos em um container, dá certo, porém, preciso trabalhar com o que tenho abaixo.
O que tenho até agora está totalmente em CSS, mas devido a dificuldade de manter em CSS, precisarei incluir JavaScript, porém não consegui chegar no resultado esperado
fiddle

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title></title>
    <meta name="description" content="sticky">
    <meta name="viewport" content="width=device-width">

05/03/2019

Olá

Oi, tudo bem ?

06/03/2019

Tudo bem!

e voce ?

Tudo bem tambem

preciso de ajuda

Voce pode me ajudar

07/03/2019

Talvez sim

O que voce precisa

Como posso utilizar o position:sticky ?

Deixe-me ver

Acho que posso te ajudar

Certo

Comment: Já que não pode colocar cada data e os diálogos separados por containers, pq não coloca a sombra e a transparência só na primeira data ?
Comment: Não pode simplesmente remover a transparência das datas? Porque `position: sticky` funciona assim, vão todas parar nos `10px` que você indicou e dá para ver as de trás conforme empilham.
Comment: Eu até poderia tirar a opacidade, mas e a sombra? Eu teria que tirar também..
Comment: Essas respostas sugerem que não há possibilidade? Nem usando JavaScript se for o caso?
Answer: Fiz um modelo, não sei se vai ficar do seu gosto...
O que eu fiz foi transformar o box da data em um pseudo-elemento after, e tb criei um pseudo-elemento before para usar como mascara da data que está abaixo.
Basicamente o que eu tenho é um before que vai encobrir completamente o que estiver abaixo. Funciona bem com cores sólidas (e.g #ddd), e com imagem fica relativamente bom tb, vc vai precisar usar um background-attachment: fixed; e a mesma imagem como background do .chat e desse pseudo-elemento ::before da data

Segue o código relativo a imagem acima

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}

* {
    margin: 0px;
    padding: 0px;
}

.chat {
    overflow: auto;
    border: solid 1px black;
    position: fixed;
    left: 50%;
    top: 50%;
    background-color: #e5ddd5;
    z-index: 100;
    height: 500px;
    margin-top: -200px;
    width: 500px;
    margin-left: -300px;
}

.box {
    width: 300px;
    margin: 30px auto;
    padding: 20px;
    text-align: center;
    font-weight: 400;
    color: black;
    font-family: arial;
    position: relative;
    border-radius: 20px;
}

.box.enviado {
    background: #dcf8c6;
}

.box.recebido {
    background: white;
}

.recebido:before {
    content: "";
    width: 0px;
    height: 0px;
    position: absolute;
    border-left: 10px solid white;
    border-right: 10px solid transparent;
    border-top: 10px solid white;
    border-bottom: 10px solid transparent;
    left: 19px;
    bottom: -19px;
}

.enviado:before {
    content: "";
    width: 0px;
    height: 0px;
    position: absolute;
    border-left: 10px solid transparent;
    border-right: 10px solid #dcf8c6;
    border-top: 10px solid #dcf8c6;
    border-bottom: 10px solid transparent;
    right: 19px;
    bottom: -19px;
}

.data {
    color: rgba(69, 90, 100, 0.95)!important;
    margin-bottom: 8px!important;
    margin-top: 8px!important;
    margin-right: auto!important;
    margin-left: auto!important;
    padding: 5px 12px 6px 12px!important;
    max-width: 75px;
    z-index: 2;
}
.data::after {
    content: "";
    background-color: rgba(225, 245, 254, 0.92);
    padding: 5px 12px 6px 12px!important;
    border-radius: 7.5px!important;
    box-shadow: 0 1px 0.5px rgba(0, 0, 0, 0.13)!important;
    text-shadow: 0 1px 0 rgba(255, 255, 255, 0.4)!important;
    width: 75px;
    opacity: 0.8;
    z-index: -1;
    top: 0%;
    height: 50%;
    left: 0;
    position: absolute;
    z-index: -1;
}

.data {
    top: 10px;
    position: sticky;
}

.data::before {
    content: "";
    width: 483px;
    height: 38px;
    background-color: #e5ddd5;
    top: -10px;
    left: -192px;
    display: block;
    position: absolute;
    z-index: -2;
}
.data:not(:first-child)::before {
    top: 0px;
    height: 28px;
}

.chat,
.data::before {
    background-image: url(https://66.media.tumblr.com/31a78c6e15775efdc87861661736adf2/tumblr_inline_mkjkugRR1f1qz4rgp.gif);
    background-position: top center;
    background-attachment: fixed;
}

05/03/2019

Olá

Oi, tudo bem ?

06/03/2019

Tudo bem!

e voce ?

Tudo bem tambem

preciso de ajuda

Voce pode me ajudar

07/03/2019

Talvez sim

O que voce precisa

Como posso utilizar o position:sticky ?

Deixe-me ver

Acho que posso te ajudar

Certo

Comment: apreciaria se não houver um tipo de cabeçalho para a data, onde o diálogo some no scroll, mas talvez seja essa a solução, visto que, possivelmente será necessário o uso de javascript, onde eu até tentei, mas ainda não consegui o resultado esperado.
Comment: @WagnerFilho não tenho conhecimento de JS para te ajudar nessa parte. Mas com CSS acredito que não tenha jeito de fazer exatamente como vc quer, qualquer solução que aparece vai ser um "jeitinho" como a proposta que fiz. Algo simples seria deixar a sombra só na primeira data, assim as subsequentes vão meio que utilizar sem pre uma sombra só referente a a do primeiro elemento de data. Ou então vc vai ter que bolar um jeito de colocar um container por dia com a data e os textos dentro, algo que parece que vc não gostaria de fazer... Se tiver alguma dúvida sobre a resposta é só perguntar []´s
Comment: ... @WagnerFilho e outra coisa que vc pode fazer é tentar dar outro acabamento nessa solução para deixar ela mais bonitinha sem esse corte seco. Talvez algo como nessa imagem http://prntscr.com/mv27io ou alguma outra coisa do tipo
Comment: Entendi.. neste caso, há possibilidade de adicionar uma classe a data anterior ? Assim que uma nova data assumir o seu lugar
Comment: @WagnerFilho com js acredito que sim, quando a próxima data chegar no top 30 por exemplo, vc remove a data que estiver com top 10. Mas isso só com js ou jQuery, com CSS puro vc não consegue trocar classe no evento de scroll. Como falei eu não entendo muito de js e não consigo te ajudar com js, mas com CSS acredito não ter opção muito melhor que essa, ate Pq ninguém nem tentou responder... Uma pena

Position: Sticky CSS ou JS


How can I comfortably design a Linux based terminal application from my Windows laptop?

Question: I have a Centos 6.4 (minimal) system configured like a "NAS drive."
I would like to design a Linux based terminal application on my Window laptop, then build/run it from my "NAS Drive."  It is annoying to keep switching to Putty, running the build script then testing the program itself!
The source code is stored/edited over a Samba share so everything's already in the right place.
Is there a c++ editor for Windows that can build/run the application with the touch of a button (F9)?  Or a batch script or something for Windows that automates a series of SSH commands?
Comment: This maybe? It is a sort of virtual linux environment http://www.cygwin.com/
Comment: I probably entirely misunderstood your question, but you know putty can [run remote ssh scripts](http://stackoverflow.com/questions/12736683/scripting-over-ssh-through-putty-on-windows), right?
Comment: I want Putty to automatically log in to my account (I understand and accept the sercurity risks) then automatically run a series of commands.
Comment: Did you consider installing Linux on your laptop ? Then, use your laptop's Linux system to develop your Linux application!
Comment: I prefer Windows for both normal computer usage and a developing environment.
Answer: If I was in your shoes, I'd use eclipse with cdt and cygwin.
Comment: I tried eclipse, the interface looks messy and when trying to setup the remote application build via SSH, it only lets me use my Windows username.
Comment: Well, I've used UltraEdit (http://www.ultraedit.com) for this sort of thing before too - more light weight, but not free.  You can program your own "F9" pretty easy.  You'll still need to solve your ssh issue:  it takes a -l argument to set the user name (the one with cygwin I mean).  Good luck with your project!


Huge citadel log files

Question: I noticed today that my mysql server was not starting up anymore. Checking the error logs, it showed that it didn't have enough disk space. I thought that's really weird since there's nothing on my server that could possibly take up 30GB. After digging around I observed my citadel logs are taking up a massive 22GB of space in the <code>/var/lib/citadel/data/</code> directory:

This is split in lots of smaller (still big) log files:

Why is this happening and how can I prevent it in the future?
EDIT: Here's a sanitized sample of one of the log files:
Comment: Are they text logs or database logs?
Comment: Not sure. They contain some human-readable text (looks like config changes, some emails, etc) but also contain some non-human-readable stuff.
Comment: Can you post a sanitized snipped of one of the logs?
Comment: I have now posted a sample above.
Answer: They're database logs.  Citadel has functionality to delete them.  Just turn on automatic log pruning and the logs that are committed to the database will go away.

Huge citadel log files


What are Bayesian p-values?

Question: I'm looking for an answer that would satisfy a reader who understands frequentist p-values but only understands the rudiments of Bayesian approaches to statistics.
At present google searches do not reveal a definition either on a Wikipedia page or any other commonly accepted resource.
This question seems related but isn't really since it transpired that the user was not actually calculating Bayesian p-values. However, the accepted answer links to this Gelman paper in explanation of what Bayesian p-values are.
Comment: This Gelman [paper](https://projecteuclid.org/download/pdfview_1/euclid.ejs/1382448225) may also be of interest.
Comment: And [this related question](http://stats.stackexchange.com/questions/148649/how-to-respond-to-reviewers-asking-for-p-values-in-bayesian-multilevel-model)
Answer: If I understand it correctly, then a Bayesian p-value is the comparison of a some metric calculated from your observed data with the same metric calculated from your simulated data (being generated with parameters drawn from the posterior distribution).
In Gelmans words: "From a Bayesian context, a posterior p-value is
the probability, given the data, that a future observation
is more extreme (as measured by some test variable)
than the data"
For example, the number of zeros generated from a poisson based model could be such a metric or test statistic, and you could calculate how many of your simulated datasets have a larger fraction of zeros than you actually observe in your real data. The closer this value to 0.5, the better the values calculated from your simulated data distribute around the real observation.
Answer: Bayesian p-values are normally used when one would like to check how a model fits the data. That is, given a model $M$ we wish to examine how well it fits the observed data $x_{obs}$ based on a statistic $T$, which measures the goodness of fit of data and model. For this, suppose we have a model $M$ with probability density function $f(x|\theta)$ and with prior $g(\theta)$. Then, one can define the prior predictive p-value or tail area under the predictive distribution through the expression
$$ p = P(T(x)\geq T(x_{obs})|M) = \int_{T(x)\geq T(x_{obs})}h(x)dx, $$
where
$$h(x)dx = \int f(x|\theta)g(\theta)d\theta$$
is the prior predictive density.
Notice that this approach may be influenced by the choice of the prior (for an example, see pg.180 of [1]). For this reason, the posterior predictive p-value was introduced. Now, consider that the prior  depends on the observed data $g(\theta|x_{obs})$, thus,
$$ h(x|x_{obs}) = \int f(x|\theta)g(\theta|x_{obs})d\theta. $$
However, this approach presents two disadvantages. First, we're considering a double use of the data (for the definiton of $h(x)$ and $p$). Second, for larger sample sizes, the posterior distribution of $\theta$ concentrates at the Maximum Likelihood Estimate of $\theta$ (the frequentist or classical approach).
To overcome this, the conditional predictive distribution was introduced. Consider a statistic $U$ that does not involve the statistic $T$. Then, the conditional predictive p-value is
$$ p_{c} = P^{h(\cdot|u_{obs})}(T(x)\geq T(x_{obs})|M) = \int_{T(x)\geq T(x_{obs})} h(t|u_{obs}) dt, $$
where $h(t|u_{obs})$ is the conditional predictive density of $T$ given $U$ and $u_{obs}$ is $U(x_{obs})$.
Additionally, one could consider the partial posterior predictive p-value with the advantage of not requiring a choice for the statistic $U$, see pg.184 of [1] for more details.
[1] Ghosh, Jayanta; Delampady, Mohan; Samanta, Tapas. An Introduction to Bayesian Analysis:Theory and Methods. Springer, 2006.

What are Bayesian p-values?


Permitir acesso ao FileSystem API do Chrome com Selenium usando Python

Question: Preciso de uma ajudinha aqui! Preciso de configurar o selenium usando o webdrive para clicar em uma janela pop-up do Chrome. Já tentei várias alternativas que achei, mas nenhuma funciona. Uma política de segurança da empresa restringe algumas configurações, mas o download automático é possível ser feito, mas o download automático é executado somente depois de clicar em Permito (Permitir). O Chrome pergunta "Armazenar arquivos neste dispositivo", com as opções Permitir ou Bloquear. Conforme imagem.

Esse foi o código utilizado:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

option = Options()
option.add_argument("--disable-infobars")
option.add_argument("start-maximized")
option.add_argument('--ignore-certificate-errors')
option.add_argument("--disable-extensions")
option.add_argument('--disable-download-notification')
option.add_experimental_option("useAutomationExtension", False)
option.add_experimental_option("prefs", {
                "safebrowsing.enabled": True,
                "profile.default_content_setting_values.notifications": 1,
                "profile.default_content_setting_values.geolocation": 1})

wd = webdriver.Chrome(chrome_options=option, executable_path='C:\\Users\\Documents\\webdriver\\chromedriver.exe')
wd.get('http://websiteintranet.com.br')

Answer: Isto é uma medida de segurança Chrome quando um website tenta utilizar o Chrome FileSystem API.
Caso tenhas plena confiança no website que estás a aceder, podes fazer bypass a esse pop-up ao iniciar o chrome com a flag --unlimited-storage
option.add_argument("--unlimited-storage")

Comment: funcionou, era exatamente isso!!! Obrigado


Create a rule at the event of "Cron maintenance tasks are performed"?

Question: I created a rule to be fired when "Cron maintenance tasks are performed".
Now I need an action to check delete all nodes of the content type: "Question" that have the field "Delete" set to "yes"
How can I do this?
Answer: you could use hook_cron_queue_info to create a task that sits in a queue and happens on a timer. This would account for the potentially long duration of the task you mention.


Conduit with aeson / attoparsec, how to exit cleanly without exception once source has no more data

Question: I'm using aeson / attoparsec and conduit / conduit-http connected by conduit-attoparsec to parse JSON data from a file / webserver. My problem is that my pipeline always throws this exception...
ParseError {errorContexts = ["demandInput"], errorMessage = "not enough bytes", errorPosition = 1:1}

...once the socket closes or we hit EOF. Parsing and passing on the resulting data structures through the pipeline etc. works just fine, but it always ends with the sinkParser throwing this exception. I invoke it like this...
j <- CA.sinkParser json

...inside of my conduit that parses ByteStrings into my message structures.
How can I have it just exit the pipeline cleanly once there is no more data (no more top-level expressions)? Is there any decent way to detect / distinguish this exception without having to look at error strings?
Thanks!
EDIT: Example:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import Control.Applicative
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as B8
import qualified Data.Conduit.Attoparsec as CA
import Data.Aeson
import Data.Conduit
import Data.Conduit.Binary
import Control.Monad.IO.Class

data MyMessage = MyMessage String deriving (Show)

parseMessage :: (MonadIO m, MonadResource m) => Conduit B.ByteString m B.ByteString
parseMessage = do
    j <- CA.sinkParser json
    let msg = fromJSON j :: Result MyMessage
    yield $ case msg of
        Success r -> B8.pack $ show r
        Error   s -> error s
    parseMessage

main :: IO ()
main =
    runResourceT $ do
        sourceFile "./input.json" $$ parseMessage =$ sinkFile "./out.txt"

instance FromJSON MyMessage where
    parseJSON j =
        case j of
        (Object o) -> MyMessage <$> o .: "text"
        _          -> fail $ "Expected Object - " ++ show j

Sample input (input.json):
{"text":"abc"}
{"text":"123"}

Outputs:
out: ParseError {errorContexts = ["demandInput"], errorMessage = "not enough bytes", errorPosition = 3:1}

and out.txt:
MyMessage "abc"MyMessage "123"

Answer: This is a perfect use case for conduitParserEither:
parseMessage :: (MonadIO m, MonadResource m) => Conduit B.ByteString m B.ByteString
parseMessage =
    CA.conduitParserEither json =$= awaitForever go
  where
    go (Left s) = error $ show s
    go (Right (_, msg)) = yield $ B8.pack $ show msg ++ "\n"

If you're on FP Haskell Center, you can clone my solution into the IDE.
Comment: Maybe I just have a misconception about attoparsec here, but even if I have a nice way to handle this exception, how can I correctly interpret it? In my case there is no actual error, everything is perfectly fine and I'd just like to stop parsing. But this error looks like it might also appear when the data is corrupt and the json data just ends in the middle. Does every attoparsec conduit end with an exception, and I just have to look at the error strings in the exception to figure out if it's an actual error or simply EOF?
Comment: The error message is accurate. What it's doing is parsing the first two snippets of JSON correctly, and for the third finding that there's no data available and therefore saying that there's a parse error. You may want to look at the implementation of conduitParserEither, which explicitly checks for EOF.
Comment: Ok, thank you for the clarification! I think I'll go with your suggestion and use conduitParserEither to detect the "demandInput" error and re-throw everything else for the actual error handling code upstream.


SQL Server 2008 intermitent error 40 running parallel queries

Question: Here's our setup :
We are using Red Gate SQL Multi-Script to run queries on our ~1000 databases which reside on a single SQL Server 2008. SQL Multi Script can be configured to run queries in parallel on multiple databases at the same time, which speeds up the execution on this number of databases. We want to run queries as fast as possible so we made the Multi Script to run 25 parallel connections (maximum allowed by Multi Script). SQL Multi Script runs on a desktop computer (Windows 7), and connects to SQL Server 2008 with "sa" login directly via its hostname (myserver.mycompany.com). Our SQL Server 2008 is not a named instance, so we don't reference it with \instancename.
Here's the issue :
We are sometimes getting the following error for a few databases in the 1000, for the same query, same server, same databases, same parallelism (running the same thing again and again, sometimes leads to few errors, sometimes not) :

"Msg 1214, Level 20, State 0, Line 0 A network-related or
  instance-specific error occurred while establishing a connection to
  SQL Server. The server was not found or was not accessible. Verify
  that the instance name is correct and that SQL Server is configured to
  allow remote connections. (provider: Named Pipes Provider, error: 40 -
  Could not open a connection to SQL Server)"

One more thing, if we lower the number of parallel connections in Multi Script, those errors seems to disappear, but because we want to have maximum performance from it, we would like to top the number of maximum parallel connections.
I also found this thread on Red Gate forum, but that doesn't help much
UPDATE:
I changed settings in the connection properties to use only TCP/IP, and what I get now is a different error:

"Msg 10048, Level 20, State 0, Line 0
  A network-related or instance-specific error occurred while
  establishing a connection to SQL Server. The server was not found or
  was not accessible. Verify that the instance name is correct and that
  SQL Server is configured to allow remote connections. (provider: TCP
  Provider, error: 0 - Only one usage of each socket address
  (protocol/network address/port) is normally permitted.)"

Anyone having ideas why that happens ?
Answer: I would try using TCP/IP only and not Named Pipes.
Comment: How do you do that ?
Comment: Probably depends on the application, and if it is using the default SQL client or the SQL Native Client.  Typically when an application establishes a connection, there is some configuration that specifies to use TCP/IP or Named Pipes.  It may also be attempting an IP connection, and trying Named Pipes if it fails.  Have you tried running this on a server operating system?  I would definitely try that before wasting more time on it.
Comment: I updated my question to include the new error when using TCP/IP only connection.
Comment: Time to run a packet capture.


Matrix Multiplication of $(AB) (CD)$

Question: For Matrix Multiplication of $(AB) (CD)$ with dimension of $A_{30\times 10}, B_{10\times 40}, C_{40\times 50}, D_{50\times 30}$, what is the number of multiplications we need for $(AB) (CD)$?
For $(AB)$, we need $30\times10\times40=12000$ multiplications.
For $(CD)$, we need $40\times50\times30=60000$ multiplications.
Question: the solution stops and said that the number of multiplications of $(AB) (CD)$ would be 72000, but I guess it should be
For $(AB)$, we need $30\times10\times40=12000$ multiplications.
For $(CD)$, we need $40\times50\times30=60000$ multiplications.
For $(AB)(CD)$, we need $30\times40\times30=36000$ multiplications.
And that the number of multiplications of $(AB) (CD)$ would be $12000+60000+36000=108000$, is not that right?
Comment: What if you do $A(BC)D?$
Comment: I think it's 30 x 40 x 30 for your last calculation
Comment: @Avra $30 \times 40 \times 30 = 36,000$
Comment: @IgorRivin. Thank you. It's 80000 and the shape of matrix is $30\times 30$, which is same as their solution.
Answer: Well, that depends.
Since matrix multiplication is associative, you can get different results.
In your example, there are few different ways of doing the multuplication:

$((A\times B)\times(C\times D))$:
$A\times B$ costs $30\cdot 10\cdot 40=12,000$ multiplications and results in a matrix $E_{30\times 40}$
$C\times D$ costs $40\cdot 50\cdot 30=60,000$ multiplications and results in a matrix $F_{40\times 30}$
$E\times F$ costs $30\cdot 40\cdot 30=36,000$ multiplications and results in a matrix $G_{30\times 30}$
so the total cost is $108,000$ multiplications

$(((A\times B)\times C)\times D)$:
$A\times B$ costs $30\cdot 10\cdot 40=12,000$ multiplications and results in a matrix $E_{30\times 40}$
$E\times C$ costs $30\cdot 40\cdot 50=60,000$ multiplications and results in a matrix $F_{30\times 50}$
$F\times D$ costs $30\cdot 50\cdot 30=45,000$ multiplications and results in a matrix $F_{30\times 30}$
so the total cost is $117,000$ multiplications

$(A\times (B\times (C\times D)))$:
$C\times D$ costs $40\cdot 50\cdot 30=60,000$ multiplications and results in a matrix $E_{40\times 30}$
$B\times E$ costs $10\cdot 40\cdot 30=12,000$ multiplications and results in a matrix $F_{10\times 30}$
$A\times F$ costs $30\cdot 10\cdot 30=9,000$ multiplications and results in a matrix $F_{30\times 30}$
so the total cost is $81,000$ multiplications

There are also $((A \times (B \times C)) \times D)$ and $(A \times ((B \times C) \times D)$
Comment: Thank you. So the solution source mentioned in my question is wrong then.

Matrix Multiplication of $(AB) (CD)$


What's stopping auditd from logging writes by Syslog when watching a Syslog file?

Question: We've recently started using auditd on one of our Ubuntu servers.
The example audit.rules file we were given has a rule like this:
-w /var/log/syslog -p wra -k logs

However, when syslog writes to the file, nothing gets logged by auditd. Similarly, if I go to the command line and run the logger command, the syslog file gets written without generating an audit log. If I alter the file directly by using an editor or appending a line to it from the command line, it does get logged.
Of course, I don't want an audit log every time syslog gets written, but I'm interested to know what causes this to happen and if there are any other cases besides syslog where this could be happening without my knowledge.
Thank you very much!
Additional info:
Test audit.rules file:
-D
-b 8192
-f 1
-w /var/log/syslog -p wra -k logs

Output of auditctl -l and augenrules --check:
# auditctl -l
-w /var/log/syslog -p rwa -k logs

# augenrules --check
/sbin/augenrules: Rules have changed and should be updated

Using logger:
# logger "logger example"
# ausearch -k logs
----
time->Fri Mar 10 14:35:20 2017
type=CONFIG_CHANGE msg=audit(1489156520.983:4463): auid=4294967295 ses=4294967295 op="add_rule" key="logs" list=4 res=1

Using echo and output redirect:
# echo "echo example" >> /var/log/syslog
# ausearch -k logs
----
time->Fri Mar 10 14:35:20 2017
type=CONFIG_CHANGE msg=audit(1489156520.983:4463): auid=4294967295 ses=4294967295 op="add_rule" key="logs" list=4 res=1
----
time->Fri Mar 10 14:36:52 2017
type=PROCTITLE msg=audit(1489156612.334:4465): proctitle="bash"
type=PATH msg=audit(1489156612.334:4465): item=1 name="/var/log/syslog" inode=417506 dev=08:01 mode=0100640 ouid=104 ogid=4 rdev=00:00 nametype=NORMAL
type=PATH msg=audit(1489156612.334:4465): item=0 name="/var/log/" inode=411799 dev=08:01 mode=040775 ouid=0 ogid=108 rdev=00:00 nametype=PARENT
type=CWD msg=audit(1489156612.334:4465):  cwd="/etc/audit"
type=SYSCALL msg=audit(1489156612.334:4465): arch=c000003e syscall=2 success=yes exit=3 a0=a93108 a1=441 a2=1b6 a3=7ffe24385b98 items=2 ppid=28462 pid=28463 auid=4294967295 uid=0 gid=0 euid=0 suid=0 fsuid=0 egid=0 sgid=0 fsgid=0 tty=pts18 ses=4294967295 comm="bash" exe="/bin/bash" key="logs"

Tail of /var/log/syslog:
# tail -n 2 /var/log/syslog
Mar 10 14:36:40 testserver root: logger example
echo example

Answer: I've understood the reason behind this behavior.
The auditctl man page for the -p flag states:

Describe  the  permission access type that a file system watch will
  trigger on. r=read, w=write, x=execute, a=attribute change. These
  permissions are not the standard file permissions, but rather the kind
  of syscall that would do this kind of thing. The read & write syscalls
  are omitted from this set since they would overwhelm  the  logs.  But
  rather  for  reads  or writes, the open flags are looked at to see
  what permission was requested.

I didn't understand what this meant at the time, but after a couple of hours digging into the linux-audit mailing list, I've come to realize this means that if you watch a file for writing, it doesn't log when there's a syscall for writing to the file. It just logs if a file was accessed with write permissions by checking for open syscalls with the O_RDWR or O_WRONLY flags.
So, when I use the logger command, I'm actually asking my Syslog daemon to write to the file for me. The syslog daemon always has that file open for writing, therefore it makes sense that nothing gets logged.
If I restart the Syslog daemon, I get something like this on my audit logs:
# ausearch -i -k logs
----
type=PROCTITLE msg=audit(10-03-2017 16:16:59.128:4613) : proctitle=/usr/sbin/rsyslogd -n
type=PATH msg=audit(10-03-2017 16:16:59.128:4613) : item=1 name=/var/log/syslog inode=417506 dev=08:01 mode=file,640 ouid=syslog ogid=adm rdev=00:00 nametype=NORMAL
type=PATH msg=audit(10-03-2017 16:16:59.128:4613) : item=0 name=/var/log/ inode=411799 dev=08:01 mode=dir,775 ouid=root ogid=syslog rdev=00:00 nametype=PARENT
type=CWD msg=audit(10-03-2017 16:16:59.128:4613) :  cwd=/
type=SYSCALL msg=audit(10-03-2017 16:16:59.128:4613) : arch=x86_64 syscall=open success=yes exit=6 a0=0x7f5848003fb0 a1=O_WRONLY|O_CREAT|O_NOCTTY|O_APPEND|O_CLOEXEC a2=0640 a3=0x7f5848000088 items=2 ppid=1 pid=10638 auid=unset uid=syslog gid=syslog euid=syslog suid=syslog fsuid=syslog egid=syslog sgid=syslog fsgid=syslog tty=(none) ses=unset comm=rs:main Q:Reg exe=/usr/sbin/rsyslogd key=logs

Answer: You can start by checking whether the rule is currently active by looking for it in the output of sudo auditctl -l.
If auditd was set to make the ruleset immutable (e.g. your /etc/audit/audit.rules contains -e 2), then only a reboot would make new rules active.
If the rule is visible, do you get anything if you run sudo ausearch -k logs? Also, what do you get if you run sudo augenrules --check?
As you say, logging every write to the /var/log/syslog (or /var/log/messages) could get a little noisy, so you might consider excluding root and/or whichever user is used for unprivileged syslog components. Once it works.
Comment: The rule is currently active according to `auditctl -l`. The ruleset is currently not immutable. I don't get any logs if I use logger, but I do get logs if I edit the file directly. I wanted to know why this is the case. I've edited my question to provide further information.


Can a player decline advantage after a foul?

Question: In association football, after a foul, the referee lets play continue but the team benefiting from the advantage immediately stop playing anyway, either because they would rather have a free kick or because they knew it was a foul and anticipated. This happened to me as a ref.
Does the referee award the initial free kick, or are players not allowed to decline advantage given by the referee?
Answer: The players have no say in it and the referee is the sole judge of whether to play advantage or not.
The referee needs to decide in each instance whether the team who has been fouled will get more out of a free kick or if play continues.
You will rarely see advantage given in a team's defending half as taking a free kick is of greater value to get the ball up the other end of the pitch. Likewise, you rarely see advantage played on fouls around the penalty area (unless there is an immediate opportunity for a shot on goal) as a team would rather setup for a free kick and have their specialist take it.
Answer: The other answers quote the relevant section of the Laws. It's not entirely clear from the Laws that advantage is a discretionary decision, but the following from IFAB's practical guidelines [pdf] clarifies that this is the case:

The referee may play advantage whenever an offence occurs but should
  consider the following in deciding whether to apply the advantage or stop play:

the severity of the offence – if the offence warrants a sending-off, the referee
  must stop play and send off the player unless there is a clear opportunity to
  score a goal
the position where the offence was committed - the closer to the opponent's
  goal, the more effective the advantage can be
the chances of an immediate, promising attack
the atmosphere of the match

In your specific example, you need to simply decide whether, during the period you were attempting to play advantage, the team ends up in a better position than they would have been if the free kick had been given. Once this benefit occurs there is no going back to the free kick, regardless of whatever happens next.
For example, if a foul occurs near halfway and the ball ends up say 20 metres up field in the possession of a teammate of the fouled player, who has a promising attacking opportunity, they can't simply leave the ball and expect to get the free kick - the anticipated advantage has already ensued.
If however, the ball ends up with a player who might be able to do something with it, but at no point do they end up with a better opportunity than the free kick would have provided (i.e. a benefit), if they choose not to play the ball, they're effectively forcing your hand into giving the free kick (which you should go with and simply award).
It can be very difficult in these situations to avoid double-dipping - where a team ends up in a better position than the free kick, makes a mistake, then attempt to con the referee into giving the original free kick. This should be avoided where possible by not looking for advantages that are never going to occur, or by failing to signal early enough when the advantage actually ensues.
Answer: Advantage can only be attained if it benefits the non-offending team.
In the case where a foul is made by Team A and the players of Team B have a chance to develop play, if Team B were to stop playing the ball (or in the extreme cases, kick it directly out or to an opponent on Team A) an aware referee will not claim this to be advantage given, and award the free kick.
Answer: Law 5 of the Laws of the Game: The Referee: 3. Powers and duties clearly favors the non-offending team:

Advantage allows play to continue when an offence occurs and the
  non-offending team will benefit from the advantage and penalises the
  offence if the anticipated advantage does not ensue at that time or
  within a few seconds.

So, if the non-offending team can't benefit from the advantage no matter why within a few seconds, then the referee should penalise the offence.


General exponential family distribution $p(s_1,s_2, x_1,x_2)$, with $s_1,s_2$ binary and $x_1,x_2$ Guassian?

Question: Let $s_1,s_2,x_1,x_2$ be 4 random variables, where $s_1,s_2\in\{-1,1\}$ are binary, while $x_1,x_2 \in \mathbb R$ are continuous. I want to find the most general form of the distribution $p(s_1,s_2,x_1,x_2)$, subject to the following constrains:

$p(s_1,s_2,x_1,x_2)$ belongs to the exponential family
The marginal $p(x_1,x_2)$ is a bivariate gaussian.
Answer: Well, write the joint density as
$$
  p(s_1,s_2,x_1,x_2) = p(x_1,x_2 \mid s_1,s_2) \cdot p(s_1,s_2) \\
 = p(x_1,x_2 \mid s_1,s_2) \cdot p(s_2 \mid s_1) \cdot p(s_1)
$$
Then the first factor is bivariate normal, conditional on the two discrete variables, multiplied by the point probabilities of the discrete variable.
For the discrete variables you could use two binomial distributions (as indicated in the last term above) or maybe a multinomial distribution over the four possible combinations.  Taking logarithms in the equation above you can put this into exponential family form.
Depending on your aims, other factorization could be possible, but the above seems the most natural for most purposes.
Comment: Why the first factor is a bivariate normal? Note that I want $p(x_1,x_2)$ to be normal. I did not require that $p(x_1,x_2|s_1,s_2)$ was normal. In fact, using the form you give, $\sum_{s_1,s_2} P(s_1,s_2,x_1,x_2)$ is *not* normal in general.
Comment: Then maybe you want to factorize the other way round, conditioning the discrete variables on the continuous ones? Maybe you should better state your real modeling problem.
Comment: @becko - the fact that it's not normal in general, while the factorization is mathematically correct no matter what form $p(.)$ takes, should tell you something about the answer.   I strongly suspect there is no solution for which $(x_1, x_2)$ are not independent of $(s_1, s_2)$.  A little work with characteristic functions might confirm this...


"this parameter is set to zero because it is redundant" - SPSS Ordinal Regression output

Question: My question has been asked here but I was none the wiser with the short answer given -
Generalized Linear Model on SPSS with the 'error': "set to zero because this parameter is redundant"
This "parameter is set to zero because it is redundant" is appearing on the output and is always the last of all my my factors (e.g. job position 1-6, it says it for the 6th one, region of work 1-3, it says it for the 3rd). I have tried switching the numbers around, so work 3 becomes work 1, but then work 2 (now 3) says "parameter is set to zero because it is redundant".
Any help as to what I can do would be really appreciated. I have looked on a lot of different internet pages to no avail. Simple explanations really appreciated.
Many thanks.
Comment: Have you seen this one: https://stats.stackexchange.com/questions/291337/interpretation-estimates-of-fixed-effects-redundant-parameters/291340#291340 ?
Comment: This tutorial explains why in dummy variables interaction, estimates for one variable levels are set to zero and regarded redundant: [link](https://stats.idre.ucla.edu/spss/seminars/introduction-to-regression-with-spss/introreg-lesson3/#s5)
Comment: You've written a comment, not an answer. Answers would actually be full explanation, with examples and possibly even code. Links are for comments.
Answer: Suspicion
From your story, I assume you have dummy-coded job positions like this:
<code>PersonID   Job1   Job2   Job3   ...
1          0      1      0      ...
2          1      0      0      ...
..         ..     ..     ..     ...
100        1      0      0      ...
</code>
Description
In a normal regression model, you will have the intercept of your regression equation. For mathematical reasons, your regression can only come up with coefficients, when all variables in the data present add 'unique' information. Else you will suffer from perfect multicollinearity, in your case there is a special name for it: the dummy trap.
I'll discuss briefly: The regression includes an intercept, usually called $\beta_0$. If you also include a dummy variable for every job position, the predicted outcome for every person will be
$\hat{y} = \beta_0 + \beta_1D_{job1} + \beta_2D_{job2} + \beta_3D_{job3}$
So you have three groups of people in your data (job1, job2 and job3), one job per person.

For a given person in job1, the $\hat{y} = \beta_{0} + \beta_1\cdot
   1$
For a given person in job2, the $\hat{y} = \beta_{0} + \beta_2\cdot
   1$
For a given person in job3, the $\hat{y} = \beta_{0} + \beta_3\cdot
   1$

The problem is that the regression will not be able to separate the magnitude of $\beta_0$ from the other coefficients. SPSS lets you know this error occurred by means of the error message you see. It automatically cancels one of your variables (see option 2 below).
Solution
There are two options that will solve this problem (option 1 is easiest):

Run a regression without an intercept

To fit the model without an intercept, one needs to use Analyze > Regression > Linear, click Options (after specifying the model), and then uncheck the Include constant in equation box.

Remove the variable that indicates job3 (or job2 or job1). $\beta_{0}$ will now be the coefficient for the job you removed (say we remove job1). The other coefficients change their interpretation in the sense that they represent the difference between job1's coefficient and their own coefficient.
Comment: I'm calculating the logit manually and I also have this message in SPSS. So are you guys saying that in my manual calculation it should be `0 * Gender` since SPSS says `0b`?


removing all white spaces for lines starting with a pattern

Question: I need to remove all the white spaces for lines which starting with a pattern in a file.
I don't want to loop through lines. Is there any simple and quick solution?
For example
Input file:
<id xxx>dafd</id>
<r>31,31, 31</r>
<r> 0, 0,0 </r>

The output file need to be
<id xxx>dafd</id>
<r>31,31,31</r>
<r>0,0,0</r>

Answer: Like this?:
echo "<id xxx>dafd</id>
<r>31,31, 31</r>
<r> 0, 0,0 </r>" | sed -r '/<r>/s/ //g;'
<id xxx>dafd</id>
<r>31,31,31</r>
<r>0,0,0</r>

Explanation:

sed -r : use extended regular expresions
/<r>/ : Lines matching
s/ //g; : Substitute blanks with nothing, globally.
Comment: That's exactly what I am looking for. Thanks.
Answer: Hi you can do it by the below script. First create a file like mytream.sh and add below lines and change the permission of the file and execute:-
vi mytream.sh

now add below lines:-
#!/bin/bash

file_to_tream="yourfilename"
sed '/<r>/s/ //g' $file_to_tream > tmp.txt
mv tmp.txt $file_to_tream

Or if you do it for any file, just change your script like below and provide the file name in command prompt
#!/bin/bash

sed '/<r>/s/ //g' $1 > tmp.txt
mv tmp.txt $1

Now run it like
chmod 777 mytream.sh
./mytream.sh yourfileName

Hope this will help you.
Comment: Thanks. similar with previous solution, however both solved the problem


FFMPEG trim video resulting not moving videos and black video with audio

Question: I tried to trim my video based on start and end time with the following code:
ffmpeg -ss 02:06:30.500 -to 02:06:32.417 -i movie.mp4 -c copy output.mp4
The output video is not moving video and some of them are black videos with audio. What should I do?
enter image description here
What should I do?
Comment: I'm voting to close this question because , as explained by the ffmpeg tag: Only questions about programmatic use of the FFmpeg libraries, API, or tools are on topic. Questions about interactive use of the command line tool should be asked on https://superuser.com/ or https://video.stackexchange.com/. Please delete this.
Answer: Try using this command :
ffmpeg -ss 02:06:30 -to 02:06:32 -i movie.mp4 -c copy output.mp4
Comment: It gives me the same result, black video with audio
Comment: in which software you are using this command ?


UITableView Cell Accessories changing when returning to table from another TableView (via NavController)

Question: I hope somebody can assist me.
I have navigation controller for several tableviewcontrollers. One of the tableviews ('anchors table') has cells having accessory views (switches and sliders).
The 'anchors table' loads fine, however when I push a new viewController onto the stack, and then go back to the 'anchors table', some of the cell which previously did not have accessory views now have a switch or slider.
In the viewDidLoad method for the anchorsViewController, I set the instance variables for the switches and sliders = nil. Here is my cellForRowAtIndexPath method:
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell...
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [dictionary objectForKey:@"Anchors"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;

// Create UI Elements only once by checking to see if
// one of them is nil
if (displayAnchorsSwitch == nil) {

    // Display Anchors
    if (indexPath.section == 0) {
        NSLog(@"Creating displayAnchorsSwitch");
        self.displayAnchorsSwitch = [[[UISwitch alloc]
                initWithFrame:CGRectZero]autorelease];
        self.displayAnchorsSwitch.on = NO;
        cell.accessoryView = self.displayAnchorsSwitch;

        [self.displayAnchorsSwitch addTarget:self
                action:@selector(switchDisplayAnchors:)
                forControlEvents:UIControlEventValueChanged];
    }
}

if (anchorsLineWidthSlider == nil) {
    // Line Width
    if (indexPath.section == 1 && indexPath.row == 0) {
        NSLog(@"Creating anchorsLineWidthSlider");
        self.anchorsLineWidthSlider = [[[UISlider alloc]
                initWithFrame:CGRectMake(0.0, 0.0, 200.0, 0.0)]autorelease];
        self.anchorsLineWidthSlider.continuous = YES;
        self.anchorsLineWidthSlider.value = 0.25;
        cell.accessoryView = self.anchorsLineWidthSlider;

        [self.anchorsLineWidthSlider addTarget:self
                action:@selector(sliderAnchorsLineWidth:)
                forControlEvents:UIControlEventValueChanged];
    }
}

// Line Opacity
if (indexPath.section == 1 && indexPath.row == 1) {
    if (anchorsLineOpacitySlider == nil) {
        NSLog(@"Creating anchorsLineOpacitySlider");
        self.anchorsLineOpacitySlider = [[[UISlider alloc]
                                          initWithFrame:CGRectMake(0.0, 0.0, 200.0, 0.0)]autorelease];
        self.anchorsLineOpacitySlider.continuous = YES;
        self.anchorsLineOpacitySlider.value =0.75;
        cell.accessoryView = self.anchorsLineOpacitySlider;

        [self.anchorsLineOpacitySlider addTarget:self
                                          action:@selector(sliderAnchorsLineOpacity:)
                                forControlEvents:UIControlEventValueChanged];
        cell.accessoryType = UITableViewCellAccessoryNone;

    }

}

if (indexPath.section == 1 && indexPath.row == 2) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

if (indexPath.section == 1 && indexPath.row == 3) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

if (anchorsFillSwitch == nil) {
    // Display Fill
    if (indexPath.section == 2 && indexPath.row == 0) {
        NSLog(@"Creating anchorsFillSwitch");
        self.anchorsFillSwitch = [[[UISwitch alloc]
                initWithFrame:CGRectZero]autorelease];
        self.anchorsFillSwitch.on = YES;
        cell.accessoryView = self.anchorsFillSwitch;

        [self.anchorsFillSwitch addTarget:self
                action:@selector(switchAnchorsFill:)
                forControlEvents:UIControlEventValueChanged];
    }
}

if (indexPath.section == 2 && indexPath.row == 1) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

if (indexPath.section == 2 && indexPath.row == 2) {
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}

return cell;
</code>
}
Comment: Did you try to `-reloadData` in the `-viewWillAppear:animated:` method on your anchors table?
Answer: First of all, TableView uses the reusable cells(as in ur case,you can use new cells also but it not a good practice.) that means, if you have a cell with text written as "hello" and is ready for reusable then the text remains until you clear that message before reusing them.. so In your code before reusing any new cell just clear its accessoryType.
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
 cell.accessoryType = UITableViewCellAccessoryNone;
//then process your code....before reusing any cell just clear all it components.
</code>
Answer: The issue here is likely of cell reuse. Accessory Views take precedence over Accessory Types. So when the Cell is reused, you aren't nil-ing the Accessory View in cases where Accessory Types need to be displayed.
There is also a problem with how you set the accessory view for the section 0. Once the displayAnchorsSwitch is initialized, the code won't be called again. So only a single row in section 0 will have the switch and rest won't (based on the code). It won't be called if the same row (one with the switch) goes off screen and comes back on after the cell has been reused.


Find the largest value

Question:
Find the largest value of:
  $$\sqrt{x_1-1}+\sqrt{x_2-1}+\cdots\ +\sqrt{x_{2017}-1}$$
  if $$x_1,x_2,...,x_{2017}\geq1$$ and $$x_1+x_2+...+x_{2017}=4034$$
Comment: First off, I would define $y_i = x_i-1$, which rephrases the problem to finding the largest value of $\sqrt{y_1}+\cdots + \sqrt{y_{2017}}$ where all $y_i$ are positive, and $y_1+\cdots + y_{2017} = 2017$.
Comment: It is true that that's the value you get when all the $y_i$ are equal to $1$, but why would you think that that's the maximal value?
Comment: Please avoid PSQs (problem statement questions), they are badly received here. Much better to show your attempts.
Answer: From @Authur's comment, using $y_i = x_i - 1$, the problem can be transformed to
\begin{align}
\max z = \sum\limits_{i = 1}^{2017} \sqrt{y_i} & \\
\sum\limits_{i = 1}^{2017} y_i &= 2017 \\
y_i &\ge 0 \quad \forall \, i \in \{1,\dots 2017\}
\end{align}
Since it's tagged as linear-algebra, let's use the Cauchy-Schwartz inequality on $\Bbb R^{2017}$ equipped with the Euclidean norm with ${\bf y} = (\sqrt{y_1},\dots,\sqrt{y_{2017}})^T$ and ${\bf z} = (1,\dots,1)^T$.
\begin{align}
|{\bf y} \cdot {\bf z}| &\le ||{\bf y}|| ||{\bf z}|| \\
\sum\limits_{i = 1}^{2017} \sqrt{y_i} &\le \left( \sum\limits_{i = 1}^{2017} (\sqrt{y_i})^2 \right)^{1/2} \sqrt{2017} \\
&= \left( \sum\limits_{i = 1}^{2017} y_i \right)^{1/2} \sqrt{2017} \\
&= 2017
\end{align}
By settting $y_i = 1 \, \forall \, i \in \{1,\dots 2017\}$, we have ${\bf y} = {\bf z}$, so equality holds, and we conclude that 2017 is the required maximum.
Comment: I love me some good CS inequality applications. That being said, you call yourself a GNU supporter, and you choose as your avatar the Vim logo over, I dunno, Gedit? Or just the GNU gnu?
Comment: @Arthur Thanks for your comment.  I really support GNU, but that doesn't stop me to be a big fan of Vim text editor [TL;DR]
and to profit from it's efficient text editing experience.  (Learning some GNU Emacs is good though, especially for cursor movement in bash.)  Thanks to FLOSS, we can run (most) Matlab code online on [Octave online](https://octave-online.net/).  I copied a Markdown logo inside to "create" sth a bit different.
Answer: There is probably a shorter proof, but here is one.
Recall Jensen's inequality: if $U(\cdot)$ is a concave function and $X$ is a random variable, then $EU(X) \le U (EX)$.
Let $X$ be the r.v. that takes each of the $y_i$ values (use the simpler formulation suggested by Arthur in the comments) with equal probability $p_i=1/2017$. Then Jensen's inequality reads
$$\frac{\sum \sqrt{y_i}}{2017} = EU(X) \le U(EX) = \sqrt{\frac{\sum y_i}{2017} } = 1$$
so
$$\sum \sqrt{y_i} \le 2017$$
for any choice of the $y_i$'s. The proposed solution achieves the upper bound and thus it is a maximum.
Comment: +1 Nice use of Jensen's inequality.  I've learnt sth new :)
Answer: I did a little mental experimentation. Do we want to lump, taking one large square root and a lot of smaller ones, or to split, taking a lot of fairly small roots?
Noting $4034 = 2 * 2017$
Say $n = 4, 2n = 8$
So consider $\sqrt{5-1} + \sqrt{1-1} + \sqrt{1-1} + \sqrt{1-1}$ (lumping)  versus $\sqrt{2-1} + \sqrt{2-1} + \sqrt{2-1} + \sqrt{2-1} $ (splitting).
Lumping gets a result of 2 while splitting gets a result of 4.
Even without the $-1$, $\sqrt{8} = 2 \sqrt{2} < 4\sqrt{1}$
In general $\sqrt{n+1} + \sqrt{1-1} + \ldots +  \sqrt{1-1} + \sqrt{1-1}\sqrt{1-1} + \sqrt{1-1} + \sqrt{1-1} < n \sqrt{1}$
You could work inductively to show that the maximum is in fact at the furthest split.
So let $x_1 = x_2 = \ldots = x_n = 2$
And the maximum 1s $2017 \sqrt{2-1} = 2017$

Find the largest value


If in a turing machine, whenever the head tries to move left, it gets rewinded all the way to the leftmost cell.

Question: ASSUMPTION : Turing Machine has one sided infinite tape(right to be precise).
Given following constrained (deterministic single-tape) Turing Machine, what is the class of language recognized by it.
Restraint:

The Turing machine, on each transition can perform three operations(wrt moving L,R,S)
1.) It can move right by one cell.
2.) It can stay on current cell.
3.) It can move to the leftmost cell. (restraint)

So Does this turing machine accepts all the languages accepted by a Unrestrained turing machine or not.
I think it accepts all that an unrestricted turing machine can accept, but I am still doubtful.
Answer: This type of machines is indeed equivalent in power to ordinary Turing machines. In fact, even if you remove the ability to perform the second type of moves (stay on the current cell), the power of the machine will not be affected. Here is how such a restricted TM can be converted to an unrestricted one.
When the machine needs to move the head to the right, it first puts a special mark, e.g. $\sim$, upon the current symbol. Then it goes all the way back to the leftmost cell, and starts moving rightward. While the machine does so, if another special mark, e.g. $\bullet$, is discovered on a symbol, it gets removed from it. Once the head encounters $\sim$, the machine replaces it with $\bullet$ and moves the head one cell to the right. This combination of moves is equivalent to one move to the right performed by an ordinary TM. Note that the symbol in the left adjacent cell is now marked with $\bullet$.
When the head needs moving to the left, there are three possibilities.

The head points to the leftmost cell. In this case the tape contains no symbols marked with $\bullet$.
The head points to the cell adjacent to the leftmost cell. In this case the tape does contain a symbol marked with $\bullet$, which is located in the leftmost cell.
The head points to neither the leftmost cell nor its adjacent cell. In this case the tape also contains a symbol marked with $\bullet$, which is not in the leftmost cell. This is the symbol the head needs to move to.

The first case can be handled by marking the current symbol with $\sim$, moving the head to the leftmost cell and checking if the current symbol has $\sim$ upon it. If it does, remove it and remain in this cell, the move is now complete. Otherwise, check if the current symbol has $\bullet$ upon it. If it does, remove it, move the head to the adjacent cell, remove $\sim$ from the symbol in that cell and move to the leftmost cell again. This handles the second case. To deal with the last case perform the following steps.

Mark the current symbol with $\bullet$.
Move the head one cell to the right.
Check if the current symbol is marked with $\bullet$.

If it is, remove $\bullet$, move the head one cell to the right, remove $\sim$, move the head to the leftmost cell and scan the tape for an occurrence of $\bullet$. Once it is found, move the head one cell to the right and finish.
Otherwise, put $\bullet$ upon it, move the head to the leftmost cell and scan the tape for the first occurrence of $\bullet$. Once it is found, remove it, move the head one cell to the right and proceed with step 2.

This simulates one move leftward performed by an ordinary TM. Note, that unless the head is pointing to the leftmost cell, the symbol in the left adjacent cell is marked with $\bullet$.