text:
Q: Android : Activity button shows up on fragment I have a simple application, with an Activity calling a Fragment.
Question I have is .. why is the Activity's button showing up on the Fragment ?
Seems to be a very simple problem .. just not able to pin point the issue !!
Activity screenshot :

Fragment Screenshot :

Notice that Activity's SUBMIT button shows up on the Fragment, but the TextView and EditText get hidden. Why ??
Activity :
package com.example.deep_kulshreshtha.toddsyndrome;

import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputEditText;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private TextInputEditText inputEditText;
    private EditText editText;
    private ToddSyndromeDBHelper dbHelper;
    private SQLiteDatabase db;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayShowHomeEnabled(true);
//        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

//        inputEditText = (TextInputEditText) findViewById(R.id.lastNameEditText);
        editText = (EditText) findViewById(R.id.editText);

        Button submitButton = (Button) findViewById(R.id.submitButton);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CreateReportFragment fragment = CreateReportFragment.newInstance();

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.content_main, fragment, "CreateFragment");
                transaction.addToBackStack("CreateBackStack");
                transaction.commit();
            }
        });

        dbHelper = new ToddSyndromeDBHelper(this);

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(db != null) {db.close();}
    }

    public SQLiteDatabase getDb(){

        if(db == null) {
//            new ConnectionHelper().execute();
            db = dbHelper.getWritableDatabase();
        }
        return db;
    }

    public void viewPatientReport(View view){

        PatientReportFragment fragment = PatientReportFragment.
                newInstance(editText.getText().toString());

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.content_main, fragment, "SearchFragment");
        transaction.addToBackStack("SearchBackStack");
        transaction.commit();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private class ConnectionHelper extends AsyncTask<Void, Void, SQLiteDatabase>{

        @Override
        protected SQLiteDatabase doInBackground(Void... params) {
            db = dbHelper.getWritableDatabase();
            return db;
        }
    }
}

Activity xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

Content xml :
<?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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="32dp"
        android:fontFamily="cursive"
        android:text="@string/todd_syndrome" />

<!--    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_last_name"
        android:layout_below="@id/headline"
        android:layout_centerHorizontal="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/lastNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />
    </android.support.design.widget.TextInputLayout>-->

    <EditText
        android:id="@+id/editText"
        android:layout_below="@id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_text_hint"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_below="@id/editText"
        android:onClick="viewPatientReport"/>

</RelativeLayout>

Fragment :
package com.example.deep_kulshreshtha.toddsyndrome;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class CreateReportFragment extends Fragment
        implements View.OnClickListener{
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

//    private OnFragmentInteractionListener mListener;
    String name;
    boolean hallucegenicDrugs = false;
    int age;
    String gender;
    boolean migraine = false;

    private EditText editText;
    private Switch switchMigraine;
    private Spinner ageSpinner;
    private RadioGroup group;
    private Switch switchHall;
    private Button saveButton;

    private View.OnClickListener radioListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean checked = ((RadioButton)v).isChecked();
            gender = ((RadioButton)v).getText().toString();
        }
    };

    public CreateReportFragment() {
        // Required empty public constructor
    }

    // TODO: Rename and change types and number of parameters
    public static CreateReportFragment newInstance(/*String param1, String param2*/) {
        CreateReportFragment fragment = new CreateReportFragment();
//        Bundle args = new Bundle();
//        args.putString(ARG_PARAM1, param1);
//        args.putString(ARG_PARAM2, param2);
//        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
//            mParam1 = getArguments().getString(ARG_PARAM1);
//            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_create_report, container, false);

        editText = (EditText) view.findViewById(R.id.createPersonName);
        name = editText.getText().toString();

        switchMigraine = (Switch) view.findViewById(R.id.migraineToggle);
        switchMigraine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                migraine = false;
            }
        });

        ageSpinner = (Spinner) view.findViewById(R.id.ageSpinner);

        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++){ list.add(i); }
        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(getContext(),
                android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        ageSpinner.setAdapter(adapter);
        ageSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                age = (int) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        group = (RadioGroup) view.findViewById(R.id.genderButton);

        RadioButton maleRadio = (RadioButton) view.findViewById(R.id.radioMale);
        maleRadio.setOnClickListener(radioListener);
        RadioButton femaleRadio = (RadioButton) view.findViewById(R.id.radioFemale);
        femaleRadio.setOnClickListener(radioListener);

        switchHall = (Switch) view.findViewById(R.id.switchButton);
        switchHall.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                hallucegenicDrugs = isChecked;
            }
        });

        saveButton = (Button) view.findViewById(R.id.saveButton);
        saveButton.setOnClickListener(this);

        return view;
    }

    @Override
    public void onClick(View v) {
        int syndromePercentage = 0;

        Log.v("Deep", "Patient name : " + name);
        Log.v("Deep", "Has migraine : " + migraine);
        Log.v("Deep", "Patient age : " + age);
        Log.v("Deep", "Patient gender : " + gender);
        Log.v("Deep", "Drugs ? : " + hallucegenicDrugs);

        if(migraine == true){ syndromePercentage += 25; }
        if(age <= 15){ syndromePercentage += 25; }
        if(gender.equals("Male")){ syndromePercentage += 25; }
        if(hallucegenicDrugs == true){ syndromePercentage += 25; }

        SQLiteDatabase db = ((MainActivity)getActivity()).getDb();

        ContentValues values = new ContentValues();
        values.put(PatientTableContract.FeedEntry.COL_NAME_PATIENT_NAME, name);
        values.put(PatientTableContract.FeedEntry.COL_NAME_RISK, syndromePercentage);

        db.insert(PatientTableContract.FeedEntry.TABLE_NAME, null, values);

        Toast.makeText(getContext(), "Data saved successfully !", Toast.LENGTH_SHORT).show();

        editText.setText("");
        switchMigraine.setChecked(false);
        ageSpinner.setSelection(0);
        group.clearCheck();
        switchHall.setChecked(false);
    }

}

Fragment xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.CreateReportFragment"
    android:background="@android:color/white">

    <!-- TODO: Update blank fragment layout -->
    <android.support.design.widget.TextInputLayout
        android:id="@+id/nameLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/createPersonName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />

    </android.support.design.widget.TextInputLayout>

<!--    <TextView
        android:id="@+id/migraineText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/nameLayout"
        android:text="@string/hint1"/>-->

    <Switch
        android:id="@+id/migraineToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hint1"
        android:layout_below="@id/nameLayout"
        android:checked="false"
        android:layout_margin="10dp"
        android:padding="10dp" />

    <TextView
        android:id="@+id/ageText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/migraineToggle"
        android:text="@string/hint2"
        android:layout_margin="10dp"/>

    <Spinner
        android:id="@+id/ageSpinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:prompt="@string/hint2"
        android:layout_below="@id/migraineToggle"
        android:layout_toRightOf="@id/ageText"
        android:layout_margin="10dp"
        android:layout_marginLeft="20dp"/>

<!--    <TextView
        android:id="@+id/genderText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/ageText"
        android:text="@string/hint3"/>-->

    <RadioGroup
        android:id="@+id/genderButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@id/ageSpinner"
        android:checkedButton="@+id/radioMale"
        android:layout_margin="10dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gender ?"
            android:layout_margin="10dp"/>

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Male"
            android:layout_margin="10dp"/>

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Female"
            android:layout_margin="10dp"/>
    </RadioGroup>

<!--    <TextView
        android:id="@+id/hallucinogenicText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/genderText"
        android:text="@string/hint4"/>

    <ToggleButton
        android:id="@+id/hallucinogenicToggle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/hallucinogenicText"
        android:hint="@string/hint4" />-->

    <Switch
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/genderButton"
        android:text="@string/hint4"
        android:checked="false"
        android:layout_margin="10dp"/>

    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/switchButton"
        android:text="Submit"
        android:layout_margin="10dp"/>

</RelativeLayout>

Second fragment xml :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.PatientReportFragment"
    android:background="@android:color/white">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:id="@+id/patientReport"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="40dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</FrameLayout>

Second Fragment :
package com.example.deep_kulshreshtha.toddsyndrome;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.deep_kulshreshtha.toddsyndrome.PatientTableContract.FeedEntry;

public class PatientReportFragment extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private String mParam1;
    private MainActivity activity;

    private String[] projection = {FeedEntry._ID, FeedEntry.COL_NAME_PATIENT_NAME,
            FeedEntry.COL_NAME_RISK};
    private String selection = FeedEntry.COL_NAME_PATIENT_NAME + " = ?";

//    private OnFragmentInteractionListener mListener;

    public PatientReportFragment() {
        // Required empty public constructor
    }

    public static PatientReportFragment newInstance(String param1) {
        PatientReportFragment fragment = new PatientReportFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        TextView textView = (TextView) view.findViewById(R.id.patientReport);

        SQLiteDatabase db = ((MainActivity)getActivity()).getDb();
        Cursor cursor = db.query(FeedEntry.TABLE_NAME,
                projection,
                selection,
                new String[]{mParam1},
                null,
                null,
                null);

        if(cursor.getCount() == 0){
            textView.setText("No data found");
            return /*view*/;
        } else {
            cursor.moveToFirst();
            int riskPercent = cursor.getInt(cursor.getColumnIndex(FeedEntry.COL_NAME_RISK));

            textView.setText("Risk percentage : " + riskPercent );
            return /*view*/;
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_patient_report, container, false);
        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

}

