android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.widget.RelativeLayout

Question: i am a beginner student of android basics course and i was making an score keeper app but when i run it with my mobile phone on android studio it is giving the following log error as well as showing "unfortunately has stopped" on my device.
I am very worried about this situation because i am new to android development and get this problem i will be more thankful to you anyone who will be able to solve this problem because it has stucked in my mind
LogCat

06-02 22:38:55.991 30457-30457/? I/art: Late-enabling -Xcheck:jni
06-02 22:38:56.059 30457-30457/com.example.tasbeeh.tasbeehcounter W/System: ClassLoader referenced unknown path: /data/app/com.example.tasbeeh.tasbeehcounter-1/lib/arm
06-02 22:38:56.107 30457-30457/com.example.tasbeeh.tasbeehcounter W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
06-02 22:38:56.192 30457-30457/com.example.tasbeeh.tasbeehcounter W/ResourceType: Failure getting entry for 0x7f060054 (t=5 e=84) (error -75)
06-02 22:38:56.194 30457-30457/com.example.tasbeeh.tasbeehcounter D/AndroidRuntime: Shutting down VM
06-02 22:38:56.197 30457-30457/com.example.tasbeeh.tasbeehcounter E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tasbeeh.tasbeehcounter, PID: 30457
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tasbeeh.tasbeehcounter/com.example.tasbeeh.tasbeehcounter.MainActivity}: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.widget.RelativeLayout
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class android.widget.RelativeLayout
        at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.tasbeeh.tasbeehcounter.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:6245)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.widget.RelativeLayout
        at android.view.LayoutInflater.createView(LayoutInflater.java:645)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.tasbeeh.tasbeehcounter.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:6245)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at android.view.LayoutInflater.createView(LayoutInflater.java:619)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.tasbeeh.tasbeehcounter.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:6245)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: android.content.res.Resources$NotFoundException: Resource "com.example.tasbeeh.tasbeehcounter:drawable/ground" (7f060054) is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f060054 a=-1 r=0x7f060054}
        at android.content.res.Resources.loadDrawableForCookie(Resources.java:2605)
        at android.content.res.Resources.loadDrawable(Resources.java:2543)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
        at android.view.View.<init>(View.java:3951)
        at android.view.ViewGroup.<init>(ViewGroup.java:573)
        at android.widget.RelativeLayout.<init>(RelativeLayout.java:248)
        at android.widget.RelativeLayout.<init>(RelativeLayout.java:244)
        at android.widget.RelativeLayout.<init>(RelativeLayout.java:240)
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at android.view.LayoutInflater.createView(LayoutInflater.java:619)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:694)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:762)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
        at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:139)
        at com.example.tasbeeh.tasbeehcounter.MainActivity.onCreate(MainActivity.java:16)
        at android.app.Activity.performCreate(Activity.java:6245)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-02 22:38:58.350 30457-30457/com.example.tasbeeh.tasbeehcounter I/Process: Sending signal. PID: 30457 SIG: 9

Layout_xml file

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout 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_height="match_parent"
    android:layout_width="match_parent"
    android:background="@drawable/ground"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="180dp"
        android:scaleType="centerCrop"
        android:src="@drawable/mosque" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:orientation="horizontal">

        <LinearLayout 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="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Person 1"
                android:textColor="@color/colorPrimary"
                android:textSize="?android:textAppearanceLarge" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Quran Read"
                android:textColor="@color/colorPrimary"
                android:textSize="20sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/quranView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="0"
                android:textColor="@android:color/black"
                android:textSize="30sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="addQuran1"
                    android:text="Add"
                    android:textColor="@android:color/white" />

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="lessQuran1"
                    android:text="Less"
                    android:textColor="@android:color/white" />

            </LinearLayout>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Durood Shareef"
                android:textColor="@android:color/black"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/duroodView1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="0"
                android:textColor="@android:color/black"
                android:textSize="30sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="addDurood1"
                    android:text="Add"
                    android:textColor="@android:color/white" />

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="lessDurood1"
                    android:text="Less"
                    android:textColor="@android:color/white" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:background="@color/colorPrimary"
                    android:onClick="resetThis1"
                    android:text="Reset This"
                    android:textColor="@android:color/white" />

            </LinearLayout>

        </LinearLayout>

        <LinearLayout 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="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Person 2"
                android:textColor="@color/colorPrimary"
                android:textSize="?android:textAppearanceLarge" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Quran Read"
                android:textColor="@color/colorPrimary"
                android:textSize="20sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/quranView2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="0"
                android:textColor="@android:color/black"
                android:textSize="30sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="addQuran2"
                    android:text="Add"
                    android:textColor="@android:color/white" />

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="lessQuran2"
                    android:text="Less"
                    android:textColor="@android:color/white" />

            </LinearLayout>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="Durood Shareef"
                android:textColor="@android:color/black"
                android:textSize="20sp" />

            <TextView
                android:id="@+id/duroodView2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:gravity="center_horizontal"
                android:text="0"
                android:textColor="@android:color/black"
                android:textSize="30sp" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="2dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="addDurood2"
                    android:text="Add"
                    android:textColor="@android:color/white" />

                <Button
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="2dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:layout_weight="1"
                    android:background="@color/colorPrimary"
                    android:onClick="lessDurood2"
                    android:text="Less"
                    android:textColor="@android:color/white" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginLeft="8dp"
                    android:layout_marginRight="8dp"
                    android:layout_marginTop="8dp"
                    android:background="@color/colorPrimary"
                    android:onClick="resetThis2"
                    android:text="Reset This"
                    android:textColor="@android:color/white" />

            </LinearLayout>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

MainActivity

package com.example.tasbeeh.tasbeehcounter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    int quran = 0;
    int durood = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void addQuran1 (View view){
        quran = quran + 1;
        displayQuran1(quran);
    }

    public void lessQuran1 (View view){
        quran = quran - 1;
        displayQuran1(quran);
    }

    public void addDurood1 (View view){
        durood = durood + 1;
        displayDurood1(durood);
    }

    public void lessDurood1 (View view){
        durood = durood - 1;
        displayDurood1(durood);
    }

    public void addQuran2 (View view){
        quran = quran + 1;
        displayQuran2(quran);
    }

    public void lessQuran2 (View view){
        quran = quran - 1;
        displayQuran2(quran);
    }

    public void addDurood2 (View view){
        durood = durood + 1;
        displayDurood2(durood);
    }

    public void lessDurood2 (View view){
        durood = durood - 1;
        displayDurood2(durood);
    }

    public void resetThis1 (View view) {
        quran = 0;
        durood = 0;
        displayQuran1(quran);
        displayDurood1(durood);
    }

    public void resetThis2 (View view) {
        quran = 0;
        durood = 0;
        displayQuran2(quran);
        displayDurood2(durood);
    }

    private void displayQuran1 (int number){
        TextView quran1displayview = (TextView) findViewById(R.id.quranView1);
        quran1displayview.setText("" + number);
    }

    private void displayDurood1 (int number){
        TextView durood1displayview = (TextView) findViewById(R.id.duroodView1);
        durood1displayview.setText("" + number);
    }

    private void displayQuran2 (int number){
        TextView quran2displayview = (TextView) findViewById(R.id.quranView2);
        quran2displayview.setText("" + number);
    }

    private void displayDurood2 (int number){
        TextView durood2displayview = (TextView) findViewById(R.id.duroodView2);
        durood2displayview.setText("" + number);
    }
}
Answer: If you see the exception root cause, the actual issue is
android.content.res.Resources$NotFoundException: Resource "com.example.tasbeeh.tasbeehcounter:drawable/ground" (7f060054) is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f060054 a=-1 r=0x7f060054}

In your layout.xml file, you have used a background for your root RelativeLayout.
<RelativeLayout 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_height="match_parent"
    android:layout_width="match_parent"
    android:background="@drawable/ground" <-- Here
    tools:context=".MainActivity">

Make sure you have added the drawable (file or xml) with name ground in your drawable or drawable-**** (mdpi, hdmi, xhdpi, xxhdpi and xxxhdpi) folder.
Tip: Try using vector drawables rather than static png files. More at: https://developer.android.com/guide/topics/graphics/vector-drawable-resources
Comment: Thank you very much for indicating and making my attention to drawable folder, the problem was not the same as you described but the things were pretty much linked with the design and colors as you told me ! :) I only changed android:textSize="@color/primary"
                                  android:textColor="@android:Color/white"    To android:textSize="20sp"
                android:textColor="#3F51B5" and the problem was solved !
Comment: Aha! Cool. Also one other point to keep in mind is that it's always better to define your own colours than using the one's under @android:color. OEMs can change those colours to different variants on their devices.
Answer: drawable image might be in v24, delete this and place it without v24(simple).


Add custom CSS classes to components - Spartacus

Question: I created a Rotating Images Component with smartedit and now i want to customize the style of that component. There is a field in smartedit style classes, but even though I added a class and in styles.scss added styles for that class I doesn't work. So i am wondering how can I change styling on a specific component, without changing the styling of all Rotating Images Components.
Answer: I will use a concrete example to illustrate how to customize component appearance via css manipulation.
Suppose I would like to change the behavior of "ORDER SUMMARY" in cart view:

find its selector in Chrome dev tools:
cx-order-summary h4

use the following line in file styles.scss, to overwrite the default setting provided by Spartacus styles library:

the final result:

Another example,suppose I need to make font color to be green and font bold:

In order to reduce the workload and avoid repeatedly applying the same CSS settings to the selectors corresponding to the Order Summary and Coupon areas, we can define the repeated CSS settings in %jerry-custom-div (similar to the programming language Macro), and then use @extend in cx-order-summary and cx-cart-coupon to directly reference this common definition.
I use the following code in styles.scss:

final result:
Comment: That works, any idea how to make the width od the said component - Rotating Images Component 100% of the page if the slot that the component is in isn't 100% of width?


How to avoid url conflict when defining menu items, and make sure path without wildcards will be used in favor of path with %?

Question: In hook_menu, I have
$path = "events"