A: I've solved this by wrapping my button inside a LinearLayout.
Probable cause of the issue: It seems Button has higher z-index rendering when it comes to android and thus not wrapping it inside another layout renders the button higher than all other fragments.
<LinearLayout
    android:id="@+id/register_btn_wrapper"
    android:orientation="vertical"
    android:layout_below="@+id/splash_logo_img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <Button
        android:id="@+id/register_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/register"
        android:textSize="@dimen/text_big"
        android:paddingLeft="@dimen/btn_padding"
        android:paddingStart="@dimen/btn_padding"
        android:paddingRight="@dimen/btn_padding"
        android:paddingEnd="@dimen/btn_padding"
        android:layout_gravity="center"
        android:background="@color/app_color" />

</LinearLayout>

Hope this helps.

A: When you bind your view in fragment it is always a better approach to bind it in the method
onViewCreated()
When you bind your view in onCreateView() you will face rendering issues.
So bind your view in onViewCreated() method and the problem should be solved
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.name_of_layout,container,false);
    }

  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
        //bind your view here
    }

A: In the onCreateView of the fragment try adding this line
    View view = inflater.inflate(R.layout.fragment_name, container, false);
    view.setBackgroundColor(Color.WHITE);

I had a similar issue and fixed it using the above lines. Also, don't forget to add android:clickable="true"    to your fragment_layout.xml parent layout.

A: I couldn't find the reason for this issue though but here is a small workaround:
Update the below layouts and try:
Activity xml :
Added a Framelayout:
 <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <include layout="@layout/content_main"/>
    </FrameLayout>

And in MainActivity: Used Framelayout container
 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CreateReportFragment fragment = CreateReportFragment.newInstance();

                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(**R.id.container**, fragment, "CreateFragment");
                transaction.addToBackStack("CreateBackStack");
                transaction.commit();
            }
        });

In Content.xml Added android:layout_marginTop
<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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    android:layout_marginTop="?attr/actionBarSize"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
    tools:showIn="@layout/activity_main">

In fragment_create_report.xml added android:layout_marginTop
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"
    android:background="@android:color/white">

A: I'm not sure if you still need help with this. But basically the fragment and the activity have to be in different layouts.
This is the general structure for it: (you don't have to use the specific layouts I user below)
<RelativeLayout>
    <LinearLayout id="@+id/all_code_relevant_to_activity"></LinearLayout>
    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
    </LinearLayout>
</RelativeLayout>

Basically you want to have your fragment separate from the rest of the code. So basically you could make a <FrameLayout> around your code in Activity.xml and then add your fragment layout by itself inside the <FrameLayout> but outside <android.support.design.widget.CoordinatorLayout>. Or make two sub layouts the split them apart

A: It's so wired to show only SUBMIT button on the top of page. I want to suggest you to add fragment instead of replace. please let me know the result after this.
FragmentTransaction fragmentTransaction = activity.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.content_main, fragment, "SearchFragment");
fragmentTransaction.addToBackStack("SearchFragment");
fragmentTransaction.commitAllowingStateLoss();

A: In your activity xml, add one more element, FrameLayout to host the fragment, like below
<?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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.deep_kulshreshtha.toddsyndrome.MainActivity"
    tools:showIn="@layout/activity_main">

    <TextView
        android:id="@+id/headline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="32dp"
        android:fontFamily="cursive"
        android:text="@string/todd_syndrome" />

<!--    <android.support.design.widget.TextInputLayout
        android:id="@+id/layout_last_name"
        android:layout_below="@id/headline"
        android:layout_centerHorizontal="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/lastNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/edit_text_hint" />
    </android.support.design.widget.TextInputLayout>-->

    <EditText
        android:id="@+id/editText"
        android:layout_below="@id/headline"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_text_hint"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/submit"
        android:layout_below="@id/editText"
        android:onClick="viewPatientReport"/>

   <!-- new layout to host fragment -->
   <FrameLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/fragment_holder"/>

</RelativeLayout>

and add your Fragment to that FrameLayout using.

A: set button property android:translationZ="-3dp" it will work.

A: What helped me is to add android:translationZ="10dp" to the layout that above the Buttons


text:
Q: Proof that if $X$ and $Y$ are continuous random variables that $E[X+Y]=E[X]+E[Y]$, how to apply Fubini's Theorem I'm trying to understand the proof that if $X$ and $Y$ are continuous random variables then $E[X+Y]=E[X]+E[Y]$ from Introduction to Probability Models by Ross.
Let $g(X, Y) = X+Y$ and we compute $E[X+Y]$; then
$E[X+Y]=\int_\mathbb{R}\int_\mathbb{R} (x+y)f(x, y)dxdy$
$=\int_\mathbb{R}\int_\mathbb{R} xf(x, y)dx dy + \int_\mathbb{R}\int_\mathbb{R} yf(x, y)dx dy$
At this point the book says to apply the fact that if $X$ is a continuous random variable with PDF f(x) then for real valued $g$
$E[g(x)]=\int_\mathbb{R}g(x)f(x)dx$
and let $g(x)=x$ for the first integral above. To apply this I need the PDF for $X$ derived from the joint PDF $f(x, y)$ of $X$ and $Y$
The PDF for $X$
$f_X(x)=\int_\mathbb{R} f(x, y) dy$
So now returning to $\int_\mathbb{R}\int_\mathbb{R} xf(x, y)dx dy$ I need to change the order of integration, I'd like to write
$\int_\mathbb{R}\int_\mathbb{R} xf(x, y)dx dy=\int_\mathbb{R} x\int_\mathbb{R} f(x, y) dy dx = \int_\mathbb{R}xf_X(x)dx=E[X]$
I believe I need to apply Fubini's theorem so I need to show that
$\int_\mathbb{R}\int_\mathbb{R} |xf(x, y)|dx dy$ is finite. This isn't really a given and I think if $X$ is Cauchy may not even be defined.
How would I complete this proof?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django 1.7 makemigrations - ValueError: Cannot serialize function: lambda I switch to Django 1.7. When I try makemigrations for my application, it crash. The crash report is:
Migrations for 'roadmaps':
  0001_initial.py:
    - Create model DataQualityIssue
    - Create model MonthlyChange
    - Create model Product
    - Create model ProductGroup
    - Create model RecomendedStack
    - Create model RecomendedStackMembership
    - Create model RoadmapMarket
    - Create model RoadmapUser
    - Create model RoadmapVendor
    - Create model SpecialEvent
    - Create model TimelineEvent
    - Create model UserStack
    - Create model UserStackMembership
    - Add field products to userstack
    - Add field viewers to userstack
    - Add field products to recomendedstack
    - Add field product_group to product
    - Add field vendor to product
    - Add field product to dataqualityissue