$items[$path] = array(
  'title' => t('Events'),
  'page callback' => 'my_events_page',
  'access arguments' => array('view my events'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'my_events.pages.inc',
);

$items[$path . '/past'] = array(
  'title' => t('Past events'),
  'page callback' => 'my_events_past_page',
  'access arguments' => array('view my events'),
  'type' => MENU_NORMAL_ITEM,
  'file' => 'my_events.pages.inc',
);

$items[$path . '/%'] = array(
  'title' => t('Events'),
  'page callback' => 'my_events_page',
  'page arguments' => array($depth),
  'access arguments' => array('view my events'),
  'type' => MENU_CALLBACK,
  'file' => 'my_events.pages.inc',
);

They were working, but not now.
If I change $items['events/past'] to $items['events/past1'], it works.
Does it mean I have path conflict? If so, how can I resolve it?
Rows in my {menu_router} table are as follows:

path: events
page_callback: views_page (but I set it to xxx_events_page in hook_menu)
fit: 1
include_file: empty (should not be empty)
--
path: events/%
page_callback: xxx_events_page (good)
fit: 2
include_file: a file path is there
--
path: events/past
page_callback: views_page (but I set it to xxx_events_past_page in hook_menu)
fit: 3
include_file: empty (should not be empty)

If I update the page_callback and include_file it works. If I clear the cache, everything set back to default.
Comment: I took liberty to re-format your post and make it a consistent whole. Of course feel free to edit it again if you feel I missed something.
Comment: Do you have any module that might define `events` path? See `{menu_links}` table, `router_path` and `module` columns.
Comment: Solved. The issue is I defined the same path in views. I see a page_callback "views_page" in menu_router table, but I never understand what it means. (It gives me hint about view, but I never try to understand it.)
Answer: Assuming you are using Drupal 7:
Order matters only a bit - menu_router_build() saves all path into the {menu_router} table just the way they are set. But there are no guarantees database will return elements in that order. Logic to decide which menu item should be executed is in menu_get_item().
Actual query is:
$router_item = db_query_range('SELECT * FROM {menu_router} WHERE path IN (:ancestors) ORDER BY fit DESC', 0, 1, array(':ancestors' => $ancestors))->fetchAssoc();

As you can see, fitting elements are ordered by fit column, most specific first.
As you can see in actual _menu_router_build(), $fit gets initially set to 0 for each menu item:
foreach ($callbacks as $path => $item) {
  $load_functions = array();
  $to_arg_functions = array();
  $fit = 0;

It means it shouldn't be possible for the order of menu elements in hook_menu() to affect order of routing. Actual code is a bit complicated to understand, but elements specific should have higher fit than elements with '%' in them. As the comment in code says: // If there is no %, it fits maximally.
Answer: I use this code bellow in a custom module "mymodule" with drupal 7 and everthing work well. What version of Drupal do you use ?
 <?php

    function mymodule_menu() {
        $path = "events";

        $items[$path] = array(
            'title' => t('Events'),
            'page callback' => 'my_events_page',
            'access arguments' => array('access content'),
            'type' => MENU_NORMAL_ITEM,
            //'file' => 'my_events.pages.inc',
        );

        $items[$path . '/%'] = array(
            'title' => t('Events'),
            'page callback' => 'my_events_page',
            'page arguments' => array($depth),
            'access arguments' => array('access content'),
            'type' => MENU_CALLBACK,
            //'file' => 'my_events.pages.inc',
        );

        $items[$path . '/past'] = array(
            'title' => t('Past events'),
            'page callback' => 'my_events_past_page',
            'access arguments' => array('access content'),
            'type' => MENU_NORMAL_ITEM,
            //'file' => 'my_events.pages.inc',
        );

        return $items;
    }

    function my_events_page(){
        print "hello";
    }

    function my_events_past_page(){
        print "past";
    }

    ?>


Installing Z3 binding with haskell on mac

Question: I have installed Z3 on my computer (Mac with m1 chip) by running:
brew install z3

I am trying to install the z3 binding for Haskell.
On the library website, it is written:
Installation:

1) Install a Z3 4.x release. (Support for Z3 3.x is provided by the 0.3.2 version of these bindings.)

2) Just type cabal install z3 if you used the standard locations for dynamic libraries (/usr/lib) and header files (/usr/include).

Otherwise use the --extra-lib-dirs and --extra-include-dirs Cabal flags when installing.

So I have done step 1, and in step 2, I type cabal install z3 which I get an error. I ran "find /opt/homebrew -name "z3.h" 2>/dev/null" in my terminal and got the following
/opt/homebrew/include/z3.h
/opt/homebrew/Cellar/z3/4.12.2/include/z3.h

I don't know why I have two headers to be honest and similarly I got the paths for the lib
/opt/homebrew/lib/libz3.4.12.dylib
/opt/homebrew/lib/libz126.96.36.199.0.dylib
/opt/homebrew/lib/libz3.dylib
/opt/homebrew/Cellar/z3/4.12.2/lib/libz3.4.12.dylib
/opt/homebrew/Cellar/z3/4.12.2/lib/libz18.104.22.168.0.dylib
/opt/homebrew/Cellar/z3/4.12.2/lib/libz3.dylib

So when I try either of the following
stack install z3 --extra-lib-dirs=/opt/homebrew/lib --extra-include-dirs=/opt/homebrew/include

OR

stack install z3 --extra-lib-dirs=/opt/homebrew/Cellar/z3/4.12.2/lib --extra-include-dirs=/opt/homebrew/Cellar/z3/4.12.2/include

I get an error:
z3> configure
z3> Configuring z3-408.2...
z3> build
z3> Preprocessing library for z3-408.2..
z3> compiling .stack-work/dist/aarch64-osx/Cabal-188.8.131.52/build/Z3/Base/C_hsc_make.c failed (exit code 1)
z3> rsp file was: ".stack-work/dist/aarch64-osx/Cabal-220.127.116.11/build/Z3/Base/hsc2hscall47771-0.rsp"
z3> command was: /usr/bin/gcc -c .stack-work/dist/aarch64-osx/Cabal-220.127.116.11/build/Z3/Base/C_hsc_make.c -o .stack-work/dist/aarch64-osx/Cabal-126.96.36.199/build/Z3/Base/C_hsc_make.o --target=arm64-apple-darwin --target=arm64-apple-darwin -Wl,-no_fixup_chains -D__GLASGOW_HASKELL__=904 -Ddarwin_BUILD_OS=1 -Daarch64_BUILD_ARCH=1 -Ddarwin_HOST_OS=1 -Daarch64_HOST_ARCH=1 -I/opt/homebrew/include -I/opt/homebrew/include -I.stack-work/dist/aarch64-osx/Cabal-126.96.36.199/build/autogen -I.stack-work/dist/aarch64-osx/Cabal-220.127.116.11/build/global-autogen -include .stack-work/dist/aarch64-osx/Cabal-18.104.22.168/build/autogen/cabal_macros.h -I/Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/../lib/aarch64-osx-ghc-9.4.7/base-220.127.116.11/include -I/Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/../lib/aarch64-osx-ghc-9.4.7/ghc-bignum-1.3/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/ffi -I/Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/../lib/aarch64-osx-ghc-9.4.7/rts-1.0.2/include -I/Users/mehradhq/.ghcup/ghc/9.4.7/include/
z3> error: clang: warning: -Wl,-no_fixup_chains: 'linker' input unused [-Wunused-command-line-argument]
z3> /private/var/folders/jr/fkn85rwj2l78jxbdpgdz7j840000gn/T/stack-cb61378bcfe38b26/z3-408.2/C.hsc:97:16: error: use of undeclared identifier 'Z3_TRUE'; did you mean 'Z3_L_TRUE'?
z3>     hsc_const (Z3_TRUE);
z3>                ^~~~~~~
z3>                Z3_L_TRUE
z3> /Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/template-hsc.h:45:10: note: expanded from macro 'hsc_const'
z3>     if ((x) < 0)                                      \
z3>          ^
z3> /opt/homebrew/Cellar/z3/4.12.2/include/z3_api.h:94:5: note: 'Z3_L_TRUE' declared here
z3>     Z3_L_TRUE
z3>     ^
z3> /private/var/folders/jr/fkn85rwj2l78jxbdpgdz7j840000gn/T/stack-cb61378bcfe38b26/z3-408.2/C.hsc:97:16: error: use of undeclared identifier 'Z3_TRUE'; did you mean 'Z3_L_TRUE'?
z3>     hsc_const (Z3_TRUE);
z3>                ^~~~~~~
z3>                Z3_L_TRUE
z3> /Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/template-hsc.h:46:41: note: expanded from macro 'hsc_const'
z3>         hsc_printf ("%lld", (long long)(x));          \
z3>                                         ^
z3> /opt/homebrew/Cellar/z3/4.12.2/include/z3_api.h:94:5: note: 'Z3_L_TRUE' declared here
z3>     Z3_L_TRUE
z3>     ^
z3> /private/var/folders/jr/fkn85rwj2l78jxbdpgdz7j840000gn/T/stack-cb61378bcfe38b26/z3-408.2/C.hsc:97:16: error: use of undeclared identifier 'Z3_TRUE'; did you mean 'Z3_L_TRUE'?
z3>     hsc_const (Z3_TRUE);
z3>                ^~~~~~~
z3>                Z3_L_TRUE
z3> /Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/template-hsc.h:48:50: note: expanded from macro 'hsc_const'
z3>         hsc_printf ("%llu", (unsigned long long)(x));
z3>                                                  ^
z3> /opt/homebrew/Cellar/z3/4.12.2/include/z3_api.h:94:5: note: 'Z3_L_TRUE' declared here
z3>     Z3_L_TRUE
z3>     ^
z3> /private/var/folders/jr/fkn85rwj2l78jxbdpgdz7j840000gn/T/stack-cb61378bcfe38b26/z3-408.2/C.hsc:99:16: error: use of undeclared identifier 'Z3_FALSE'; did you mean 'Z3_L_FALSE'?
z3>     hsc_const (Z3_FALSE);
z3>                ^~~~~~~~
z3>                Z3_L_FALSE
z3> /Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/template-hsc.h:45:10: note: expanded from macro 'hsc_const'
z3>     if ((x) < 0)                                      \
z3>          ^
z3> /opt/homebrew/Cellar/z3/4.12.2/include/z3_api.h:92:5: note: 'Z3_L_FALSE' declared here
z3>     Z3_L_FALSE = -1,
z3>     ^
z3> /private/var/folders/jr/fkn85rwj2l78jxbdpgdz7j840000gn/T/stack-cb61378bcfe38b26/z3-408.2/C.hsc:99:16: error: use of undeclared identifier 'Z3_FALSE'; did you mean 'Z3_L_FALSE'?
z3>     hsc_const (Z3_FALSE);
z3>                ^~~~~~~~
z3>                Z3_L_FALSE
z3> /Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/template-hsc.h:46:41: note: expanded from macro 'hsc_const'
z3>         hsc_printf ("%lld", (long long)(x));          \
z3>                                         ^
z3> /opt/homebrew/Cellar/z3/4.12.2/include/z3_api.h:92:5: note: 'Z3_L_FALSE' declared here
z3>     Z3_L_FALSE = -1,
z3>     ^
z3> /private/var/folders/jr/fkn85rwj2l78jxbdpgdz7j840000gn/T/stack-cb61378bcfe38b26/z3-408.2/C.hsc:99:16: error: use of undeclared identifier 'Z3_FALSE'; did you mean 'Z3_L_FALSE'?
z3>     hsc_const (Z3_FALSE);
z3>                ^~~~~~~~
z3>                Z3_L_FALSE
z3> /Users/mehradhq/.ghcup/ghc/9.4.7/lib/ghc-9.4.7/lib/template-hsc.h:48:50: note: expanded from macro 'hsc_const'
z3>         hsc_printf ("%llu", (unsigned long long)(x));
z3>                                                  ^
z3> /opt/homebrew/Cellar/z3/4.12.2/include/z3_api.h:92:5: note: 'Z3_L_FALSE' declared here
z3>     Z3_L_FALSE = -1,
z3>     ^
z3> 6 errors generated.
z3>