Traceback (most recent call last):
  File "manage.py", line 29, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 124, in handle
    self.write_migration_files(changes)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemigrations.py", line 152, in write_migration_files
    migration_string = writer.as_string()
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 129, in as_string
    operation_string, operation_imports = OperationWriter(operation).serialize()
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 80, in serialize
    arg_string, arg_imports = MigrationWriter.serialize(item)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 245, in serialize
    item_string, item_imports = cls.serialize(item)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 310, in serialize
    return cls.serialize_deconstructed(path, args, kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 221, in serialize_deconstructed
    arg_string, arg_imports = cls.serialize(arg)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/writer.py", line 323, in serialize
    raise ValueError("Cannot serialize function: lambda")
ValueError: Cannot serialize function: lambda

I found a note about that here https://code.djangoproject.com/ticket/22892
There is also link to documentation https://docs.djangoproject.com/en/dev/topics/migrations/#serializing-values
But it does not make it clearer for me. The error meassage have not gave me a clue where to look for problem.
Is there way how to detect what line exactly cause the problem?
Any hints?

A: We had this issue with using lambda in the custom field definition.
It is than hard to spot as it is not listed in traceback and the error is not raised on the particular model which uses such custom field.
Our way to fix:

*

*check all your custom fields (even in the 3rd party libraries)

*change the lambda to callable, which is defined in the module (i.e. not in custom field class)

A: It took me a bit of time to figure this out, but a code example of what @Radek suggested.
An example replacing the lambda with a function.
Borken version:
class SomeModel(ParentModel):
    thing_to_export = ArrayField(models.CharField(max_length=50),
                                 default=lambda: ['Default thing'])

Working version:
def default_thing():
    return ['THIS IS A DEFAULT']

class SomeModel(ParentModel):
    thing_to_export = ArrayField(models.CharField(max_length=50),
                                 default=default_thing)


text:
Q: Any way to prevent getUserMedia "Live Broadcast" when applied to a video srcObject inside WKWebView? I'm having some issues with the now available getUserMedia api available in the WKWebView (as of iOS 14.3).
On a page in the webview, I will access the camera using the following code:
navigator.mediaDevices.getUserMedia({
    video: {
        facingMode: "user"
    },
    audio: false
}).then(function(webcamStream) {
    document.querySelector("#video").srcObject = webcamStream; /* this is a HTML video tag available on the page */
}).catch(function() {
    console.log("fail")
});

This... mostly works. Unlike in Safari (and now Chrome), instead of the video element just showing what is in the video track of the webcamStream MediaStream object, it opens up a "Live Broadcast" panel and the video track pauses whenever this is closed. Is there anyway to replicate the behaviour in Safari and Chrome, where there is no panel popup?
Image of the "Live Broadcast" panel
Thanks

A: For Safari iOS web based apps, link: Video Playback on Safari  references that the  element needs to have a playsInLine attribute along with the idea that it won't autoplay unless it is muted and it pauses if it is out of frame. <video id="video" autoplay playsInline muted></video> and the stream may need to stream.play() to get it started.
https://developer.apple.com/documentation/webkitjs
https://developer.apple.com/documentation/webkit/delivering_video_content_for_safari
As for recording, https://webkit.org/blog/11353/mediarecorder-api/ has info for the MediaRecorder interface available in Safari 14.03?  I don't have much info for native iOS apps.

A: I think I have found a solution. You have to set these properties on WKWebViewConfiguration
 to true:

*

*allowsInlineMediaPlayback

*mediaTypesRequiringUserActionForPlayback
Then video will play as expected


text:
Q: Random letters: What is the chance that real words are generated? Suppose that we are just typing random letters with our keyboards and we include space bar. We don't distinguish between capital and lowercase letters. If we do this for a long time, how many of the words will be real words? How should one do this in Mathematica?

A: Just for comparing with Pillsy's answer, let's suppose we generate a uniformly random sequence of a-z and spacebar.
SeedRandom[42];
n = 10^7;
chars = Union[{" "}, CharacterRange["a", "z"]];
p = DictionaryLookup /@ StringSplit@ StringJoin@ RandomChoice[chars, n];

(Length@p - Count[p, {}])/ Length@p // N

(* 0.0071783 *)

2558out of 356352 are "dictionary words"
And these are the relevant lengths distribution taking or discarding duplicates:
Sort@Tally@StringLength@Flatten@p
Sort@Tally@StringLength@Flatten@Union@p

(* {{1, 496}, {2, 1475}, {3, 495}, {4, 83}, {5, 8}, {6, 1}}
   {{1, 1},   {2, 77},   {3, 351}, {4, 82}, {5, 8}, {6, 1}}*)

Select[Flatten@Union@p, StringLength@# > 4 &]
(* {"apnea", "carny", "crony", "hopped", "jacks", "mound", "rhino", "shots", "swags"}*)

A: the probability of a sequence of a given length being a word (as reported by DictionaryLookup):
 p[n_] := p[n] = (ToLowerCase /@
        DictionaryLookup[StringExpression @@ ConstantArray[_, n]] //
             Union // Length)/26^n // N    (* 27^n if spaces are to be included *)
 Show[{
   ListLogPlot[Table[{n, p[n]}, {n, 3, 20}]],
   LogPlot[ 71625 Exp[-3.6 x  ], {x, 5, 20}]}]

numc = 100000;
list = RandomChoice[CharacterRange["a", "z"], numc];
(* for spaces:
list = RandomChoice[Append[CharacterRange["a", "z"], " "], numc]; *)
TableForm[
 res = Table[ {n,
    Flatten[DictionaryLookup[StringJoin[#],IgnoreCase -> True] & /@
       Partition[ list , n, 1]] // Length , numc p[n]} , {n, 3, 20}],
 TableHeadings -> {None,{"Len", "count", "expected"}}]
Print["total words found: ", res[[All, 2]] // Total, " expected: " ,
  numc Sum[p[n], {n, 3, 20}] ];

total words found: 5565 expected: 5632.06

Edit re: .. the prediction in consistently high by almost exactly 3/2..
This was because DictionaryLookup is case sensitive. IgnoreCase -> True fixes it.
I suppose this may be useful to tabulate:
 TableForm[ Table[ {k, Sum[p[n], {n, k, 25}]}, {k, 2, 7}] ,
    TableHeadings -> {None, {"min word", "expected words/length"}}]

including spaces (equal proability as a letter) doesn't affect things much..

and just for fun.. (note DictionaryLookup is pretty liberal with what it considers words )
numc = 1000;
n = 4
list = RandomChoice[CharacterRange["a", "z"], numc]; words =
 IntervalUnion @@
  Reap[MapIndexed[
     If[Length@DictionaryLookup[StringJoin[#], IgnoreCase -> True] ==
        1, Sow[Interval@(Flatten@{#2, #2 + n - 1})]] &,
     Partition[list, n, 1] ]][[2, 1]];
Row /@ Partition[
   MapIndexed[
    If[ IntervalMemberQ[words, First@#2] , Style[ #, Red], #] &  ,
    list], 80] // TableForm

A: Let's assume we're generating letters with the same frequency as they appear in the dictionary, in strings with lengths that have the same frequency as the lengths of words in the dictionary. To do this, first we need a list of words:
words = DictionaryLookup[];
letters = (Values@# -> Keys@#) &@CharacterCounts[StringJoin[words]];
lengths = (Values@# -> Keys@#) &@Counts[StringLength[words]];

Now we need a fast way of testing if something is a word, which we can do using Dispatch (which in my testing is about 30 times faster than just using DictionaryLookup):
Attributes[wordQ] = Listable;
With[{table = Dispatch[Append[Thread[words -> True], _ -> False]]},
  wordQ[s_String] := Replace[s, table]];

Then we can see how many words we get if we let our monkeys bang away for a million tries:
BlockRandom[
  SeedRandom[137];
  trials =
   Counts[
    wordQ[Table[StringJoin[RandomChoice[letters, RandomChoice[lengths]]],
      1000000]]]] // AbsoluteTiming
(* {4.31088, <|False -> 997584, True -> 2416|>} *)

UnitConvert[N[True/(True + False) /. trials], "Percent"]
(* 0.2416% *)

So it looks like the answer is about 2.4 in a thousand, using this particular distribution of strings.

A: Of course the answer depends greatly on how you "randomly" choose the letters. Here is a Manipulate that reads in a source text, which is used to define the probability of occurrence of any given letter. It writes a short "poem" based on those probabilities. You can also look at probability "pairs" (how often a is followed by b, how often a is followed by c, etc) or at probability triples (how often ab is followed by a, for instance.) As you increase the length of the correlation, more and more actual words appear.
imageNames =
  ExampleData["Text"][[Flatten[{Range[15], Range[17, 26], 28}]]];
pRange[start_, end_, inc_] := Table[{i}, {i, start, end, inc}];
lenPiece = 850; againOld = False; bookOld = {};
Manipulate[
 If[again != againOld || bookTitle != bookOld,
  rawString = ExampleData[bookTitle]; againOld = False; again = False;
   bookOld = bookTitle;];
 textProc = StringJoin[
   Riffle[ToLowerCase[StringCases[rawString, LetterCharacter ..]], " ", 2]];
 startPos = First[RandomChoice[Drop[StringPosition[
       StringTake[textProc, Round[StringLength[textProc]/2]], " "],
      3]]] - 1;
 poem = StringSplit[StringTake[StringJoin[NestList[
      StringJoin[StringTake[#, -(mTerms - 1)],
        RandomChoice[StringCases[textProc, # ~~ xx_ -> xx]]] &,
      StringTake[textProc, {startPos, startPos + mTerms - 1}],
      lenPiece]], mTerms {1, lenPiece, 1}]];
 formatPoem = StringJoin[
   Insert[Insert[poem, "\n", pRange[8, Length[poem], 8]], " ",
    pRange[1, 1.1 Length[poem], 1]]];
 numLines = StringPosition[formatPoem, "\n"];
 outPoem = StringTake[formatPoem, First[numLines[[Min[Length[numLines], 20]]]]];
 titleLong =
  StringJoin[Insert[Take[poem, 4], " ", pRange[1, 4, 1]]] ~~ "\n";
 title = StringTake[titleLong, Min[StringLength[titleLong], 30]];
 Graphics[{Text[
    Style[title, Bold, FontSize -> 16], {0, 1}], {Text[
     Style[outPoem, FontSize -> 12, LineSpacing -> {1.1, 0}], {0,
      0}]}}, ImageSize -> {400, 400}],
 {{bookTitle, {"Text", "AliceInWonderland"}, "Source Text"},
  Thread[imageNames -> imageNames[[All, 2]]]},
 Row[{Control[{{again, False, "New Poem"}, {False, True}}],
   Control[{{mTerms, 3, "      # of Succesive Letters"}, Range[5]}]}]]

Here it is, run with Alice in Wonderland as the source text and a correlation length of 1:

and now with a correlation length of 3


text:
Q: Hi, I have to set a dynamic Date to replace hard coded value, I hace A flag in my table, how can I replace my hard coded value: I have to set a dynamic Date to replace hard coded value, I have A flag in my table, how can I replace my hard coded value with the flag:
(sum(
  PeriodsToDate(
     [calendar].[hierarchy].[Week],
     [calendar].[hierarchy].[Week].&[33]
  ),
  Measures].[sales]
  )
 )

I tried this but I have no value:
(sum(
    PeriodsToDate(
       [calendar].[hierarchy].[Week],
       [calendar].[hierarchy].[Week].&[All], ],[calendar].[WeekFlag].&[1]),
       Measures].[sales]))

Do you have any Idea about this?

A: You could maybe try using currentmember to generalise. You seem to have a lot of extra brackets!..
(sum(
    PeriodsToDate(
       [calendar].[hierarchy].[Week],
       [calendar].[hierarchy].[Week].CURRENTMEMBER
    )
    ,Measures].[sales])
)


text:
Q: Railities using incorrect Rake version I am getting the following error when running my Rails 3.2.9 application
Could not find rake-10.0.3 in any of the sources

I believe that it is caused by the fact that rake is calling for version 10.0.3 and railities is specifying > 0.8.7 in my gemlock file.
railties (3.2.9)
  actionpack (= 3.2.9)
  activesupport (= 3.2.9)
  rack-ssl (~> 1.3.2)
  rake (>= 0.8.7)
  rdoc (~> 3.4)
  thor (>= 0.14.6, < 2.0)
rake (10.0.3)

Is there a way to specify the version dependency of railities?

A: Specifying
gem 'rake', '0.8.7'

fixed the issue.


text:
Q: How to pass multiple parameters for executable path in the Process Task (SSIS)? How to pass multiple parameters for executable path in the Process Task (SSIS)?
I will have to pass two Input Parameters.

*

*Variable1  = Executable file

*Variable2 =  String Variable as an input for the execution file

In the Execute Process Task Editor >> Process  >>
Arguments >>  @[User::Variable1] + "" + @[User::Variable2]

A: You must assign an expression to achieve that:

*

*Double Click on the execute process task

*Go to Expression Tab

*Select the Executable property and click on the button shown on the right side of the line

*In the expression builder select the variable @[User::Variable1]

*Add a new expression line and select the Arguments property

*In the expression builder select the variable @[User::Variable2]


text:
Q: std::async execution order guarantee I am trying to introduce logging to a multithreaded application. Currently, I am just using std::cout from the different threads. However, in that case, the order of the output is getting jumbled, even though one thread logged early, its output in stdout is coming after the log of another thread.
So, one solution can be to move all logging to an extra thread, but I don't want to manage one more thread. So I am thinking of using std::async to do the logging from the different threads. Is this possible? Are there any suggested ways to do this? Also is the order of execution of std::async guaranteed?
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <future>
#include <string>
#include <mutex>

void print(int i)
{
    std::cout << i << std::endl;
}

int main()
{
    auto a1 = std::async(std::launch::async, print, 1);
    auto a2 = std::async(std::launch::async, print, 2);
    auto a3 = std::async(std::launch::async, print, 3);

    a3.wait();
    a2.wait();
    a1.wait();
}

For the above code, is it guaranteed that the order of output will be
1
2
3

?

A: The whole point of std::async(std::launch::async, ...) is that it's asynchronous (thus using not only "async" in the name, but repeating it in the first parameter).
You're not guaranteed much of anything about the relative order of things happening in threads created with std::async, unless you force synchronization using something like an std::mutex, std::condition_variable, or some of the synchronizing primitives in <atomic>.
You say you don't want to manage one more thread, but then you create and manage not only one, but three more threads. I don't quite understand how this makes sense.
My own tendency would be to create a type to handle logging. Whether it uses a separate thread or not is its own internal affair. The threads doing the real work just do something like: log(error) << "error 12345"; and it's up to the logging object to implement that efficiently. Yes, if you have a lot of other threads contending for use of the single logging object, it's likely to be best off running in a thread of its own--but they should neither know nor care one way or the other about that.

A:
For the above code, is it guaranteed that the order of output will be
1
2
3
4

?

No. wait() waits until the value is available. It doesn't start the execution. It merely blocks until its done.
It may as well happen that all of those futures are ready even before you call any wait()s. In that case it's quite obvious that the order is not guaranteed (and completely unrelated to the order of those wait() calls).

A: A way to offload logging from the current thread to elsewhere is to have a queue between the thread wanting to log and a thread actually writing the log to disk (or whatever). A queue is a good object to use, because it preserves order.
There's probably way better ways of doing this than what I'm about to describe (and I did this quite a while ago, so its bound to have been bettered). It's possible to adapt log4cpp so as to have a thread accepting logging requests submitted via std::queue. That's not a multithreaded thing, so what I've done before is to create a log event class, manage those using shared_ptrs, put the shared_ptrs to log event objects on the std::queue (so the posting to the queue is small, fast, and a minimum lock time on the necessary mutex). Then I've added in ZeroMQ with a PUSH/PULL pattern to allow multiple PUSHERs (posters onto the std::queue) to send 1 byte long messages to wake up a single PULL thread (that polls the zeroMQ and pulls from the std::queue). So logging consisted of the creation of a log event object, acquiring a mutex, pushing a shared_ptr to the log event object onto a std::queue, releasing the mutex and finally pushing a 1 byte message into a ZeroMQ socket.
Yes, it's a fairly horrific blend of std::queue and ZeroMQ, but it was quick to dispatch an arbitrary long log event without having to serialise the log event data in the thread send it.
A possible embelishment would be to turn off the mutex locking on the shared_ptr (it's not needed), or just use a raw pointer instead and try to remember to call delete.


text:
Q: Plotting multiple lists of complex numbers The user #Nasser showed an elegant way to plot complex numbers:
data = Table[RandomReal[{-1, 1}] + I RandomReal[{-1, 1}], {30}];

p = ListPlot[{Re[#], Im[#]} & /@ data,
    AxesOrigin -> {0, 0},
    PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}},
    ImagePadding -> 40,
    AspectRatio -> 1,
    Frame -> True,
    FrameLabel -> {{Im, None}, {Re, "complex plane"}},
    PlotStyle -> Directive[Red, PointSize[.02]]];

Show[p, Graphics@Circle[{0, 0}, 1]]

How can I change this code so that an input of multiple lists is possible and they are plotted each in a different color?

A: I propose using this function to process your complex numbers:
complexSplit = Function[z, {Re@z, Im@z}, Listable];

It works on multiple list shapes:
complexSplit[3.7 + 2.1 I]
complexSplit[{3.7 + 2.1 I, 5.7 + 4.4 I}]
complexSplit[{{3.7 + 2.1 I, 5.7 + 4.4 I}, {8.1 + 3.7 I}, 4.2 + 5.1 I}]

{3.7, 2.1}

{{3.7, 2.1}, {5.7, 4.4}}

{{{3.7, 2.1}, {5.7, 4.4}}, {{8.1, 3.7}}, {4.2, 5.1}}

Next I use this to create three lists of complex numbers:
data = {1, I}.# & /@ RandomReal[{-1, 1}, {3, 2, 50}]

Or as Rojo reminded me, more simply:
data = RandomComplex[{-1 - I, 1 + I}, {3, 50}];

I can then plot all three lists in a single ListPlot expression:
ListPlot[complexSplit @ data,
 AxesOrigin -> {0, 0},
 PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}}, ImagePadding -> 40, AspectRatio -> 1,
 Frame -> True, FrameLabel -> {{Im, None}, {Re, "complex plane"}},
 PlotStyle -> (Directive[#, PointSize[.02]] & /@ {Purple, Darker@Green, Orange}),
 Epilog -> Circle[{0, 0}, 1]
]

I can plot only the first list by using:
ListPlot[complexSplit @ {First @ data},
 AxesOrigin -> {0, 0},
 PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}}, ImagePadding -> 40, AspectRatio -> 1,
 Frame -> True, FrameLabel -> {{Im, None}, {Re, "complex plane"}},
 PlotStyle -> (Directive[#, PointSize[.02]] & /@ {Purple, Darker@Green, Orange}),
 Epilog -> Circle[{0, 0}, 1]
]

Note that I added a List level ({ }); this is to keep each point from being plotted as a different color.  Note also that the points from the first list are not colored the same as they are in the first plot; if you wish to preserve coloring you can replace any list you do not wish to plot with Indeterminate.  Here I will plot the first and third lists using the same coloring as plotting all three:
ListPlot[complexSplit @ ReplacePart[data, 2 -> Indeterminate],
 AxesOrigin -> {0, 0},
 PlotRange -> {{-1.2, 1.2}, {-1.2, 1.2}}, ImagePadding -> 40, AspectRatio -> 1,
 Frame -> True, FrameLabel -> {{Im, None}, {Re, "complex plane"}},
 PlotStyle -> (Directive[#, PointSize[.02]] & /@ {Purple, Darker@Green, Orange}),
 Epilog -> Circle[{0, 0}, 1]
]


text:
Q: Log console errors using protractor I am trying to log console errors in protractor like this
log output is in format
{
  level: {
    value: 900,
    name: 'WARNING'
  },
  message: 'message',
  timestamp: 1442090739962,
  type: ''
}, {
  level: {
    value: 800,
    name: 'INFO'
  },
  message: 'message',
  timestamp: 1442090740723,
  type: ''
}, {
  level: {
    value: 1000,
    name: 'ERROR'
  },
  message: 'error message',
  timestamp: 1442090740723,
  type: ''
},

I want to catch only errors so i have written test like this
it('it should be detect console errors', function() {
  browser.manage().logs().get('browser').then(function(browserLogs) {
    // browserLogs is an array of objects with level and message fields
    browserLogs.forEach(function(log) {
      if (log.level.value > 900) { // it's an error log
        console.log('Browser console error!');
        console.log(log.message);
      }
    });
  });
});

Problem is it's catching errors sometimes and sometimes not.
when i give wrong path to websocket and if there is an error then it is logging it. But When I give wrong path to ng-include and if there is a 404 error in console then it's not logging.
I am using firefox for testing. Is this console plugin browser dependent or what?
Why it is showing different behaviour for console errors?

A: Had similar problems, so I wrote wrapping functions
injectConsoleTracing = function () {
    browser.executeScript('window.errs=typeof(errs)=="undefined" ? [] : window.errs; window.console.error = function(msg){window.errs.push(msg); }; ');
    browser.executeScript('window.logs=typeof(logs)=="undefined" ? [] : window.logs; window.console.log = function(msg){window.logs.push(msg); }; ');
};

expectNoConsoleErrors = function () {
    browser.executeScript('return window.errs;').then(function (v) {
        expect(v).toEqual([]);
    });
    browser.executeScript('return window.logs;').then(function (v) {
        expect(v).toEqual([]);
    });
};

A: 800 is not greater  than 900 then how do you expect to catch the error,
it should be
if (log.level.value <= 900)

A: In my Test Suite I use the following to check for Console Errors and display them if any are present:
browser.manage().logs().get('browser').then(function(browserLog) {
    if (browserLog.length) {
        console.log('Browser console error!');
        console.error('log: ' + JSON.stringify(browserLog));
    }
});


text:
Q: How do you change a paragraphs/headers colour if the body already has a color? Basically, I have given my  a color (blue) and I would like to make one of the headers (
) in the body a different color (green) without using the id. I am trying to make all
 headers a certain color.
When I open the code in a browser I get the following:

body {
  color: blue;
  font-family: sans-serif;
}
h3 {
  font-style: italic;
  color: green;
  font-family: serif;
}
#id1 {
  color: blue;
}
span {
  color: orange;
}
.id4 {
  font-family: serif;
}
<!DOCTYPE html>

  <title>Question1</title>
  <link href="question1.css" type="text/css" rel="stylesheet"></link>

This is a silly header

First h2 heading this is.

Mares eat oats

   and this is a span

and this is yet more text in the second paragraph.

This is a third paragraph.

May the fourth paragraph be with you.

A: h3
{
    font-style: italic;
    color: green !important;
    font-family: serif;
}

DEMO: http://jsfiddle.net/k5pcdvkz/
EDIT: The question requires that the id attribute in the h3 not be used for styling. Hence, the id styles must be overridden to apply the green color. !important is an effective tool in this case.

A: Shortly:
h3:nth-child(1) { color:green; }
Details:
codepen demo link
You can use nth-child property that is new in CSS3. It choose the elements by number. It starts with number 1 and the number is defined by order of siblings, but little bit confusing. However, only with following one example you can use it easily. I'll show you it.
<!DOCTYPE html>

list 1

list 2

list 3

list 4

Here, you can apply your style at each of
 elements. But please see carefully for 4th
.
ul li:nth-child(1) { color:red; }
ul li:nth-child(2) { color:blue; }
ul li:nth-child(3) { color:green; }
/* 4th
 is not nth-child(4), but nth-child(5) because of
 element. */
ul li:nth-child(5) { color:pink; }

I don't know the reason why, but the nth-child method counts other sibling together. Then, in your case, you can use like this.
h3:nth-child(1) { color:green; }

I'm sure you'll be use it without difficulty. Have a nice day with HTML5~!


text:
Q: Liquid rising in a capacitor Different authors of books have given two different answers which one is more appropriate?

Q-A parallel-plate capacitor is placed in such a way that its plates are horizontal and the lower plate is dipped into a liquid of dielectric constant $K$ and density $\rho$. Each plate has an area of $A$. The plates are now connected to a battery which supplies a positive charge of magnitude Q to the upper plate. Find the rise in the level of the liquid in the space between the plates.

Solution 1:
The situation is shown in the figure. A charge $-Q\left(1-\frac{1}{K}\right)$ is induced on the upper surface of the liquid and $Q\left(1-\frac{1}{K}\right)$ at the surface in contact with the lower plate. The net charge on the lower plate is $-Q+Q\left(1-\frac{1}{K}\right)=-\frac{Q}{K} .$ Consider the equilibrium of the liquid in the volume $A B C D$. The forces on this liquid are
(a) the force due to the electric field at $C D$,
(b) the weight of the liquid,
(c) the force due to atmospheric pressure and
(d) the force due to the pressure of the liquid below $A B$.
As $A B$ is at the same horizontal level as the outside surface, the pressure here is the same as the atmospheric pressure. The forces in (c) and (d), therefore, balance each other. Hence, for equilibrium, the forces in
(a) and (b) should balance each other.
The electric field at $C D$ due to the charge $Q$ is
$$
E_{1}=\frac{Q}{2 A \varepsilon_{0}}
$$
in the downward direction. The field at $C D$ due to the
charge $-Q / K$ is
$$
E_{\mathrm{z}}=\frac{Q}{2 \mathrm{A\varepsilon}_{0} \mathrm{~K}}
$$
also in the downward direction. The net field at $C D$ is
$$
E_{1}+E_{2}=\frac{(K+1) Q}{2 A \varepsilon_{0} K}
$$
The force on the charge $-Q(1-\frac{1}{K})$ at $C D$ is
$$
\begin{aligned}
F=Q\left(1-\frac{1}{K}\right) \frac{(K+1) Q}{2 A \varepsilon_{0} K} \\
=\frac{\left(K^{2}-1\right) Q^{2}}{2 A \varepsilon_{0} K^{2}}
\end{aligned}
$$
in the upward direction. The weight of the liquid considered is $hA\rho g$. Thus,
$$
h A \rho g =\frac{\left(K^{2}-1\right) Q^{2}}{2 A \varepsilon_{0} K^{2}}$$
or,
$$h =\frac{\left(K^{2}-1\right) Q^{2}}{2 A^{2} K^{2} \varepsilon_{0} \rho g}
$$
Solution 2:
Alternative method based on energy.

Suppose the liquid rises by a distance $h .$ Then let us calculate the extra energy of the liquid as a sum of polarization energy and the ordinary gravitational energy. The latter is $$\frac{1}{2} h \cdot \rho g \cdot S h=\frac{1}{2} \rho g S h^{2}$$
If $\sigma$ is the free charge surface density on the palate, the bound charge density is, from the previous problem,
$$
\sigma^{\prime}=\frac{\varepsilon-1}{\varepsilon} \sigma
$$
This is also the volume density of induced dipole moment i.e. Polarization. Then the energy is, as before
$$
-\frac{1}{2} \cdot \sigma^{\prime} E_{0}=\frac{-1}{2} \cdot \sigma^{\prime} \frac{\sigma}{\varepsilon_{0}}=\frac{-(\varepsilon-1) \sigma^{2}}{2 \varepsilon_{0} \varepsilon}
$$
and the total polarization energy is
$$
-S(a+h) \frac{(e-1) \sigma^{2}}{2 \varepsilon_{0} \varepsilon}
$$
Then, the total energy is
$$
U(h)=-S(a+h) \frac{(\varepsilon-1) \sigma^{2}}{2 \varepsilon_{0} \varepsilon}+\frac{1}{2} \rho g S h^{2}
$$
The actual height to which the liquid rises is determined from the formula
$$
\frac{d U}{d h}=U^{\prime}(h)=0 $$This gives:
$$h=\frac{(\varepsilon-1) \sigma^{2}}{2 \varepsilon_{0} \varepsilon \rho g}
$$

This is not a homework question but I just want clarity.
Please explain why the answers are different in a simple language so that even a high school student can understand.
Thanks

A: Short answer: the first solution makes the incorrect assumption that the pressure in the liquid between the plates is equal to the atmospheric pressure at height $a$.
The second solution is written in an incomplete and confusing fashion but is ultimately sound and gives the correct answer.
I want to give all the credit for setting me on the right path to this comment by @napstablook, which also contains a link to a better version of the second solution:

Have a look at this: I think the half factor comes from there. And it is easily derivable that $P= -σ′$. And I don't think the energy is missing the part you mentioned. That part implies the work done by the electric field of surface charge on itself! the external electric field only does work to polarize this dipole. It seems to me that this new $E$' originated due to the work done on the bound charges by the external electric field. Also, there is an alternative solution given that agrees with the 2nd answer.

Now, about the mistake in the first solution. Let's call the height of the liquid outside the capacitor the "base height", aka $a$. Outside the capacitor, the pressure at the base height is of course equal to the atmospheric pressure. The first solution assumes the same holds inside the capacitor, i.e. that the pressure at the base height is also equal to the atmospheric pressure. But that's an incorrect assumption.
In fact the pressure there is larger. Inside the capacitor, the pressure is equal to the atmospheric pressure at the interface between the liquid and air.
How can the pressure inside the capacitor at the base height be bigger than outside the capacitor at the same height? Wouldn't the liquid start flowing out of the capacitor horizontally, to move from higher to lower pressure? No, for the exact same reason that the water from the bottom of a lake, where the pressure is high, doesn't flow upward to move from higher to lower pressure.
Why doesn't it do that in the lake example? Because the upward force on some small volume element of water due to the pressure differential is compensated by a downward force, namely force of gravity.
In the capacitor situation, the reason the liquid doesn't start flowing out of the capacitor horizontally is analogous. Consider a small volume element of the liquid somewhere near the edge of the capacitor, which experiences the pressure differential pushing it outward. That outward force is compensated by a certain inward force.
What is that inward force? It's the force responsible for the whole phenomenon of the liquid being sucked in and rising inside the capacitor. It's the force with which the non-uniform electric field near the capacitor's edge (called the fringe/fringing field) acts on the dielectric material of the liquid, polarizing it and pulling it inside the region with the stronger field, i.e. inside the capacitor.
ADDENDUM: another good comment by @napstablook, which expresses several questions that I'm sure many other people will have:

Can you please elaborate why the pressure is larger? @ReasonMeThis the answer looks more focused on what happens if pressure is larger.

This follows immediately from the balance of forces considerations that I described in my answer. Let's look at the lake example again, what did we see there? We saw that for a small volume element of water not to flow (i.e. for the situation to be static), the force due to the pressure differential must be equal and opposite to the external force (gravity in this case).
The same is true for our dielectric liquid. We know that near the edge of the capacitor there is an external force due to the non-uniform electric field (called the fringe/fringing field) trying to pull the liquid inside the capacitor. (How do we know this? See below.) Here again, for the situation to be static the force due to the pressure differential must be equal and opposite to this external force. Therefore the pressure differential must create an outward force, which means the pressure is larger inside the capacitor than outside (at the same height).

Also how can you calculate this extra pressure we need to balance (without resorting to the 2nd method.)

If we already knew the height of the liquid inside the capacitor (which we of course don't until we solve the problem!) then we could use the fact that the pressure must be equal to the atmospheric pressure at the interface between the liquid and air. Without knowing that height it would be extremely difficult to calculate this extra pressure, because it's very hard to deal with the field at the edge of the capacitor.
This is why the approach of the first solution, dealing with forces instead of energies, is actually completely infeasible for this problem. You might find this surprising, but actually if you for example look up the far more standard problem of finding the inward pulling force on a slab of dielectric partially inserted into a capacitor, you'll find that it's always solved with the energy approach. And you'll find discussions about the infeasibility of using the force approach because the fringe fields are so complicated.
And, just to make it explicit, how do we know there even is an inward pulling force to begin with? From energy considerations. Because the dielectric lowers the electric energy density by partially screening the electric field, the overall energy is lower if the dielectric is inserted more fully.

One final thing : 'It's the force with which the non-uniform fringe field near the capacitor'sedge acts on the dielectric material of the liquid, polarizing it and pulling it inside the region with the stronger field." I don't get this last statement.It is because the meaning of fringe field is not cleartome (is there a source you can cite for me to check?)

As I mentioned above, the non-uniform electric field near the edges of a capacitor is called the fringe/fringing field. It is that field that is responsible for pulling dielectrics into the capacitor. I know this seems a bit counterintuitive. But we can see that this must be so, because in order to have an inward pulling force on a dielectric the electric field must have a horizontal component (I am imagining that the capacitor plates are horizontal), but the field inside the capacitor far from the edges is vertical!


text:
Q: How to return NULL from JsonConvert.DeserializeObject I have a class:
public class CustomResponse
{
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string Message {get; set; }
    [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
    public string Details {get; set; }
}

Then I'm trying to deserialize JSON string to this class:
var settings = new JsonSerializerSettings
    {
        NullValueHandling.Ignore,
        MissingMemberHandling.Ignore,
    };
var customResponse = JsonConvert.Deserialize<CustomResponse>(jsonString, settings);

My JSON string for example:
{"DocumentId":"123321", "DocumentNumber":"ABC123"}

As a result I have an object which have all properties is NULL, but customResponse is not NULL. How do I get NULL in result?

A: If you want to avoid creating a custom JsonConverter, you can use the following extension method:
public static class Exts
{
    public static T OrDefaultWhen<T>(this T obj, Func<T, bool> predicate)
    {
        return predicate(obj) ? default(T) : obj;
    }
}

Usage:
var jsonString = @"{
    Message: null,
    Details: null
}";

var res = JsonConvert.DeserializeObject<CustomResponse>(jsonString)
                     .OrDefaultWhen(x => x.Details == null && x.Message == null);

A: You could create a custom JsonConverter that allocates and populates your object, then checks afterwards to see whether all properties are null, using the value returned by the JsonProperty.ValueProvider:
public class ReturnNullConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;

        // Get the contract.
        var contract = (JsonObjectContract)serializer.ContractResolver.ResolveContract(objectType);

        // Allocate the object (it must have a parameterless constructor)
        existingValue = existingValue ?? contract.DefaultCreator();

        // Populate the values.
        serializer.Populate(reader, existingValue);

        // This checks for all properties being null.  Value types are never null, however the question
        // doesn't specify a requirement in such a case.  An alternative would be to check equality
        // with p.DefaultValue
        // http://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Serialization_JsonProperty_DefaultValue.htm
        if (contract.Properties
            .Where(p => p.Readable)
            .All(p => object.ReferenceEquals(p.ValueProvider.GetValue(existingValue), null)))
            return null;

        return existingValue;
    }

    public override bool CanWrite { get { return false; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then use it like:
var settings = new JsonSerializerSettings
{
    NullValueHandling = NullValueHandling.Ignore,
    MissingMemberHandling = MissingMemberHandling.Ignore,
    Converters = { new ReturnNullConverter<CustomResponse>() },
};
var customResponse = JsonConvert.DeserializeObject<CustomResponse>(jsonString, settings);

Sample fiddle.
However, in comments you wrote, if CustomResponse is NULL, then service return a correct response and i try to deserialize to OtherCustomResponse.  In that case, consider using a polymorphic converter such as the ones from How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects? or Deserializing polymorphic json classes without type information using json.net


text:
Q: Java Spring SQL how to combine/join 3 tables into one I have 3 tables that I want to combine/join into one, I have tried different methods like join, left/right join but somehow i lose myself in the amount of statements i write so i cant get it to work properly.
I want to map the name in measurement to measurement_id in measurement_data_points and then map data_points_id in measurement_data_points to id in measurement_point
I have included a made-up result that i would like at the bottom to give a clear understanding.
My Tables:
+-------------------------+
| Tables_in_db_datapoints |
+-------------------------+
| measurement             |
| measurement_data_points |
| measurement_point       |
+-------------------------+

measurement table
mysql> select * from measurement;
+----+----------------------+
| id | name                 |
+----+----------------------+
|  1 | identifiedNeed       |
|  2 | identifiedBackground |
|  3 | identifiedGoal       |
+----+----------------------+

measurement_data_points table
mysql> select * from measurement_data_points;
+----------------+----------------+
| measurement_id | data_points_id |
+----------------+----------------+
|              1 |              1 |
|              1 |              2 |
|              1 |              3 |
|              1 |              4 |
|              2 |              5 |
|              2 |              6 |
|              2 |              7 |
|              2 |              8 |
|              3 |              9 |
|              3 |             10 |
|              3 |             11 |
|              3 |             12 |
+----------------+----------------+

measurement_point table
+----+------------+-----+----------+--------+
| id | date       | f1  | precison | recall |
+----+------------+-----+----------+--------+
|  1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|  2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|  3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|  4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|  5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|  6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|  7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|  8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|  9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| 10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| 11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| 12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----+------------+-----+----------+--------+

I want the result to mainly be like this:
+-----------------------+----------------+------------+-----+----------+
| measurement_id        | data_points_id |  date      | f1  | precison | recall |
+-----------------------+----------------+------------+-----+----------+
| identifiedNeed        |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
| identifiedNeed        |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
| identifiedNeed        |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1
| identifiedNeed        |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
| identifiedBackground  |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
| identifiedBackground  |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedBackground  |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
| identifiedBackground  |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
| identifiedGoal        |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
| identifiedGoal        |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
| identifiedGoal        |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
| identifiedGoal        |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+-----------------------+----------------+------------+-----+----------+

If that doesnt work then this works as well
+----------------+----------------+------------+-----+----------+--------+
| measurement_id | data_points_id | date       | f1  | precison | recall |
+----------------+----------------+------------+-----+----------+--------+
|              1 |              1 | 2017-11-19 | 0.3 |      0.5 |    0.2 |
|              1 |              2 | 2017-11-12 | 0.7 |      0.4 |   0.15 |
|              1 |              3 | 2017-11-15 | 0.5 |      0.3 |    0.1 |
|              1 |              4 | 2017-11-18 | 0.6 |      0.2 |   0.05 |
|              2 |              5 | 2017-11-19 | 0.2 |      0.4 |    0.2 |
|              2 |              6 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              2 |              7 | 2017-11-15 | 0.5 |      0.2 |    0.1 |
|              2 |              8 | 2017-11-18 | 0.6 |      0.1 |   0.05 |
|              3 |              9 | 2017-11-19 | 0.1 |      0.4 |    0.2 |
|              3 |             10 | 2017-11-12 | 0.4 |      0.3 |   0.15 |
|              3 |             11 | 2017-11-15 | 0.3 |      0.2 |    0.1 |
|              3 |             12 | 2017-11-18 | 0.2 |      0.1 |   0.05 |
+----------------+----------------+------------+-----+----------+--------+

A: Try the following:
select M.Name, data_points_id, date, f1 ,precision , recall
from measurement M
Inner join measurement_data_points md on m.id=md.measurement_id
inner join measurement_point mp on mp.id=md.data_points_id

A: The query you request is quite simple.  It uses the "main" table (measurement) joined with the other two.
A "join" is a way to link two tables, using one or more fields.
In your case, for example, you can join measurement with measurement_data_points using the field measurement_id using following sintax (inside a SELECT command):
...
FROM measurement A
LEFT JOIN measurement_data_points B ON A.measurement_id= B.measurement_id

Once joined, you can use in your SELECT every fields of the two tables.  Eg.
...
SELECT  measurement.name
    , measurement_data_points.data_points_id
...

Putting all together, it should be simply:
 SELECT measurement.measurement_id
    , measurement_data_points.data_points_id
    , measurement_point.date
    , measurement_point.f1
    , measurement_point.precison
    , measurement_point.recall
FROM measurement
LEFT JOIN measurement_data_points  ON measurement.measurement_id= measurement_data_points.measurement_id
LEFT JOIN measurement_point ON measurement_data_points.data_points_id = measurement_point.id ;

Query with measurement name instead of measurement id:
SELECT measurement.name
    , measurement_data_points.data_points_id
    , measurement_point.date
    , measurement_point.f1
    , measurement_point.precison
    , measurement_point.recall
FROM measurement
LEFT JOIN measurement_data_points  ON measurement.measurement_id= measurement_data_points.measurement_id
LEFT JOIN measurement_point ON measurement_data_points.data_points_id = measurement_point.id ;

Tip: all these are very simple queries and if you just use a few of your time to read something about SQL SELECT  and SQL JOIN (look on Internet) you will be capable to make queries like this by yourself and with satisfatcion.

A: SELECT a.name AS measurement_id,
       b.data_points_id,
       c.date,
       c.f1,
       c.precision,
       c.recall
FROM measurement a,
     measurement_data_points b,
     measurement_point c
WHERE a.id = b.measurement_id
  AND b.measurement_id = c.measurement_id;


text:
Q: Weighted cumulative percents (ascending/descending) in expss tables I would like to build tables of cumulative percentages using the expss package, including both ascending (0% -> 100%) and descending (100% -> 0%) orders. There is already an existing function (namely fre()) for ascending order, although the resulting table is not much customizable.
I would like to include these calculations inside a tab_stat_fun instruction, and managed to get to the desired output for unweighted datasets. Consider the following example (infert dataset):
infert %>%
  tab_cells(age) %>%
  tab_cols(total()) %>%
  tab_stat_cases(label="N", total_row_position="above", total_statistic="u_cases", total_label="TOTAL") %>%
  tab_stat_cpct(label="%Col.", total_row_position="above", total_statistic="u_cpct", total_label="TOTAL") %>%
  tab_stat_fun(label="% Asc.", function(x){100*cumsum(table(sort(x)))/sum(table(sort(x)))}) %>%
  tab_stat_fun(label="% Desc.", function(x){100-(100*cumsum(table(sort(x)))/sum(table(sort(x))))}) %>%
  tab_pivot(stat_position="inside_columns")

Works great, but if I ever want to weigh those results by a numeric vector (for the sake of demonstration: infert$w <- as.vector(x=rep(2, times=nrow(infert)), mode='numeric')), this will inevitably lead to an error since neither sum nor cumsum accept weights argument (as far as I know).
Is there a special built-in function that would do the trick? Or a combination of functions that may imply multiplying the age vector by the weight vector?

A: There is no such ready-made function. However we can utilize your approach and just replace base::table with base::xtabs. The latter can calculate weighted frequency:
library(expss)
data(infert)
infert$w <- as.vector(x=rep(2, times=nrow(infert)), mode='numeric')

cumpercent = function(x, weight = NULL){
    if(is.null(weight)) weight = rep(1, length(x))
    counts = xtabs(weight ~ x)
    100*cumsum(counts)/sum(counts)
}

infert %>%
    tab_cells(age) %>%
    tab_cols(total()) %>%
    tab_weight(w) %>%
    tab_stat_cases(label="N", total_row_position="above", total_statistic="u_cases", total_label="TOTAL") %>%
    tab_stat_cpct(label="%Col.", total_row_position="above", total_statistic="u_cpct", total_label="TOTAL") %>%
    tab_stat_fun(label="% Asc.", cumpercent) %>%
    tab_stat_fun(label="% Desc.", function(x, weight = NULL){100-cumpercent(x, weight)}) %>%
    tab_pivot(stat_position="inside_columns")


text:
Q: How can I trim the carriage return from text that is being piped in bash? I'm using this command to get my last typed command:
history | cut -c 8- | tail -n 2 | head -n 1

It works very well in bash, removing the line numbers, but there is one problem I have with it, (er, annoyance, because I want just the command) and I'm piping this to the xsel clipboard manager:
It also grabs the trailing new line / carriage return...
I know in some shells you can use:
echo "text \c"

I'm not sure how to incorporate that into bash though.
Extra points for the solution that is easiest to type on the fly :)

A: You can get the last command in your history with the bash builtin !! and use echo -n to print that command without a newline character at the end:
echo -n !!

The !! argument will expand to the actual command string and -n makes sure the output contains no newline character.

A: If I am reading your question correctly, you need to remove the trailing newline. Try this perl bit: `perl -ne 'chomp and print'
Examples:
[root@talara test]# ls -la
total 20
drwxr-xr-x   3 root root 4096 Jun  7 21:30 .
dr-xr-x---. 28 root root 4096 Jun  8 08:42 ..
-rw-r--r--   1 root root    0 Jun  7 15:10 FILE1
drwxr-xr-x   3 root root 4096 Jun  7 14:49 ham
-rw-r--r--   1 root root   36 Jun  7 21:31 t
-rw-r--r--   1 root root   11 Jun  7 16:21 test

[root@talara test]# ls -la | perl -ne 'chomp and print'
total 20drwxr-xr-x   3 root root 4096 Jun  7 21:30 .dr-xr-x---. 28 root root 4096 Jun  8 08:42 ..-rw-r--r--   1 root root    0 Jun  7 15:10 FILE1drwxr-xr-x   3 root root 4096 Jun  7 14:49 ham-rw-r--r--   1 root root   36 Jun  7 21:31 t-rw-r--r--   1 root root   11 Jun  7 16:21 test

And to make it easy for typing over and over and on the fly you can make an alias: alias chomp="perl -ne 'chomp and print'"


text:
Q: How do I return a single value from an array output by a function without declaring a variable first? Let's say I have this:
function data() {
    $out['a'] = "abc";
    $out['b'] = "def";
    $out['c'] = "ghi";
    return $out;
}

I can output the data by declaring it as a variable, then using the array index to echo it:
$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];

But, I'm calling functions inline with other functions, and I'm trying to avoid having to declare a variable first. For instance, I want to do something like this:
echo data()[0]; //pulls first value in array without declaring it as a variable first. This needs to be variable i.e. data()[1] data()[2] etc.

Or more specifically, I'm actually trying to do it as a class:
$traverseXML->getData("Route", "incoming", "field", "value")[0]
//getData() returns an array, I'm trying to get a single value.

A: Personally i would do something like this
<?php
function data($key = false, $default = 'not found') {
    $out['a'] = "abc";
    $out['b'] = "def";
    $out['c'] = "ghi";
    if($key)
    {
        if(isset($out[$key]))
            return $out[$key];
        else
            return $default;
    }

    else
        return 'empty';
}
 ?>

 <?= data('a') ?>


text:
Q: Maintaining Two Separate Software Versions From the Same Codebase in Version Control Let's say that I am writing two different versions of the same software/program/app/script and storing them under version control. The first version is a free "Basic" version, while the second is a paid "Premium" version that takes the codebase of the free version and expands upon it with a few extra value-added features. Any new patches, fixes, or features need to find their way into both versions.
I am currently considering using master and develop branches for the main codebase (free version) along side master-premium and develop-premium branches for the paid version. When a change is made to the free version and merged to the master branch (after thorough testing on develop of course), it gets copied over to the develop-premium branch via the cherry-pick command for more testing and then merged into master-premium.
Is this the best workflow to handle this situation? Are there any potential problems, caveats, or pitfalls to be aware of? Is there a better branching strategy than what I have already come up with?
Your feedback is highly appreciated!
P.S. This is for a PHP script stored in Git, but the answers should apply to any language or VCS.

A: Instead of having two code version with a common base you should design your application in a way to make those premium features plug-able and driven by configuration rather than different code bases.
If you are afraid to ship those premium features (disabled by configuration) with the basic version you can still remove that code in a final build/packaging step and just have two build profiles.
Having this design you can also ship 5 different flavors and get very flexible, maybe even allowing third parties to contribute.

A: We are using 2 separate projects, the Basic one and the Premium one that depends on Basic project. Do not use braches, they are usually used for features.

A: I strongly recommend not using branches for this purpose. In general, you should consider branches for things that will be (or might be) merged back together again later (or for release branches, where you eventually stop development of one of the branches). In your case, you will never merge your "basic" and "premium" versions together, and they will both be maintained indefinitely, so branches are not appropriate.
Instead, maintain one common version of the source code and use conditional compilation (eg. #ifdef in C/C++, not sure what the equivalent is for PHP) to include or exclude the sections of code that differ between "basic" and "premium".
It looks like PHP might not have such a conditional compilation feature built in, so you could use the C preprocessor (cpp, you probably already have it) to preprocess your common source code and from that, produce a "basic" and a "premium" version without the preprocessor directives. Of course, if you choose to do this you should use make or something similar to automate the process of running the preprocessor.

A: While most current answers are in favour of conditional compilation instead of branches, there is one scenario where there is a clear benefit to using branches: if you (now or later) decide to make the source code of the basic version available, including all the version history but excluding all the premium features, then you can do so with the branches approach but not with a single branch and conditional compilation.
I'd advise against cherry picking, and instead merge all changes from the basic version into the premium version. There should be no feature or bug fix included in the basic but missing in the premium version. To make things as painless as possible, you should make sure that the premium branch modifies the common files as little as possible. So the premium branch should mostly contain additional files, and perhaps some slight modifications to build instructions. That way, changes from the basic version will merge automatically without causing conflicts.
Greg's answer suggested that you "consider branches for things that will be (or might be) merged back together again later". With the approach I just described this is the case, except that the final branch for all commits will be master-premium not master (which is actually master-basic).
Sub-modules would of course be an option as well. It depends on your build process, but if you can make the premium version into a project which uses the basic version as a module, that would be just fine. You might however have a harder time if at some point you decide to cherry-pick features from the premium branch into the basic branch. With sub-modules such a change would be represented as two distinct commits, whereas with branches this would be a single commit to the basic version, and the next merge into the premium version would know that these changes are already included and don't have to be merged again.

A: In "hardware" this is done often, they are systems sold to control the mess, sorry I can't remember what they are called.
Once the "mid range" washing machine ships, it's code is not change other than for a very important bug fix, even when the same code gets changed in the "low end" washing machine that ships  a few months later.
Customers don't expect to get upgrades to a washing machine they have already brought, a new model is also not shipped every few months.
Most of us don't live in that world, so do what Greg says unless you are writing software for washing machines.


text:
Q: How to save Borderlands 2 characters online My friend and I have been playing Borderlands 2 online on the Xbox for months. Today he's coming here at my place and we want to have a session together.
If I make him log with his account on my Xbox, will he be able to use his character?

A: If the operation is the same as on PC your characters are saved online. It's necessary to launch the game (and the game session) on the account who hosted for the first time the game, otherwise you will spawn in the first mission of the game (with your character).

A: yes, your characters are saved online. as long as you make sure that both accounts are signed in and that you have a stable Internet connection for it to sync, you'll be fine


text:
Q: Any explaination for Android android.content.SyncManager? I've be searching around to find out how the Android Sync mechanism works.
Speciallfy for the ContentResolver.addPeriodSync() method.
who is calling the sync operation frequently?
I came across with the andorid.content.SyncMananger, which seems to be the one doing this from Android framework.
But I couldn't find any document for the SyncManager except the Source Code.

A: All Apps are able to call this method.
It is mostly used when an account is created, on Apps that use SyncAdapters. This is what most Apps will use to keep their data current. addPeriodicSync lets you tell Android that a SyncAdapter needs to run a sync operation repeatedly, with a set period.
The synchronization mechanism isn't very well documented, but if you google SyncAdapter you should find enough details.
Please see SyncAdapter:
http://developer.android.com/reference/android/content/AbstractThreadedSyncAdapter.html


text:
Q: How to use dynamic column inside of bquote a <- "t"
bquote(data.frame(.(a) = 1:10)
Error: unexpected '=' in "bquote(data.frame(.(a) ="

a needs to be dynamic. How can this be accomplished?

A: You cannot use bquote for this. The easiest way to solve this is just to use setNames()
a <- "t"
setNames(data.frame(1:10), a))

Alternative you could build the data.frame call and then use do.call but you still have to set the parameter name with setNames()
do.call("data.frame", setNames(list(1:10), a))

But if you are using tidyverse packages, you can dynamically set names in a tibble call using :=
tibble(!!a := 1:10)


text:
Q: Pandas concat only beside certain column values I have a  100 row dataframe with a column "genres" containing either "Romance" or "Fantasy". I have another dataframe with 50 values. How do I horizontally concatenate these values only beside cells containing "Romance"?

A: Your question is ambiguous, you should provide an example of input/output. However, if I understand correctly, you can add values only in rows matching Romance (provided there are 50 of these rows) by using loc:
df.loc[df['genres'].eq('Romance'), 'new_column'] = other_df['col'].values


text:
Q: What does 'Max allocated RAM size' mean on this mobo? I see in multiple webshops that this MSI Z87 G41 PC Mate mobo has an attribute called Max Allocated RAM Size: 1760 MB
What does this mean? Can the motherbord handle maximum 1760MB memory in total, per memory module or per process? or something else?

A: I believe this is related to allocating memory to on-board or on-chip (haswell etc.) GPUs which share system memory.  The figure relates to the largest amount of system memory you can allocate across as extra memory for the GPU, in addition to any on-chip or on-board GFX memory.

A: On older boards way-back-when which only supported 2GB RAM in total this sort of thing referred to what you would expect to see after on-board video hardware and other devices and consumed some.
On a modern board like this (which supports 64GB as the other specs state) this refers to what memory can be allocated to the on-board GPU - so you might put 8GB in there but only see ~6.25 GB available to OS/apps/games as the GPU has claimed the remainder for its work. You usually have some control over what the GPU does claim, and of course if you completely replace its function with an add-on card (which you likely will if building a machine for gaming) it should take 0.
This information is normally listed with or directly after the name/model of GPU in a specs sheet, I assume that line has been missed out by mistake in this case (either a mistake on the seller's part or due to them copying a bad list from the manufacturer's blurb) leading to a little confusion.


text:
Q: Which puck has the greatest kinetic energy at the finish line? The question is:

"Two pucks one with mass 3kg and the other with mass 1kg are pushed along a frictionless table with the same horizontal force from rest from the same starting point to the same finish line. Which of the pucks has the greatest kinetic energy at the finish line?"

I thought the pucks had the same kinetic energy at the finish line, but apparently thats wrong. Can someone explain? Is it the 3kg one because of the greater mass?

A: You can take a couple of approaches. GaryP has a good one.
Work done on a particle is the force applied through a distance. We are told that there is some distance $d$ through which both pucks are moved and they are both subject to the same force $F$.
Work is the change of kinetic energy $W=Fd$. F and d is the same for both. One can zoom in though.
A constant force implies a constant acceleration by Newton's second law. The pucks are starting from rest, the final velocity is $V$. So the average velocity is $(0+V)/2$. The acceleration is $(V-0)/t$ where $t$ is the time it takes the puck to traverse distance $d$. So $t=2d/V$. So $a=V^2/2d$. But $a=F/m$. So $Fd=mV^2/2$.
So while the kinetic energy is the same, $2Fd/m=V^2$. So velocity will be smaller for the more massive puck.


text:
Q: Multi-functionality facebook app design: one big app vs. breaking into smaller apps? Okay, I am developing a Facebook app that has multiple sections, each of which serve as a single page that does a simple task for the user, and requires different set of permissions to accomplish that task.
My question is: should I create multiple apps, one for each of the sections? or do I create a single app, and request new permissions when the user goes from one section to another?

A: Although I think this question is more appropriate for Stack UX, I'll answer it here.
If these tasks/sections are not at all relevant to each other, and the user will not likely need to use another task if s(he) used one. Then it might be good idea to make every section a separate app. Even it you will ask on permissions separately, it's still hard to promote an app which has no specific "topic", and it's not nice to show the user things that are not really interesting to him.
However, if these tasks are interconnected, i.e, the user will most likely need to use many of them once (s)he starts using one, then you should have a single app. This opinion is based on many reasons:

*

*It's a bad experience to ask the user to authenticate a completely different app if he (for example) clicked on a button in the current app.

*Separation will make your apps less popular, it's more attracting to see a single app that has 100,000 users than see 10 apps that have 10,000 each. Besides, promoting and spreading a single app is easier. In fact, for this reason I would even choose to make it a single app even if the sections are not relevant to each other.
As for how to ask for permissions in a single app, this is dependent on many factors including:

*

*The target audience: if your target users are lazy and don't really care about what permissions they are giving, then it'll be a good idea to ask for all permissions at the very beginning, this is easier for development and less interrupting for the user.

*The variation of permissions: if sections request so different permissions, like having a section that only require light read permissions, and another that require page management permission; then it's better to ask for additional permissions every time the user starts using a "more dangerous" section. On the other hand, if most sections require similar permissions, like having all the sections require read permissions only, then it's probably better not to interrupt the user every time he enters a new section.