Error: [S-7282]
       Stack failed to execute the build plan.

       While executing the build plan, Stack encountered the error:

       [S-7011]
       While building package z3-408.2 (scroll up to its section to see the
       error) using:
       /Users/mehradhq/.stack/setup-exe-cache/aarch64-osx/Cabal-simple_6HauvNHV_184.108.40.206_ghc-9.4.7 --verbose=1 --builddir=.stack-work/dist/aarch64-osx/Cabal-18.104.22.168 build --ghc-options " -fdiagnostics-color=always"
       Process exited with code: ExitFailure 1

I do not know what this is saying. I also ran it with cabal just to see if it works but again got the following error:
Warning: Unknown/unsupported 'ghc' version detected (Cabal 126.96.36.199 supports
'ghc' version < 9.4): /Users/mehradhq/.ghcup/bin/ghc is version 9.4.7
Warning: Unknown/unsupported 'ghc' version detected (Cabal 220.127.116.11 supports
'ghc' version < 9.4): /Users/mehradhq/.ghcup/bin/ghc is version 9.4.7
Resolving dependencies...
Build profile: -w ghc-9.4.7 -O1
In order, the following will be built (use -v for more details):
 - hsc2hs-0.68.10 (exe:hsc2hs) (requires download & build)
 - z3-408.2 (lib) (requires download & build)
Downloading  hsc2hs-0.68.10
Downloaded   hsc2hs-0.68.10
Downloading  z3-408.2
Starting     hsc2hs-0.68.10 (exe:hsc2hs)
Downloaded   z3-408.2
Building     hsc2hs-0.68.10 (exe:hsc2hs)
Installing   hsc2hs-0.68.10 (exe:hsc2hs)
Completed    hsc2hs-0.68.10 (exe:hsc2hs)
Starting     z3-408.2 (lib)

Failed to build z3-408.2. The failure occurred during the configure step.
Build log ( /Users/mehradhq/.cabal/logs/ghc-9.4.7/z3-408.2-f9eabcb0.log ):
Configuring library for z3-408.2..
cabal-22.214.171.124: Missing dependency on a foreign library:
* Missing (or bad) header file: z3.h
* Missing (or bad) C library: z3
This problem can usually be solved by installing the system package that
provides this library (you may need the "-dev" version). If the library is
already installed but in a non-standard location then you can use the flags
--extra-include-dirs= and --extra-lib-dirs= to specify where it is.If the
library file does exist, it may contain errors that are caught by the C
compiler at the preprocessing stage. In this case you can re-run configure
with the verbosity flag -v3 to see the error messages.
If the header file does exist, it may contain errors that are caught by the C
compiler at the preprocessing stage. In this case you can re-run configure
with the verbosity flag -v3 to see the error messages.

cabal: Failed to build z3-408.2. See the build log above for details.

The error messages are much clearer but I have everything installed and have defined the paths. I also looked at the Segmentation fault in Z3 (Haskell) question. I tried both ways proposed in the responses, none of them work. Also I am running on:
The Glorious Glasgow Haskell Compilation System, version 9.4.7
The GHCup Haskell installer, version 0.1.19.4
stack Version 2.11.1
cabal-install version 220.127.116.11

Can someone please explain what is the problem and how to fix it? thank you in advance.
Comment: This seems to be a version mismatch between the installed `4.12.2` and looked for `408.2` (maybe that's meant to be `4.08.2`?) z3 libraries. You can try to install z3v408.2 or z3v4.08.2
Comment: @cafce25 Thanks. How can I install an older version of z3 using brew I just ran brew install z3. I have done brew search z3 and apparently an older version of z3 does not exist. How else can I get z3 for my computer?
Comment: Not an answer to your question; but unless you're planning to do low-level programming with z3, you might want to consider using a higher-level interface from Haskell; that can save you a lot of trouble in communicating with z3. There are a few such libraries, I'm most familiar with https://hackage.haskell.org/package/sbv, which handles communication with z3 behind the scenes, saving you a lot of headache.
Comment: As I don't use a mac and thus don't use hombrew can't help you there, that's just what I interpret the error messages to mean.
Answer: Just for the sake that someone else is trying to run Z3 binding with haskell on mac (with an arm processor) and gets the same errors, I will post the solution that has worked for me here. So basically, installing Z3 by executing the following command
brew install Z3

in the terminal will install Z3 for you - you can verify this by running Z3 --version. However, the problem is that the Z3 version is 4.12.* whereas the Z3 binding for Haskell only accepts a Z3 version of 4.8.. So this doesn't work to bind Haskell with Z3. Unfortunately, brew does not have version 4.8. of Z3 to install, therefore you cannot use brew for this. Before proceeding you can run brew uninstall Z3 to uninstall the Z3. Now go to the website https://github.com/Z3Prover/z3/releases/tag/z3-4.8.17 and download https://z3-4.8.17-arm64-osx-10.16.zip/. Then run "cabal install z3" with the flags --extra-include-dirs and --extra-lib-dirs referring to the z3 headers and libz3.* directory respectively. (for me this was cabal install z3 -v3 --extra-include-dirs=/Users/PATH/z3-4.8.17-arm64-osx-10.16/include --extra-lib-dirs=/Users/PATH/z3-4.8.17-arm64-osx-10.16/bin) Even when I ran this I got the error that Warning: Unknown/unsupported 'ghc' version detected (Cabal 184.108.40.206 supports
'ghc' version < 9.4 hence I asked the question yesterday. If you have ghcup installed then just use ghcup install ghc X*. In the placeholder X specify that version of ghc then use ghc setup ghc X to make that version the working version of ghc. The reason is that you need an older version of ghc than 9.4 to install z3. After doing so, again run the command cabal install z3 with the flags and if it works, then it works. For me it didn't so logging the errors, I had to change the version of my LLVM using brew. My version was 17 but the cabal install z3 wanted a version between 9-13. So I installed version 12 (to install you need to use brew. You need to further unlink and link the new version. You can google it or just simply ask Chatgpt). Then if you run cabal install z3 and it still doesn't work like me do the following:
!!!!!
sudo cp /Users/PATH/z3-4.8.17-arm64-osx-10.16/bin/libz3.dylib /usr/local/lib/

!!!!!
Okay I am NOT going to suggest this and it is NOT recommended to copy it to lib manually for safety reasons. However, this works (and I really needed it). Again just run cabal install z3 -v3 --extra-include-dirs=/Users/PATH/z3-4.8.17-arm64-osx-10.16/include and all should work. Please note that the last problem is due to that apparently the --extra-lib-dirs flag doesn't recognize the directory. So I put the file in the lib directory manually. I hope this helps someone as it took me a long time to get the z3 with haskell binding to work. The SBV library is a good alternative but I have been told that it does not work good with quantification over arrays. I haven't experimented it myself though.
Comment: Looks like z3 Haskell bindings bitrotted severely if you have to downgrade everything. In particular, z3 4.8 is pretty old by now, shouldn't really use it. Please file a ticket with them so they at least know installation is such a hassle these days.
Comment: Also, you said SBV doesn't work with quantification of arrays. I'm not sure if that's true. What exactly are you trying to do? I'm sure there might be a way to model such usage, but hard ti say without seeing what you are trying to do.
Comment: @alias Thank you for your comments and sorry for getting back late. I think the main issue is that because the Haskell bindings only work with the 4.8 version of z3, I have to downgrade a lot of things. I'll send a notice because it wasn't only me and other students had similar issues (on mac or windows). Regarding SBV, my professors have found that previously SBV did not work well for quantification over arrays. So the plan is to write a predicate transformer for programs written in GCL. We have to convert programs to predicate logic using wlp and then pass the expression to z3 for validation
Comment: @alias I have not tried SBV myself and am not aware if this is the case or not. However, I will probably sun some experiments using SBV to see if thats the case or not. Just wanted to get z3 running because I am short in time and wanted to get the suggested approach up and running as fast as possible. Do you have any experience or advice regarding the usage of SBV or in general in the domain of the project? will appreciate it and thanks in advance.
Comment: SBV should be just fine for programming predicate transformers; but impossible to say without seeing what sort of trouble your colleagues ran into. If you try it out and have difficulties, you can always ask at the relevant stack overflow forum: https://stackoverflow.com/questions/tagged/sbv


Commutative property of ring addition

Question: I have a simple question answer to which would help me more deeply understand the concept of (non)commutative structures. Let's take for example (our teacher's definition of) a ring:
Let $R\neq \emptyset$ be a set, let $\oplus:A\times A \to A$ and $\bullet :A\times A \to A$ be binary operations. Moreover, let $(R, \oplus)$ be a commutative group, $(R, \bullet)$ be a monoid and following property holds for all $a, b, c\in R$:
$$a\bullet(b\oplus c) = (a\bullet b)\oplus(a \bullet c)$$
$$(b\oplus c)\bullet a = (b\bullet a)\oplus(c \bullet a)$$
Then ordered triple $\mathbf R = (R, \oplus, \bullet \mathbf)$ is called a (unitary) ring.
Moreover, we call ring $\mathbf R$ commutative iff $(R, \bullet)$ is a commutative monoid. Commutativity of a ring is always a matter of its multiplicative operation because the additive operation is always assumed to be commutative.
Could anyone explain me the bold part? Why do we even in non-commutative rings (and fields etc.) assume the addition to be always commutative? Is there some serious reason? Would it make any trouble? Or studying of structures with non-commutative addition just doesn't give us anything new so we can take addition as commutative simply because of our comfort?
Comment: Possible duplicate of [Why is ring addition commutative?](http://math.stackexchange.com/questions/609364/why-is-ring-addition-commutative)
Answer: Perhaps the comment refers to the fact that in order to generalize rings to structures with noncommutative addition, we cannot  simply delete the axiom that addition is commutative,  since, in fact, other axioms force addition to be commutative (Hankel, 1867 [1]). The proof is simple: apply both the left and right
distributive law in different order to the term  $\rm\:(1\!+\!1)(x\!+\!y),\:$ viz.
$$\rm (1\!+\!1)(x\!+\!y) = \bigg\lbrace \begin{eqnarray}\rm (1\!+\!1)x\!+\!(1\!+\!1)y\, =\, x + \color{#C00}{x\!+\!y} + y\\
\rm 1(x\!+\!y)\!+1(x\!+\!y)\, =\, x + \color{#0A0}{y\!+\!x} + y\end{eqnarray}\bigg\rbrace\Rightarrow\, \color{#C00}{x\!+\!y}\,=\,\color{#0A0}{y\!+\!x}\ \ by\ \ cancel\ \ x,y$$
Thus commutativity of addition, $\rm\:x+y = y+x,\:$ is implied by these axioms:
$(1)\ \  *\,$ distributes over $\rm\,+\!:\ \   x(y+z)\, =\, xy+xz,\ \   (y+z)x\, =\, yx+zx$
$(2)\ \,  +\,$ is cancellative: $\rm\ \      x+y\, =\, x+z\:\Rightarrow\: y=z,\ \  y+x\, =\, z+x\:\Rightarrow\: y=z$
$(3)\ \,  +\,$ is associative:  $\rm\ \    (x+y)+z\, =\, x+(y+z)$
$(4)\ \  *\,$ has a neutral element $\rm\,1\!:\ \      1x = x$
In order to state this result concisely, recall that a SemiRing is
that generalization of a Ring whose additive structure is relaxed
from a commutative Group to merely a SemiGroup, i.e. here the only
hypothesis on addition is that it be associative (so in SemiRings,
unlike Rings, addition need not be commutative, nor need every
element $\rm\,x\,$ have an additive inverse $\rm\,-x).\,$ Now the above result may
be stated as follows: a semiring with $\,1\,$ and cancellative addition
has commutative addition. Such semirings are simply subsemirings
of rings (as is $\rm\:\Bbb N \subset \Bbb Z)\,$ because any commutative cancellative
semigroup embeds canonically into a commutative group, its group
of differences (in precisely the same way $\rm\,\Bbb Z\,$ is constructed from $\rm\,\Bbb N,\,$
i.e. the additive version of the fraction field construction).
Examples of SemiRings include:  $\rm\,\Bbb N;\,$ initial segments of cardinals;
distributive lattices (e.g. subsets of a powerset with operations $\cup$ and $\cap$;
$\rm\,\Bbb R\,$ with + being min or max, and $*$ being addition; semigroup semirings
(e.g. formal power series); formal languages with union, concat; etc.
For a nice survey of SemiRings and SemiFields see [2]. See also Near-Rings.
[1] Gerhard Betsch. On the beginnings and development of near-ring theory.
pp. 1-11 in:
Near-rings and near-fields. Proceedings of the conference
held in Fredericton, New Brunswick, July 18-24, 1993. Edited by Yuen Fong,
Howard E. Bell, Wen-Fong Ke, Gordon Mason and  Gunter Pilz.
Mathematics and its Applications, 336. Kluwer Academic Publishers Group,
Dordrecht, 1995. x+278 pp. ISBN: 0-7923-3635-6 Zbl review
[2] Hebisch, Udo; Weinert, Hanns Joachim. Semirings and semifields. $\ $ pp. 425-462 in:  Handbook of algebra. Vol. 1. Edited by M. Hazewinkel.
North-Holland Publishing Co., Amsterdam, 1996. xx+915 pp. ISBN: 0-444-82212-7
Zbl review,
AMS review
Comment: Thank you, it's really interesting! Most books I have, talk about the topics just briefly without any deeper and detailed insight. These are the notes which I'd love to have my books full of...
Accepted button goes to you.
Comment: Never knew distribuitive was THAT amazing.
Answer: There are so-called  near-semirings (http://en.wikipedia.org/wiki/Near-semiring) in which addition is non-commutative.
Answer: Of course one can develop a theory in which the addition is not commutative (see Boris' answer and his mentioning the near-semirings).
Why "rings with non-commutative addition" are a somewhat side story and commutativity of addition is the usual assumption? Simply because the basic and main examples of these rings, those which primarily occur doing mathematics, do have this property.
I believe that by far most "rings" can be reconducted in a way or another to the ring of matrices over some algebraic structure with commutative addition (commutative rings or division algebras, tipically). Addition of such matrices commutes.

Commutative property of ring addition


Retorno da função system(); c++

Question: Alguém poderia me ajudar, já faz um tempo que estou com essa duvida, referente a como passar para um variável o retorno da função System();
Função essa que executa um determinado comando no console, e traz na tela os resultados.
Se eu por exemplo quisesse guardar em uma variável tipo string, a seguinte saída:
string hostname = system("whoami");

E fazer que com o conteúdo nela contido seja o hostname da maquina.
Comment: O retorno da função system é um int com valor 0 se correu tudo bem (depende da implementação) ou um valor diferente de zero caso o parâmetro seja NULL.
Answer: Talvez o que você precisa é da função fopen ao invés de system. Você pode fazer o seguinte:
FILE* output_file = nullptr;
char buffer[1024];

output_file = popen("whoami", "r");

if(output_file)
{
    int i = 0;
    char c;

    while((c = fgetc(output_file)) != EOF)
    {
        buffer[i] = c;
        i++;
    }
    buffer[i] = '\0';

    std::cout << buffer << '\n';
}

A função popen grava a saida do comando num arquivo, e este arquivo é retornado pela função. Daí é so salvar o conteúdo do arquivo no buffer.
Comment: nullptr é o mesmo que NULL, foi introduzido em c++11.  Nota que ao contrário de NULL, nullptr não é uma macro, é uma palavra reservada e eu recomendo que você o use. O erro  deve ser porque c++11 não está ativado. Vai logo e ativa, c++ moderno é bem melhor.
Comment: Otimo, é exatamente o que eu preciso, poderia me explicar mais sobre o nullptr, pois em meu codigo diz que ele não foi declarado
Answer: Só para clarificar um pouco sobre a função system, pois a utilização que mostrou  não está correta:
string hostname = system("whoami");

A função system executa um determinado comando mas não devolve os resultados mostrados na tela e sim um inteiro. Passo a citar a documentação sobre o significado desse inteiro retornado:

If command is a null pointer, the function returns a non-zero value in case a command processor is available and a zero value if it is not.
If command is not a null pointer, the value returned depends on the system and library implementations, but it is generally expected to be the status code returned by the called command, if supported.

Em tradução livre:

Se o comando for um ponteiro NULL, a função devolve um valor diferente de zero se o processador de comandos estiver disponível e zero caso contrário.
Se o comando não for um ponteiro NULL, o valor retornado vai depender do sistema operacional e respetiva implementação, mas regra geral é esperado que seja um código de estado devolvido pelo comando executado, se suportado.

Em conclusão, o valor devolvido é um numero, que depende da implementação, mas regra geral é um código. Por isso esta função não devolve o que espera, embora o resultado da execução do comando seja visível na consola após chamar a função system.
Para obter o resultado da execução do comando como texto e guardar numa variável pode fazer como está na resposta do @user72726

Retorno da função system(); c++


Google Cloud App engine error 502

Question: I'm new to google cloud platform. I have deployed a dotnet core project to App Engine locate Asian-south-1. But start from yesterday, the server always returns Error code 502 with a message.
"Error: Server Error
The server encountered a temporary error and could not complete your request.
Please try again in 30 seconds."
I also try to create a brand new project and deploy it but still have no lucks. How can I debug to see where is the problem?
Answer: Edit: There seems to be an issue with GAE traffic in Asia, which is probably related to your error. The Google engineering team is investigating it with high priority.
Previous answer in case is it helpful in some way:
To make sure the issue is in your application, I'd start by trying to deploy the sample HelloWorld application as described in the quickstart.
If that works you can start debugging your own code. You can check the logs in Stackdriver and take a look at the App Engine dashboard.
Additionally, you can try Stackdriver Debugger for a closer look at the code, although it is still in alpha, so it may not work perfectly.

Google Cloud App engine error 502


How to generate report using report viewer which can contain bulk of data

Question: I want to display a report which will generate as employee selected by grid view. If i select 'Select All' check box than all employee data should be through in report and if i select people randomly than only that people data will be produce in report.  Please help me out. I done report for single employee but for this i am not getting any idea. Thanks :)
Comment: Which report tool you used for generating report. Crystal report or something else.
Answer: There is a property called setParameters in report viewer which is used to pass the data from .NET application to your report viewer .The below links may help you
Pass Report Parameters
Cascading Parameters


Probability of infinitely many events

Question: If $x_n$ identical and independent and $P(x_n)>r>0$, show $P(x_n$ happens for infinitely many $n)=1$.
I know this follows from second lemma of borel contelli, but is there a way not to use that lemma?
Comment: Independence is crucial, so the best way to prove this is to use Borel-Cantelli. Any attempt to prove it from scratch is likely to imitate the proof of Borel-Cantelli Lemma.
Comment: What are $x_n$'s? Are they events or random variables?
Comment: @kabomurphy Events
Comment: @kabomurphy is the condition here stronger than borel contelli though?
Answer: The event that only finitely many of the events $\ \left\{x_n\right\}_{i=1}^\infty\ $ occur is $\ \bigcup_\limits{i=1}^\infty\bigcap_\limits{j=i}^\infty\Omega\setminus x_j\ $. Since $\ \bigcap_\limits{j=i}^\infty\Omega\setminus x_j\subseteq\bigcap_\limits{j=i}^{i+k-1}\Omega\setminus x_j \ $ for all positive integers $\ i\ $ and $\ k\ $, and the latter events have probablity less than $\ (1-r)^k\ $, it follows that the probability of $\ \bigcap_\limits{j=i}^\infty\Omega\setminus x_j\ $ is zero for every $\ i\ $.  Thus, since the event that only finitely many of the events $\ \left\{x_n\right\}_{i=1}^\infty\ $ occur is a countable union of events of zero probability, it also has zero probability itself.
I'll leave it for others to judge how closely this mimics the proof of the Borel-Cantelli lemma, or whether it is any simpler.

Probability of infinitely many events


What does "URL-safe" mean?

Question: The definition for JSON Web Tokens (JWT, see RFC 7519) says that it is a "URL-safe means of representing claims to be transferred between two parties".
I'm wondering, what does it mean if something is URL-safe?
As far as I know, JWT are not passed around as part of the URL. Is it just that, or is there more to it?
Answer: Later in the RFC it says:

A JWT is represented as a sequence of URL-safe parts separated by
period ('.') characters.  Each part contains a base64url-encoded
value.

This, combined with the RFC not specifying some other meaning explicitly, suggests it means simply "safe to put in a URL" (e.g., doesn't have unencoded / or ? or & characters, etc.).
Comment: Thank you, this makes sense. It's all about making the transport of the character sequence as simple as possible.

What does "URL-safe" mean?


Integral limit as $N\to\infty$ in Theorem 8.15 of Gilbarg-Trudinger

Question: I am reviewing the proof of Theorem 8.15 in Gilbarg-Trudinger (see below).
In equation (8.36), how can we take $N\to\infty$? Writing $2^* := \frac{2\hat{n}}{\hat{n}-2}$ and $q^\ast := \frac{2q}{q-2}$, equation (8.36) is presicely
$$
\left(\int_{w \le N}\left(w^\beta - k^\beta\right)^{2^\ast} + \int_{w > N}\left(\beta N^{\beta-1}w - \beta N^\beta +N^\beta-k^\beta\right)^{2^\ast}\right)^{1/2^\ast} \le C\left(\int_{w \le N}\left(\beta w^{\beta}\right)^{q^\ast} + \int_{w > N}\left(\beta N^{\beta-1}w\right)^{q^\ast}\right)^{1/q^\ast}.
$$
By the monotone convergence theorem, I can easily handle the integrals over $w \ge N$. Clearly, since $w\in L^{2^\ast}$ we also have $w\in L^{q^\ast}$; so $\int_{w> N} w^{q^\ast} \to 0$ as $N\to\infty$. However, I do not know whether
$$
\int_{w > N}\left(\beta N^{\beta-1}w\right)^{q^\ast} \to 0
$$
as $N\to\infty$ due to the multiple $N^{(\beta-1)q^\ast}$.
Any advice on how to handle this integral (as well as the integral $\int_{w > N}\left(\beta N^{\beta-1}w - \beta N^\beta +N^\beta-k^\beta\right)^{2^\ast}$) would be appeciated. I thought of trying to combine them but I am not sure how to do that either.

Equation 8.3
\begin{equation}
    Lu=D_i(a^{ij}(x)D_ju+b^i(x)u)+c^i(x)D_iu+d(x)u
\end{equation}.
Equation 8.29
\begin{equation}
    \begin{aligned}
        A^i(x,z,p) &= a^{ij}(x)p_j + b^i(x)z - f^i(x),\\
        B(x,z,p) &= c^i(x)p_i + d(x)z - g(x)
    \end{aligned}
\end{equation}
Equation 8.30 For $v\ge 0, v\in C_0^1(\Omega)$
\begin{equation}
     \int_{\Omega}\left(D_ivA^i(x,u,Du)-vB(x,u,Du)\right)dx \le(\ge,=)0
 \end{equation}
Equation 8.32
\begin{equation}
    \bar z=|z|+k,\qquad \bar b=\lambda^{-2}(|b|^2+|c|^2+k^{-2}|f|^2)+\lambda^{-1}(|d|+k^{-1}|g|)
\end{equation}
Equation 8.33
\begin{align}
p_iA^i(x,z,p)  & \ge \frac{\lambda}{2}(|p|^2-2\bar b\bar z^2)  \\
      | \bar zB(x,z,p)  |     &\le \frac{\lambda}{2}\left( \epsilon|p|^2+\frac{\bar b}{\epsilon}\bar z^2\right)
\end{align}
Any help will be greatly appreciated
Answer: I feel a little silly but I'll leave my answer here anyway.
If we don't split the integral between where $w \ge N$ and $w<N$, we can just apply the monotone convergence theorem to
$$
f_N(x) = \left[\mathbb{1}_{w\le N}\left(w^\beta - k^\beta\right) + \mathbb{1}_{w>N}\left(\beta N^{\beta-1}w - \beta N^\beta + N^\beta - k^\beta\right)\right]^{2^{\ast}}.
$$
Indeed, $(f_N)$ is an increasing sequence of non-negative functions converging pointwise to $\left(w^\beta - k^\beta\right)^{2^\ast}$.
Same idea on the right-hand side.


Proving definiteness of matrix implicates the sign of diagonal

Question: Let $A\in \mathbb R ^{n\times n}$ be positive definite. Prove that this implicates that all elements on the main diagonal are positive.
So $A$ is positive definite means, that $v^T Av>0$, where $v^T=[v_1,...,v_n]$.
I got that:
$$
v^T Av=(v_1^2A_{1,1}+v_1 v_2 A_{2,1}+...+v_1 v_n A_{n,1})+...+(v_1 v_n A_{1,n}+...+v_n^2 A_{n,n})
$$
The only thing I noticed is that coefficient by $A_{i,i}$(so the main diagonal) is always $v_i^2$, so if one of the elements on the main diagonal were non positive, there would be at least one non-positive factor in the equation. Still I have no idea why would this imply that they all must be positive. Any tips?
Comment: Please do NOT write the element of the matrix A in row i and column j as A with subscripts i, j. This notation idenotes a co-factor. Instead, use lower case a with subsripts
Answer: Choose $v = e_j$, the $j$th column of the identity matrix to see that $a_{jj} = e_j^T A e_j > 0$.


How can I delete a row from the database?

Question: I would like to delete all rows from the database that is older than 1 month. How can I do that in Drupal 8?

DELETE FROM myTable WHERE MyColumn < DATEADD(MONTH, -1, GETDATE())
Answer: You can do it by using this code
<code>$query = \Drupal::database()->delete('table');
$query->condition('some column', 'some condition');
$query->execute();
</code>


Buzzer between free-throws

Question: In the NBA, I regularly notice a short buzzer sound played between the first and the second free-throw. What's the reason for this?
Answer: Buzzer is to note that subs are coming in.
Buzzer can be used for any substitution.   I can not find any referee notes for the NBA regarding in-between free throws (probably because they would be in the notes for person running clock).
Anecdotally I refereed since I was 11 years old.   The scorer's table will hit the buzzer to alert the referee OR players for any substitution.   Meaning if I call a foul and at the scorer's table, I might motion the substitution in before I get set and before the rotating referee in-bounds the ball.
The scorer's table can hit the buzzer there.  They usually don't (pee-wee through small time college).
The most common reason the scorer's table will hit buzzer for subs are:

Referee missed seeing the subs and about to start play.   For sure the number one reason outside the NBA.   There are some gyms where kids are on a knee in front of their bench (not scorer's table) so it is hard to infer they are coming in.   Been in so many gyms (even small colleges) where I was constantly asking players if they were subbing - "no talking to coach" so you tend to stop looking and wait to hear.   The scorer's table if working properly will buzz the referee so they stop and motion subs in.
Players not paying attention.   Referee motions for subs and players just sit there.   Little buzz gets them going.
And in some gyms they do the automatic 2nd free throw buzz.   Maybe 1 out of 5 gyms in my area.   I think this is just to get things moving faster.   Ref and player hears the buzz, player runs in, other player runs off.   With no buzz then ref holds up hand walks in the vicinity of subs and motions them in, given they are paying attention.   It is faster for sure.  But we are talking about maybe shaving off 3-4 seconds if that.   I can see the NBA doing it because that is for sure the 2nd worst part of watching an NBA game is the 60 seconds for 2 free throws (the worst is the 10 timeouts in the last two minutes).
Some people running the clock just love to hit the buzzer.  I mean seriously I will work a game where I hear the buzzer at the end of each quarter and that's it.   The next game the guy hits it 40 times.
This goes along with number 4 and not applicable to the NBA.   Some smaller gyms have bad buzzers.   Some are excruciatingly loud and some sound low or weird.   So the scorer's table might refrain from using them unless they have to.  Those gyms you will get the "hey ref" instead of the buzzer.  Note that the buzzer is much more efficient as some gyms I might not hear a "hey ref" even if yelled from 20 feet (ref's are also conditioned to not listen to any phrase from the stands with the word "ref").
For specifically the NBA I think the buzzer serves two purposes - make things quicker and alert fans.

Also in case you have another follow-up.   In a two free throw situation you only can sub on second free throw, three free throw only on third, and one free throw or a 1 and 1 you can sub before the first.  This is solely so there is only one set of subs per stop in play.   If you are a new referee and let in subs on the first free throw - it is very natural to do it when you are giving scorer's table the number of the player committing the foul and subs are 3 feet from you - and then the coach decides to put in another sub on the second free throw... you will get majorly dinged in any critique if someone is watching your game.

Buzzer between free-throws


Global Window Trigger after a transformation in Apache Flink

Question: I am trying to implement window triggers in flink, which will fire if the average value is higher than a threshold.
The streaming data has student's name & mark seperated by ,. The window has to be triggered, if the average mark of the student cross 90 irrespective of number of attempts.
example data:
Fred,88
Fred,91
Wilma,93
.
.

Current Flink Code:
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.api.windowing.triggers.Trigger.TriggerContext
import org.apache.flink.streaming.api.windowing.triggers.{CountTrigger, PurgingTrigger, Trigger, TriggerResult}
import org.apache.flink.streaming.api.windowing.windows.{GlobalWindow, Window}

case class Marks(name : String, mark : Double, count : Int)

class MarksTrigger[W <: Window] extends Trigger[Marks,W] {

  override def onElement(element: Marks, timestamp: Long, window: W, ctx: TriggerContext): TriggerResult = {
    if(element.mark > 90) TriggerResult.FIRE  // fire if avg mark is > 90
    else TriggerResult.CONTINUE
  }

  override def onProcessingTime(time: Long, window: W, ctx: TriggerContext): TriggerResult = {
    TriggerResult.CONTINUE
  }
  override def onEventTime(time: Long, window: W, ctx: TriggerContext): TriggerResult = {
    TriggerResult.CONTINUE
  }

  override def clear(window: W, ctx: TriggerContext) = ???
}

object Main {
  def main(args: Array[String]) {

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    val data = env.socketTextStream("localhost", 9999)

    val fdata = data.map { values =>
      val columns = values.split(",")
      Marks(columns(0), columns(1).toDouble, 1)
    }

    val keyed = fdata.keyBy(_.name).
      window(GlobalWindows.create()).
      trigger(new MarksTrigger[GlobalWindow]()). // TODO

    keyed.print()
    env.execute()
  }
}

Calculating average:
Tried the following in batch mode
case class Marks(name : String, mark : Double, count : Int)

val data = benv.fromElements(("Fred", 88.0), ("Fred", 95.0), ("Fred", 91.0), ("Wilma", 93.0), ("Wilma", 95.0), ("Wilma", 98.0))

data.map(x => (x._1, x._2, 1)).groupBy(0).reduce { (x, y) =>
    (x._1, x._2 + y._2, x._3 + y._3)
}.map(x => Marks(x._1, x._2/x._3, x._3)).collect

How do i tie these together? should .window() and .trigger() be called before calculating average or average calculation should be done inside onElement()?
Answer: I figured out the solution
import org.apache.flink.api.scala.ExecutionEnvironment
import org.apache.flink.streaming.api.scala._
import org.apache.flink.streaming.api.windowing.assigners.GlobalWindows
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.api.windowing.triggers.Trigger.TriggerContext
import org.apache.flink.streaming.api.windowing.triggers.{CountTrigger, PurgingTrigger, Trigger, TriggerResult}
import org.apache.flink.streaming.api.windowing.windows.{GlobalWindow, Window}

class MarksTrigger[W <: Window] extends Trigger[Marks,W] {

  override def onElement(element: Marks, timestamp: Long, window: W, ctx: TriggerContext): TriggerResult = {
    //trigger is fired if average marks of a student cross 80
    if(element.mark > 90) TriggerResult.FIRE
    else TriggerResult.CONTINUE
  }

  override def onProcessingTime(time: Long, window: W, ctx: TriggerContext): TriggerResult = {
    TriggerResult.CONTINUE
  }
  override def onEventTime(time: Long, window: W, ctx: TriggerContext): TriggerResult = {
    TriggerResult.CONTINUE
  }

  override def clear(window: W, ctx: TriggerContext) = ???
}

case class Marks(name : String, mark : Double, count : Int)

object Main {
  def main(args: Array[String]) {

    val env = StreamExecutionEnvironment.getExecutionEnvironment
    val data = env.socketTextStream("localhost", 9999)

    // data is obtained in "name,mark" format
    val fdata = data.map { values =>
      val columns = values.split(",")
      (columns(0), columns(1).toDouble, 1)
    }

    // calculating average mark and number of exam attempts
    val keyed1 = fdata.keyBy(0).reduce { (x,y) =>
      (x._1, x._2 + y._2, x._3 + y._3)
    }.map( x => Marks(x._1, x._2 / x._3, x._3))

    val keyed = keyed1.keyBy(_.name).
      window(GlobalWindows.create()).
      trigger(PurgingTrigger.of(new MarksTrigger[GlobalWindow]())).
      maxBy(1)

    keyed.print()
    env.execute()

  }
}


If previous li has more height some white space is coming

Question: I have some
 that look like some list of boxes.
screenshot

list

css
#selectable {
      list-style-type: none;
      margin: 0;
      padding: 0;
      width: 450px;
}
#li .handle {
      background: #f8f8f8;
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      padding:8px;
}
#selectable li {
      margin: 3px;
      padding: 1px;
      float: left;
      width: 100px;
      height: 80px;
      font-size: 4em;
      text-align: center;
}

Dynamically I will change the height of some li it messed up
See  fiddle. Here i am merging selected boxes. Try selecting 4 and 8 you will see the issue.
screenshot

What I need is:

I want to fill the empty white spaces with 4 and 5
Selection should be applicable only if boxes has same width(if vertical selection) and only boxes has same height (if horizontal selection)
Comment: Tried you `display:inline-block;`? The `li`s will behave like regular `div`s.
Comment: please see my updated question and fiddle
Comment: This is not a question, it's request to write your code for you. Alright, 1 could be a question if worded differently, but 2 simply is a request to do work for you...
Comment: Have you see my answer ?
Answer: try with masonry
My codepen (it is one fork of the official example)
Simple result (without js button)
Your jsfiddle modify (when u click on apply. apply mansonry in var merge if u want result when u drag and drop)
HTML

Masonry - destroy

<button id="toggle-button">Toggle Masonry</button>

1

2

3

4

5

6

JS
// http://masonry.desandro.com/masonry.pkgd.js added as external resource

docReady( function() {

  var container = document.querySelector('.masonry');
  var button = document.querySelector('#toggle-button');
  var msnry = new Masonry( container, {
    columnWidth: 200

 });

  var isActive = true;

  eventie.bind( button, 'click', function() {
    if ( isActive ) {
      msnry.destroy();
    } else {
      msnry = new Masonry( container );
    }
    isActive = !isActive;
  });

});

Comment: Hi ColoO,Thanks for your answer.In http://jsfiddle.net/kBjBc/9/
 I select the boxes and click "Apply" I am getting exactly what is required, but when I select other box for second time (without refreshing the screen) the whole layout is broken.It is half way done!! Please help me on this.
Comment: i don't understand what you want to do in your project but if you want add masonery when you drage and drop [http://jsfiddle.net/kBjBc/13/](http://jsfiddle.net/kBjBc/13/). you have always the same problem but the mansonery is alaways activated. You need to see where your code isn't compatible with masonery (i don't find :p maybe html syntaxe ? [masonery add property in style=""] )
Comment: finally, i can propose one [test](http://jsfiddle.net/kBjBc/15/). i press apply i start masonery, the second press "apply" destroy masonery. So before each action, you must remove masonery with this line msnry.destroy();. After u don't have bug. Good luck ;)
Answer: Sounds like what you need is an jQuery tile grid plugin. Don't think you'll be able to accomplish this only using HTML and CSS, unfortunately.
Comment: @NishamMahsin That didn't actually clarified anything, unfortunately. What's the fiddle soppose to do? Can you explain how your code works or what your trying to accomplish?
Comment: i am selecting boxes and merging selected boxes
Comment: @NishamMahsin Ah, now I understand! What you need to do then is to move the actual DOM elements around to the right order, so they float the right way to fill up the space.
Comment: .yes. when u merge 4 and 8 ,  the boxes 5,6,7,10,11,12 coming down. but i dont want this.
Comment: Yeah, I understand that know. Not sure you can accomplish this with a `` list and CSS. You might need to build it as a table and calculate the correct `colspan` and `rowspan` for each `` on each merge. Needs a bit of thinking and code I admit. But the best solution I can think of right now.
Answer: Instead of a list, I'm using a table to use colspan and rowspan. The JavaScript is fully commented, please ask if something is unclear.
Fiddle here.
HTML:

        1
        2
        3
        4

        5
        6
        7
        8

        9
        10
        11
        12

CSS:
#selectable {
    width: 400px;
    height: 200px
}

.xioCss{
    width: 25%;
    height: 33%;
    border: 1px solid black;
    text-align: center;
    font-size: 25px
}

#selectable .ui-selecting {
    background: #FECA40;
}

#selectable .ui-selected {
    background: #F39814;
    color: white;
}

JavaScript:
$("#selectable").selectable({
    filter: "td",
    stop: function(){
        var $selected = $(".ui-selected");

        if( $selected.length < 2 ){
            //Cannot combine when there are less than 2 selected
            return false;
        }

        //Remove strange acting hidden elements
        $selected.each(function(){
            if($(this).is(":hidden")){
                $selected = $selected.not($(this));
            }
        });

        //Save all the ids of the selected elements in an array
        var ids = $selected.map(function(){
            return parseInt($(this).attr("id"));
        }).get();

        //Go through all the elements
        //and check if an element is hidden under one of the selected elements.
        //If so, also select that element.
        var $allElements = $(".ui-selectee");
        for (var i = 0; i < $allElements.length; i++){
            if(ids.indexOf($allElements[i].hiddenUnder) >= 0){
                $selected = $selected.add($allElements.eq(i));
            }
        }

        //Comparing with the first td: vertical or horizontal
        var vertical = 0;
        var horizontal = 0;
        for ( var i = 0; i < $selected.length; i++ ){
            //Checking: horizontal, has it the same tr as parent?
            if( $selected[0].parentNode === $selected[i].parentNode ){
                //Same tr as parent, so horizontal
                horizontal++;
            }

            //Checking: vertical, has it the same child index?
            if($selected.eq(0).index() === $selected.eq(i).index()){
                //Same child index, so vertical
                vertical++;
            }

        }

        //If the selected elements are a block,
        //The product of horizontal and vertical should equal the amount of selected elements.
        if(horizontal*vertical !== $selected.length){
            return false;
        }

        //Hide all the td except the first on (skip 0),
        //and save the element they are hidden under.
        for (var i = 1; i < $selected.length; i++){
            $selected.eq(i).hide();
            $selected[i].hiddenUnder = ids[0];
        }

        //And set the colspan and the rowspan of the first one
        $selected.eq(0).attr({
            colspan: horizontal,
            rowspan: vertical
        });
    }
})

Comment: Some second merges did indeed not work due to underestimated hidden elements, but they should be fully cooperating now.
Answer: I think the best way to achieve this is to use the jquery plugin masonry.min.js
Its better to use the width in the percentage format rather than in fixed pixels.
Suppose you have a grid with 4 columns

 content 1

 content 2

 content 3

 content 4

CSS
.item { width:25%; }
.w1 { width:50%; }
.w2 { width:25%; }
.w3 { width:75%; }
.w4 { width:100%; }

Then the elements will be in the grid and number of elements in each row varies according to the width of the elements.


Pegar os valores das colunas da linha clicada e passar inputs

Question: Aqui é a função para pegar o valor da linha da tabela, e passar para inputs, se eu pego as linhas que foram carregadas do banco não da erro mas quando, insiro um novo item na tabela, ai pego o valor da 2 coluna da linha, no teste    alert exibi normal texto mas quando passo para os inputs, os campos se misturam, nunca vi nada igual, o input descrição aparece com array dentro.

Descrição do item
        <input type="text" id="resultDescricao" name="resultDescricao" readonly >

Modelo:
        <input type="text" id="modelo" onchange="montarDescricao()" style="text-transform: uppercase; display: inline-block" onkeyup="montarDescricao()">

Obs:
        <input type="text" name="obs_item" id="obs_item" onchange="montarDescricao()" style="text-transform: uppercase; display: inline-block" onkeyup="montarDescricao()">

        <input type="hidden" id="obs" name="obs">

Medida:
        <input type = "text" id = "medida" onchange = "montarDescricao()"  placeholder="0,00" style = "text-transform: lowercase; display: inline-block" onkeyup = "montarDescricao()">

Braço esq.:
        <input type="text" id="bracoesq" onchange="montarDescricao()" style="text-transform: uppercase" onkeyup="montarDescricao()">

Módulo
        <input type="text" name="modulo" id="modulo" onchange = "montarDescricao()" placeholder="2x0,00"style = "text-transform: lowercase; display: inline-block" onkeyup = "montarDescricao()">

Braço dir.:
        <input type="text" id="bracodir" onchange="montarDescricao()" style="text-transform: uppercase"  onkeyup="montarDescricao()">

        Revestimento
        <select name="revestimento" id="revestimento" class="revestimento" onChange="montarDescricao()">
            <option value="">  Selecione um Revestimento</option>
            <?php foreach ($revestimento_list as $rl): ?>
                <option value="<?php echo $rl['id'] ?>"><?php echo $rl['nomedesc']; ?></option>
            <?php endforeach; ?>
        </select>

Vlr. unitário
        <input type="text" name="vlr_unitario" value="R$ 0,00" id="vlr_unitario" data-prefix="R$ " class="dinheiro" >

Qtde
        <input type="number" name="qtde" id="qtde" onkeyup="so_numero(this)" value="1" min="1" >

Qtde módulos
        <input type="number" name="num_modulos" id="num_modulos"  value="2" min="1" />

        <input type="button" onclick="addProd()" id="add_prod" value="adicionar produto" style="background-color: #faac58"/>

        <input type="text" name="json_prod" id="json_prod">
        <?php
    endforeach;
    ?>
</fieldset>
</fieldset>

    ID
    Nome do Produto
    Quant.
    Módulos
    Obs.
    Preço Unit.
    Sub-Total
    Ações

 function pegar_valor_linha_tabela_editar(elemento) {
var id = $(elemento).closest('tr').find('td').eq('0').text().trim();  // recebe id
var descricao = $(elemento).closest('tr').find('td').eq('1').html();  // recebe descriçao completa
var qtde = $('input[name="quant[' + id + ']"]').val().trim(); // recebe quantidade
var num_modulos = $(elemento).closest('tr').find('td').eq('3').text().trim(); // recebe numero de modulos
var obs_item = $(elemento).closest('tr').find('td').eq('4').text().trim(); // recebe observacao
var vlr_unitario = $(elemento).closest('tr').find('td').eq('5').text().trim(); // recebe valor unitario
OBJ = $(elemento).closest("tr"); //recebe objeto da linha

if (id === 0) {
    return;
} else {
    $('#id').val(id);

    //inicio quebra descriçao
    //aqui e coluna 2 da tabela eu pego e divico essas descrição
    var descricaoArray = descricao.split('[');
    var modelo = descricaoArray[0].trim();
    var medida = descricaoArray[1].trim();
    var bracoesq = descricaoArray[2].trim();
    var modulo = descricaoArray[3].trim();
    var bracodir = descricaoArray[4].trim();
    var revestimento = descricaoArray[5].split(']');

   //fim do quebra descrição

    $('#resultDescricao').val(descricao);
    $('#modelo').val(modelo);
    $('#medida').val(medida.replace(']', ''));
    $('#bracoesq').val(bracoesq.replace(']', '').replace('BRE', ''));
    $('#modulo').val(modulo.replace(']', ''));
    $('#bracodir').val(bracodir.replace(']', '').replace('BRD', ''));
    $('#revestimento option:contains(' + revestimento[0] + ')').prop('selected', true);
    $('#obs_item').val($.trim(obs_item));
    $('#vlr_unitario').val(vlr_unitario.replace(' ', ''));
    $('#qtde').val($('input[name="quant[' + id + ']"]').val());
    $('#num_modulos').val(num_modulos);
    excluirProd(elemento);
}

}
Modelo de descrição
// CALIFORNIA [2,90] [BRE25] [3x80] [BRD25] [ARTIGO: 1.000 - COR: 02] - COM MAIS PUXES

Quando da erro
// 3 [CALIFORNIA [2,90] [BRE25] [3x80] [BRD25] [ARTIGO: 1.000 - COR: 02]] [BRE] [ 2] [BRD ] [ R$ 0,00]

Campo medida
// CALIFORNIA [2,90] [BRE25] [3x80] [BRD25] [ARTIGO: 1.000 - COR: 02]

Mesmo no alert exibindo que os dados estão sendo passados para os inputs corretamente, exibi tudo errado, nunca vi isso variável pegar valor sem ser declarado
Função para add produtos
function addProd() {
if ($('#modelo').val() === '') {
    alert('Informe um Modelo !');
    return;
}
if ($('#revestimento').val() === '') {
    alert('Selecione um Revestimento !');
    return;
}
if ($('#num_modulos').val() === '') {
    alert('Selecione a Quantidade de Módulos !');
    return;
}
if ($('#bracoesq').val() === '') {
    alert('Informe a medida Braço Esquerdo !');
    return;
}
 if ($('#bracodir').val() === '') {
    alert('Informe a medida Braço Direito !');
    return;
}
var products_table = document.getElementById('products_table');
var id = products_table.rows.length;
var name = document.getElementById('resultDescricao').value;
var price = document.getElementById('vlr_unitario').value.replace(/[ R|$|.]/gi, '').replace(/[,]/gi, '.');
var qtde = document.getElementById('qtde').value;
var num_modulos = document.getElementById('num_modulos').value;
var obs_item = document.getElementById('obs_item').value;

subtotal = price * parseInt(qtde);
subtotal = ("R$ " + number_format(subtotal, 2, ',', '.'));
price = ("R$ " + number_format(price, 2, ',', '.'));

incluir_produto();
document.getElementById('resultDescricao').value = "";
document.getElementById('modelo').value = "";
document.getElementById('vlr_unitario').value = 'R$0,00';
document.getElementById('bracoesq').value = "";
document.getElementById('bracodir').value = "";
$("#revestimento").val($("#revestimento option:first").val());
document.getElementById('qtde').value = "1";
document.getElementById('medida').value = "";
document.getElementById('modulo').value = "";
document.getElementById('obs_item').value = "";

if ($('input[name="quant[' + id + ']"]').length !== 0) {
    id = parseInt(id) + 1;

}

if ($('#id').val() != '') {
   var tr =
   '
' +
   '' + id + '	' +
   '' + name + '	' +
   '' +
   '<input style="width:50px;" type="number" name="quant[' + id + ']" id="quant[' + id + ']" class="p_quant" value="' + qtde + '"  onkeyup="updateSubtotal(this)" onchange="updateSubtotal(this)" data-price="' + price + '" />' +
   '	' +
   ' ' + num_modulos + '	' +
   ' ' + obs_item + '	' +
   ' ' + price + '	' +
   '' + subtotal + '	' +
   '\n\
           	' +
   '
';
   OBJ.prev().after(tr); //colocar o novo tr antes deste
   OBJ.remove();
   var contador = 1;
   $(".classeDaLinha").each(function () {
             $(this).find("#id").html(contador);
           $(this).find(".p_quant").prop("name", "quant[" + contador + "]");
         contador++;
   });
   $(OBJ).closest('tr').show();
   $('#id').val('');
} else {
    var tr =
    '
' +
    '' + id + '	' +
    '' + name + '	' +
    '' +
    '<input style="width:50px;" type="number" name="quant[' + id + ']" id="quant[' + id + ']" class="p_quant" value="' + qtde + '"  onkeyup="updateSubtotal(this)" onchange="updateSubtotal(this)" data-price="' + price + '" />' +
    '	' +
    ' ' + num_modulos + '	' +
    ' ' + obs_item + '	' +
    ' ' + price + '	' +
    '' + subtotal + '	' +
    '\n\
            	' +
    '
';
$('#products_table tbody').append(tr);
}
updateTotal();
preencherJason();
}

Aqui requisição pra carregar os itens do banco e criar as linhas
function carregar_itens_pedido(id_pedido)
{
 $.ajax
        ({
            type: 'POST',
            dataType: 'json',
            url: BASE_URL + '/pedidos/carregar_itens_pedido',
            data: {id_pedido: id_pedido},
            success: function (arrayRetorno)
            {
                $("#products_table tbody").empty();
                tr = "";
                for (var index in arrayRetorno) {
                    subTotal = arrayRetorno[index].vlr_unitario * arrayRetorno[index].vlr_unitario.qt;
                    id = arrayRetorno[index].id;
                    num_sofa = arrayRetorno[index].num_sofa;
                    name = arrayRetorno[index].nomedesc;
                    price = arrayRetorno[index].vlr_unitario;
                    qtde = arrayRetorno[index].qt;
                    num_modulos = arrayRetorno[index].num_modulos;
                    obs_item = arrayRetorno[index].obs_item;

                    subtotal = price * qtde;
                    subtotal = ("R$ " + number_format(subtotal, 2, ',', '.'));
                    price = ("R$ " + number_format(price, 2, ',', '.'));

                    if (qtde === null) {
                        qtde = '';
                    }
                    tr +=   '
' +
                    '' + id + '	' +
                    '' + name + '	' +
                    '' +
                    '<input style="width:50px;" type="number" name="quant[' + id + ']" id="quant[' + id + ']" class="p_quant" value="' + qtde + '"  onkeyup="updateSubtotal(this)" onchange="updateSubtotal(this)" data-price="' + price + '" />' +
                    '	' +
                    ' ' + num_modulos + '	' +
                    ' ' + obs_item + '	' +
                    ' ' + price + '	' +
                    '' + subtotal + '	' +
                    '\n\
                    	' +
                    '
';
                }
                $('#products_table tbody').append(tr);
                updateTotal();
                preencherJason();
             }
        });
      }

Comment: O melhor será mesmo criar um [exemplo mínimo verificável](https://pt.stackoverflow.com/help/mcve) juntando algum html para que seja possível de testar e ver o problema em si. Veja [neste fiddle](https://jsfiddle.net/#&togetherjs=3REa548L8v) como o código que tem obtêm os valores dos `tds` funciona, assumindo que estão como html
Comment: Eu alterei aqui, mas o erro deve estar na hora de quebrar a descrição
Comment: Posta o HTML, asism fica mais fácil para simularmos aqui
Comment: Já postei o html
Comment: https://jsfiddle.net/ramoty/971yLqpL/20/#&togetherjs=3REa548L8v @Isac
Answer: Vlw pela ajuda ai, o erro estava em um laço pra criar tabela que exibia os itens do banco já cadastrados, vou posta o código que usei pra solucionar.
FireDebug salvando novamente.
function pegar_valor_linha_tabela(elemento) {
var modelo = $(elemento).closest('tr').find('td').eq('0').html().trim();
var medida = $(elemento).closest('tr').find('td').eq('1').text().trim();
var bracoesq = $(elemento).closest('tr').find('td').eq('2').text().trim();
var modulo = $(elemento).closest('tr').find('td').eq('3').text().trim();
var bracodir = $(elemento).closest('tr').find('td').eq('4').text().trim();
var revestimento = $(elemento).closest('tr').find('td').eq('5').text().trim();
$('#resultDescricao').val(modelo + ' [' + medida + '] [BRE' + bracoesq+ '] [' + modulo + '] [BRD' + bracodir + '] [' + revestimento + ']');
$('#modelo').val(modelo);
$('#medida').val(medida);
$('#bracoesq').val(bracoesq);
$('#modulo').val(modulo);
$('#bracodir').val(bracodir);
$('#revestimento option:contains(' + revestimento + ')').prop('selected', true);
var botao = document.getElementById("modulo");
botao.click();
}


can I switch one collinear predictor onto dependent variable position in a model?

Question: I have a situation where my current model looks like MODEL 1: C ~ A * B + (1|random effect, that is C is predicted by  A and B and their interaction and all 3 variables are continuous variables.
I am primarily analyzing it as a multilevel mixed model. However, I noticed that A & B when aggregated over all levels of the random effect turn out to be highly negatively correlated (about -.90), raising concerns of multicollinearity, however, the predicted correlation in the multilevel model ranges from -.60 to -.75 and when I compute a vif measure of MODEL 1, all vif indicators are bellow 2.
The estimates of model 1 show an effect of A (estimate 0.364, p<.001) but not B (0.0331, p=.4) and a significant A*B interaction: estimate 0.132, p<.001)
However, when  I test them individually e.g. (MODEL 2: C ~ A + (1|random effect or MODEL 3: C ~  B + (1|random effect both A and B appear significant and with opposite directions as expected. standardized estimate for A is 0.33571 and for B is -0.15296
This is primarily a correlational analysis, as there is no real causal relation or order between A, B and C in my case and I am interested in all 3 variables (theoretically i. Given that the correlation of A or B with C is negligible <.2, I am wondering if it would be sound to reverse the predictor of interest (A) into a DV position, so running a model like the one below
MODEL 4: A ~ C*B +  (1|random effect)
Would this be a sound way to deal with collinearity in this case, and would a result from this model allow me to more confidently accept or interpret the results from model 1, mainly the interaction and the relation between A & C without concerns for the collinear predictors in model 1?
Thanks!
Answer: A couple of points:

The fact that most of your diagnostics come back without issue is exactly why multicollinearity is so dangerous-- it can make your model do strange things that really can't be "caught" by standard diagnostics.

Multiple Regression of any kind is by definition directional. E.g (a ~ b * c) is fundamentally different than (b~a * c). The just aren't the same thing and have totally different interpretations. If you care about A~ C * B, then sure, run the model. But it isn't the same as your initial analysis.

If really all you care about is the pairwise relationships, then it probably makes more sense to just do pairwise t-tests with a p-value adjustment, and maybe visualize the correlation. Without some sort of hypothesized directional relationship, linear models aren't really your friend here in my opinion.
Comment: Thank you for your answer. Just to add (if it is useful to clarify) that in this case, A & C theoretically represent the same underlying construct just measured in different ways, that's why I wondered whether an interaction between A*B or C*B could be taken as "equivalent". For example, A and C are supposed to represent the intensity of a subjective experience, but A is measured subjectively (via self-report), whereas C is measured using bodily signals and sensors.
Comment: In this case, you may consider an additive dependent variable. In other worse, model (A+C) ~ B + Random Effect


HTML text rendered backwards... but only partially (1., 2., etc.)

Question: When text inside of an  tag is rendered with a preceding number, the number is sent to the back of the string, and its punctuation is rendered backwards.
HTML:
1. Step One

Renders as:
 Step One .1

This might be weird to try and imagine, so I have included a link to the screenshot:
HTML, CSS, & Rendered result:
https://i.stack.imgur.com/bRmcV.jpg
I'm at a bit of a loss for what could possibly cause this. My theory is that there is some CSS property being inherited from elsewhere. I have been slowly removing chunks of CSS in an effort to find the guilty party, but so far no luck. This renders 100% properly on other sections of the website that use different style sheets. I was not the original author of the style sheets, so it has been difficult to pin-point the possible source.
I would greatly appreciate if anyone has seen anything similar and might be able to point me in the direction of CSS properties that could possibly cause this, or if it's something else entirely.
Comment: What is your css code?  do you have any RTL  (right to left) commands?
Comment: Alternatively to CSS, look for `dir="rtl"` attributes in your HTML source.
Comment: Have you tried your browser developer tools? They will tell you exactly which css is used for a particular element.
Comment: @briansol I realize in hindsight that you meant css RTL - I apologize for assuming you were talking about the HTML attribute. Thank you for your help, you were correct!
Comment: @briansol I can post the CSS directly related to these elements, but on a page with no other style sheets it is rendering properly. Trying to dig through all other CSS above this has been a headache and probably not a good idea to dump. I know it's not ideal, but I'm not aware of much of an alternative. I am open to suggestions, of course!
Comment: @Tomalak none of my current HTML has it. I appreciate the idea though!
Comment: @the_lotus in the screenshot, the computed css is taken from dev tools. I believe there is some css affecting the rest of the page (not just directly these elements) that is causing. There is nothing particularly un-ordinary about the styles you see on the computed, as well as the broken-out styles.
Comment: @veratti Use the "computed style" tab to track down any `text-direction` that might be in effect for your element in question. It will point you to the exact location of the responsible CSS file.
Comment: @Tomalak you were correct about that property being the culprit (direction: rtl)! I was able to find that the CSS property with your guidance, you are my hero - I had seen posts about the attribute on the element, but didn't think to look for "direction" in the CSS. Thanks again!!!!
Answer: Thank you @Tomalak, @briansol and @the_lotus for helping me track this one down.
There was a CSS property being inherited that was causing the text to render this way. Upon viewing inherited computed styles, I saw:
direction: rtl;

The correct property setting would be:
direction: ltr;

Thanks again for your help!