问:
How to get distinct data from two tables using SQL Select query
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

```<code>Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000
</code>```

Table_Innovation

```<code>Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno
</code>```

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

```<code>counts
 2
</code>```

output: How many users started Innovation base on email need details of users.

```<code> Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000
</code>```

答:
Please try to make use of below code for the desire output:</p>

```<code>    DECLARE @Table_UserInformation TABLE(Name VARCHAR(100),Email VARCHAR(100),mobile VARCHAR(100))
    INSERT INTO @Table_UserInformation VALUES
    ('mazhar','mazar@gmail.com','720000000'),
    ('rahul','rahul@gmail.com','992000000'),
    ('raj','raj@gmail.com','700000000')

    DECLARE @Table_Innovation TABLE(Email VARCHAR(100),DATA1 VARCHAR(100),DATA2 VARCHAR(100))
    INSERT INTO @Table_Innovation VALUES
    ('mazar@gmail.com','aim to achive LD','NA'),
    ('mazar@gmail.com','Search for LD','NA'),
    ('rahul@gmail.com','mind tech','Techno')

    SELECT
        COUNT(DISTINCT Email) AS COUNTS
    FROM
        @Table_Innovation

    SELECT
        DISTINCT T1.Name,T1.Email,T1.mobile
    FROM
        @Table_UserInformation T1  INNER JOIN @Table_Innovation T2 ON T1.Email=T2.Email
</code>```

Body:
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000

Table_Innovation

Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

counts
 2

output: How many users started Innovation base on email need details of users.

 Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000

Body:
Please try to make use of below code for the desire output:

    DECLARE @Table_UserInformation TABLE(Name VARCHAR(100),Email VARCHAR(100),mobile VARCHAR(100))
    INSERT INTO @Table_UserInformation VALUES
    ('mazhar','mazar@gmail.com','720000000'),
    ('rahul','rahul@gmail.com','992000000'),
    ('raj','raj@gmail.com','700000000')

    DECLARE @Table_Innovation TABLE(Email VARCHAR(100),DATA1 VARCHAR(100),DATA2 VARCHAR(100))
    INSERT INTO @Table_Innovation VALUES
    ('mazar@gmail.com','aim to achive LD','NA'),
    ('mazar@gmail.com','Search for LD','NA'),
    ('rahul@gmail.com','mind tech','Techno')

    SELECT
        COUNT(DISTINCT Email) AS COUNTS
    FROM
        @Table_Innovation

    SELECT
        DISTINCT T1.Name,T1.Email,T1.mobile
    FROM
        @Table_UserInformation T1  INNER JOIN @Table_Innovation T2 ON T1.Email=T2.Email


来源: stackexchange

问:
Hiding ‘Bottom Navigation Bar’ whilst keyboard is present - Android
I have a small demo chat UI application. This application has a bottom navigation bar. I need the bottom navigation bar to hide when the keyboard appears.

Here is an example of the chat UI

As you can see when you click in the EditText element, the keyboard appears but the bottom navigation bar stays visible. I have tried methods such as this measurement method, but the UI elements flicker like this.

Is there a proper way to hide the bottom navigation bar when the keyboard is visible?

EDIT:
In the below activity you can see where I set the keyboard listener to adjust the position of UI elements when the keyboard is determined as being visible.

This is my activity code, uses setKeyboardListener method from the above link and set it in onCreateView:

```<code>package uk.cal.codename.projectnedry.TeamChatFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.roughike.bottombar.BottomBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;

import static android.view.View.GONE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TeamChatView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TeamChatView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.teamChatList)
    RecyclerView mTeamChatRecyclerView;
    @BindView(R.id.teamChatSendButton)
    ImageButton mTeamChatSendButton;
    @BindView(R.id.messageTextInput)
    EditText mMessageTextInput;
    TeamChatListAdapter mTeamChatListAdapter;
    TeamChatListAdapter.ClickListener mTeamChatListClickListener;
    private ArrayList<String> mTestMessageList;

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }

    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.d("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TeamChatView.
     */
    public static TeamChatView newInstance() {
        TeamChatView fragment = new TeamChatView();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
    }

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

        mTestMessageList = new ArrayList<>();
        this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
        this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);

        this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
                    getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
                    mMessageTextInput.setText("");
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                }
            }
        });

        setKeyboardListener(new OnKeyboardVisibilityListener(){
            @Override
            public void onVisibilityChanged(boolean visible) {
                RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
                BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
                if (visible) { // if more than 100 pixels, its probably a keyboard...
                    lowerNavigationBar.setVisibility(GONE);
                    contentFrame.setPadding(0, 0, 0, 0);
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                } else {
                    contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                    lowerNavigationBar.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static int convertDpToPixel(float dp, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void addToTestMessageList(String str){
        this.mTestMessageList.add(str);
        this.mTeamChatListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
       // getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
    }

    @Override
    public TeamChatPresenter getSpecificImpOfGenericPresenter() {
        return (TeamChatPresenter) this.mPresenter;
    }
}
</code>```

This is my XML layout:

```<code><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:orientation="vertical"
    tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">

    <android.support.v7.widget.RecyclerView
        android:layout_above="@+id/chatViewMessageEntryLayout"
        android:id="@+id/teamChatList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:isScrollContainer="false"
        android:paddingTop="10dp"
        android:scrollbars="vertical" />

    <RelativeLayout
        android:id="@+id/chatViewMessageEntryLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <View
            android:id="@+id/chatViewMessageEntrySeperator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#e3e3e8" />

        <EditText
            android:id="@+id/messageTextInput"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_below="@+id/chatViewMessageEntrySeperator"
            android:layout_toLeftOf="@+id/teamChatSendButton"
            android:background="@android:color/transparent"
            android:hint="Enter message"
            android:inputType="textCapSentences|textMultiLine"
            android:maxLength="1000"
            android:maxLines="4"
            android:paddingLeft="10dp" />

        <ImageButton
            android:id="@+id/teamChatSendButton"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="center"
            android:background="#00B9EF"
            android:src="@drawable/ic_send_white_24dp" />

    </RelativeLayout>

</RelativeLayout>
</code>```

答:
Add the attribute : android:windowSoftInputMode="adjustResize"" in your manifest inside activity tag:

```<code> <activity
        android:name=".YourActivity"
        android:windowSoftInputMode="adjustResize"/>
</code>```

NB: I suggest, You should use NestedScrollView as the parent layout.

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I have a small demo chat UI application. This application has a bottom navigation bar. I need the bottom navigation bar to hide when the keyboard appears.

Here is an example of the chat UI

As you can see when you click in the EditText element, the keyboard appears but the bottom navigation bar stays visible. I have tried methods such as this measurement method, but the UI elements flicker like this.

Is there a proper way to hide the bottom navigation bar when the keyboard is visible?

EDIT:
In the below activity you can see where I set the keyboard listener to adjust the position of UI elements when the keyboard is determined as being visible.

This is my activity code, uses setKeyboardListener method from the above link and set it in onCreateView:

package uk.cal.codename.projectnedry.TeamChatFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.roughike.bottombar.BottomBar;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import uk.cal.codename.projectnedry.R;
import uk.cal.codename.projectnedry.TeamChatFragment.ListAdapter.TeamChatListAdapter;
import uk.demo.cal.genericmodelviewpresenter.GenericMvp.GenericMvpFragment;

import static android.view.View.GONE;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link TeamChatView.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link TeamChatView#newInstance} factory method to
 * create an instance of this fragment.
 */
public class TeamChatView extends GenericMvpFragment implements TeamChatContract.RequiredViewOps {

    private OnFragmentInteractionListener mListener;
    @BindView(R.id.teamChatList)
    RecyclerView mTeamChatRecyclerView;
    @BindView(R.id.teamChatSendButton)
    ImageButton mTeamChatSendButton;
    @BindView(R.id.messageTextInput)
    EditText mMessageTextInput;
    TeamChatListAdapter mTeamChatListAdapter;
    TeamChatListAdapter.ClickListener mTeamChatListClickListener;
    private ArrayList<String> mTestMessageList;

    public interface OnKeyboardVisibilityListener {
        void onVisibilityChanged(boolean visible);
    }

    public final void setKeyboardListener(final OnKeyboardVisibilityListener listener) {
        final View activityRootView = ((ViewGroup) getActivity().findViewById(android.R.id.content)).getChildAt(0);

        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            private boolean wasOpened;

            private final int DefaultKeyboardDP = 100;

            // From @nathanielwolf answer...  Lollipop includes button bar in the root. Add height of button bar (48dp) to maxDiff
            private final int EstimatedKeyboardDP = DefaultKeyboardDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);

            private final Rect r = new Rect();

            @Override
            public void onGlobalLayout() {
                // Convert the dp to pixels.
                int estimatedKeyboardHeight = (int) TypedValue
                        .applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, activityRootView.getResources().getDisplayMetrics());

                // Conclude whether the keyboard is shown or not.
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                boolean isShown = heightDiff >= estimatedKeyboardHeight;

                if (isShown == wasOpened) {
                    Log.d("Keyboard state", "Ignoring global layout change...");
                    return;
                }

                wasOpened = isShown;
                listener.onVisibilityChanged(isShown);
            }
        });
    }

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

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment TeamChatView.
     */
    public static TeamChatView newInstance() {
        TeamChatView fragment = new TeamChatView();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @SuppressLint("MissingSuperCall")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(TeamChatPresenter.class, TeamChatModel.class, savedInstanceState);
    }

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

        mTestMessageList = new ArrayList<>();
        this.mTeamChatListAdapter = new TeamChatListAdapter(mTestMessageList);
        this.mTeamChatRecyclerView.setAdapter(this.mTeamChatListAdapter);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        this.mTeamChatRecyclerView.setLayoutManager(linearLayoutManager);

        this.mTeamChatSendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!String.valueOf(mMessageTextInput.getText()).equals("")) {
                    getSpecificImpOfGenericPresenter().sendMessage(String.valueOf(mMessageTextInput.getText()));
                    mMessageTextInput.setText("");
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                }
            }
        });

        setKeyboardListener(new OnKeyboardVisibilityListener(){
            @Override
            public void onVisibilityChanged(boolean visible) {
                RelativeLayout contentFrame = (RelativeLayout) getActivity().findViewById(R.id.content_company_navigation);
                BottomBar lowerNavigationBar = (BottomBar) getActivity().findViewById(R.id.bottomBar);
                if (visible) { // if more than 100 pixels, its probably a keyboard...
                    lowerNavigationBar.setVisibility(GONE);
                    contentFrame.setPadding(0, 0, 0, 0);
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                } else {
                    contentFrame.setPadding(0, 0, 0, convertDpToPixel(60, getContext()));
                    mTeamChatRecyclerView.smoothScrollToPosition(mTestMessageList.size());
                    lowerNavigationBar.setVisibility(View.VISIBLE);
                }
            }
        });
        return view;
    }

    /**
     * This method converts dp unit to equivalent pixels, depending on device density.
     *
     * @param dp A value in dp (density independent pixels) unit. Which we need to convert into pixels
     * @param context Context to get resources and device specific display metrics
     * @return A float value to represent px equivalent to dp depending on device density
     */
    public static int convertDpToPixel(float dp, Context context){
        Resources resources = context.getResources();
        DisplayMetrics metrics = resources.getDisplayMetrics();
        int px = (int) (dp * ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }

    public void addToTestMessageList(String str){
        this.mTestMessageList.add(str);
        this.mTeamChatListAdapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
       // getView().getViewTreeObserver().removeGlobalOnLayoutListener(test);
    }

    @Override
    public TeamChatPresenter getSpecificImpOfGenericPresenter() {
        return (TeamChatPresenter) this.mPresenter;
    }
}

This is my XML layout:

<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:orientation="vertical"
    tools:context="uk.cal.codename.projectnedry.TeamChatFragment.TeamChatView">

    <android.support.v7.widget.RecyclerView
        android:layout_above="@+id/chatViewMessageEntryLayout"
        android:id="@+id/teamChatList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:isScrollContainer="false"
        android:paddingTop="10dp"
        android:scrollbars="vertical" />

    <RelativeLayout
        android:id="@+id/chatViewMessageEntryLayout"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal">

        <View
            android:id="@+id/chatViewMessageEntrySeperator"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#e3e3e8" />

        <EditText
            android:id="@+id/messageTextInput"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center_vertical"
            android:layout_below="@+id/chatViewMessageEntrySeperator"
            android:layout_toLeftOf="@+id/teamChatSendButton"
            android:background="@android:color/transparent"
            android:hint="Enter message"
            android:inputType="textCapSentences|textMultiLine"
            android:maxLength="1000"
            android:maxLines="4"
            android:paddingLeft="10dp" />

        <ImageButton
            android:id="@+id/teamChatSendButton"
            android:layout_width="50dp"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:layout_gravity="center"
            android:background="#00B9EF"
            android:src="@drawable/ic_send_white_24dp" />

    </RelativeLayout>

</RelativeLayout>

Body:
Add the attribute : android:windowSoftInputMode="adjustResize"" in your manifest inside activity tag:

 <activity
        android:name=".YourActivity"
        android:windowSoftInputMode="adjustResize"/>

NB: I suggest, You should use NestedScrollView as the parent layout.

Hope this helps.


Title: Mean of timedeltas when resampling in pandas

Body:
Given this dataframe:

df = pd.DataFrame(pd.to_timedelta(['00:00:02','00:00:05','00:00:10','00:00:15','00:00:05']))
df.index = pd.to_datetime(['20/02/2017 12:42:10','20/02/2017 12:43:10','20/02/2017 12:45:10','20/02/2017 12:45:10','20/02/2017 12:45:10'])
df.columns = ['time']

df
Out[232]:
                        time
2017-02-20 12:42:10  00:00:02
2017-02-20 12:43:10  00:00:05
2017-02-20 12:45:10  00:00:10
2017-02-20 12:45:10  00:00:15
2017-02-20 12:45:10  00:00:05

I amb trying to resample it, getting the average time for each min.
P.e it works when suming them doing:

df.resample('min').sum()
Out[245]:
                        time
2017-02-20 12:42:00 00:00:02
2017-02-20 12:43:00 00:00:05
2017-02-20 12:44:00 00:00:00
2017-02-20 12:45:00 00:00:30

There is any way of making this work with mean?

Something like:

df.resample('min').mean()

Body:
You can first convert timedeltas to total_seconds (floats), resample and use fillna. Last convert to_timedelta back:

df = pd.to_timedelta(df.time.dt.total_seconds().resample('min').mean().fillna(0), unit='s')
print (df)
2017-02-20 12:42:00   00:00:02
2017-02-20 12:43:00   00:00:05
2017-02-20 12:44:00   00:00:00
2017-02-20 12:45:00   00:00:10
Freq: T, Name: time, dtype: timedelta64[ns]

Increase precision is possible by converting to nanoseconds:

print (pd.Series(df.time.values.astype(np.int64), index=df.index))
2017-02-20 12:42:10     2000000000
2017-02-20 12:43:10     5000000000
2017-02-20 12:45:10    10000000000
2017-02-20 12:45:10    15000000000
2017-02-20 12:45:10     5000000000
dtype: int64

df = pd.to_timedelta(pd.Series(df.time.values.astype(np.int64), index=df.index)
                                 .resample('min').mean().fillna(0))
print (df)
2017-02-20 12:42:00   00:00:02
2017-02-20 12:43:00   00:00:05
2017-02-20 12:44:00   00:00:00
2017-02-20 12:45:00   00:00:10
Freq: T, dtype: timedelta64[ns]


问:
Simple question on printf and C. Printing characters of a string one by one
I have weird string that I want to inspect by printing its characters one by one. How can this be done?

I'm worried in case it has any special characters that may obstruct its printing. Can they be 'escaped'?

答:
An alternative way to see special characters:

```<code>./a.out | hexdump -C
</code>```

hexdump

ContentLicense: CC BY-SA 2.5

Body:
An alternative way to see special characters:

./a.out | hexdump -C

hexdump


问:
Inversify.js - Reflect.hasOwnMetadata is not a function
I'm trying out Inversify.js for a Typescript application I'm using. Right now, there is no framework involved, so it's pure ES2015.

I'm trying to follow along the example in the main page, but I'm being hit with:
"Reflect.hasOwnMetadata is not a function" when I try to run it in the browser.

I'm using Webpack as package bundler.

Here is my folder structure:

Here is the main app.ts file:

```<code>/// <reference path="../typings/index.d.ts" />
/// <reference path="./domain/abstract/match.interface.ts" />

import kernel from "../inversify/inversify.config.ts";

import {symbols} from "../inversify/symbols.ts";

var ninja = kernel.get<INinja>("INinja");

ninja.fight();
ninja.sneak();
</code>```

interfaces.d.ts:

```<code>interface INinja {
    fight(): string;
    sneak(): string;
}

interface IKatana {
    hit(): string;
}

interface IShuriken {
    throw();
}
</code>```

inversify.config.ts

```<code>/// <reference path="../node_modules/inversify/type_definitions/inversify/inversify.d.ts" />
/// <reference path="../node_modules/reflect-metadata/reflect-metadata.d.ts" />
/// <reference path="inversify.ts" />

import {Kernel} from "inversify"
//import {MatchHub} from "../app/components/Hubs/match/match-hub.component.ts";
//import {symbols} from "./symbols.ts";

import {Ninja, Katana, Shuriken} from "./inversify.ts";

var kernel = new Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken);

export default kernel;
</code>```

symbols.ts:

```<code>export const symbols = {
    Match : Symbol("Match")
}
</code>```

tsconfig.json:

```<code>{
  "compilerOptions": {
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata":  true,
    "removeComments": true,
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "wwwroot"
  ]
}
</code>```

Webpack.config.js:

```<code>module.exports = {
  entry: './app/app.ts',
  output: {
    filename: '../Scripts/app/app.js'
  },
  resolve: {
      extensions: ['', '.Webpack.js', '.web.js', '.ts','.js', '.tsx']
  },
  module: {
    loaders: [
        {
          test: /\.ts?$/,
          exclude: /(node_modules|bower_components)/,
          loader: 'ts-loader'
        }
    ]
  },
  watch: true
}
</code>```

Firefox Console Error:

Webpack output:

When  I tried to install Inversify the following warnings popped up:

Is it a bug? Or am I doing something wrong? Thanks!

PS: Tried following the sample files, but I couldn't understand anything!

I come from ASP.NET MVC 5 with Ninject so I can relate for most of the syntax.

答:
May be a silly thing to point out, I ran into a the same issue but it was because of the order of imports.
Its  unlikely to be the case for any other imports but in case of reflect-metadata it has to be imported before any classes that use it.</p>

```<code>import { Container } from "inversify";
//reflect-metadata should be imported
//before any interface or other imports
//also it should be imported only once
//so that a singleton is created.
import "reflect-metadata";
import Battle from "./interfaces/battle";
import EpicBattle from "./interfaces/epic_battle";
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying out Inversify.js for a Typescript application I'm using. Right now, there is no framework involved, so it's pure ES2015.

I'm trying to follow along the example in the main page, but I'm being hit with:
"Reflect.hasOwnMetadata is not a function" when I try to run it in the browser.

I'm using Webpack as package bundler.

Here is my folder structure:

Here is the main app.ts file:

/// <reference path="../typings/index.d.ts" />
/// <reference path="./domain/abstract/match.interface.ts" />

import kernel from "../inversify/inversify.config.ts";

import {symbols} from "../inversify/symbols.ts";

var ninja = kernel.get<INinja>("INinja");

ninja.fight();
ninja.sneak();

interfaces.d.ts:

interface INinja {
    fight(): string;
    sneak(): string;
}

interface IKatana {
    hit(): string;
}

interface IShuriken {
    throw();
}

inversify.config.ts

/// <reference path="../node_modules/inversify/type_definitions/inversify/inversify.d.ts" />
/// <reference path="../node_modules/reflect-metadata/reflect-metadata.d.ts" />
/// <reference path="inversify.ts" />

import {Kernel} from "inversify"
//import {MatchHub} from "../app/components/Hubs/match/match-hub.component.ts";
//import {symbols} from "./symbols.ts";

import {Ninja, Katana, Shuriken} from "./inversify.ts";

var kernel = new Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken);

export default kernel;

symbols.ts:

export const symbols = {
    Match : Symbol("Match")
}

tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "experimentalDecorators": true,
    "emitDecoratorMetadata":  true,
    "removeComments": true,
    "sourceMap": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "wwwroot"
  ]
}

Webpack.config.js:

module.exports = {
  entry: './app/app.ts',
  output: {
    filename: '../Scripts/app/app.js'
  },
  resolve: {
      extensions: ['', '.Webpack.js', '.web.js', '.ts','.js', '.tsx']
  },
  module: {
    loaders: [
        {
          test: /\.ts?$/,
          exclude: /(node_modules|bower_components)/,
          loader: 'ts-loader'
        }
    ]
  },
  watch: true
}

Firefox Console Error:

Webpack output:

When  I tried to install Inversify the following warnings popped up:

Is it a bug? Or am I doing something wrong? Thanks!

PS: Tried following the sample files, but I couldn't understand anything!

I come from ASP.NET MVC 5 with Ninject so I can relate for most of the syntax.

Body:
May be a silly thing to point out, I ran into a the same issue but it was because of the order of imports.
Its  unlikely to be the case for any other imports but in case of reflect-metadata it has to be imported before any classes that use it.

import { Container } from "inversify";
//reflect-metadata should be imported
//before any interface or other imports
//also it should be imported only once
//so that a singleton is created.
import "reflect-metadata";
import Battle from "./interfaces/battle";
import EpicBattle from "./interfaces/epic_battle";


问:
Webpack dist: index.html is a blank page
I'm pretty new to Webpack, and have followed this tutorial to add authentication to a React app I have been working on.

It all works fine in development, however I get a blank page when trying to run the distribution files.

Here's my webpack.config.js:

```<code>const NODE_ENV = process.env.NODE_ENV;
const dotenv = require('dotenv');

const webpack = require('webpack');
const fs      = require('fs');
const path    = require('path'),
      join    = path.join,
      resolve = path.resolve;

const getConfig = require('hjs-webpack');

const isDev  = NODE_ENV === 'development';
const isTest = NODE_ENV === 'test';

const root    = resolve(__dirname);
const src     = join(root, 'src');
const modules = join(root, 'node_modules');
const dest    = join(root, 'dist');

var config = getConfig({
  isDev: isDev,
  in: join(src, 'app.js'),
  out: dest,
  html: function (context) {
    return {
      'index.html': context.defaultTemplate({
        title: 'My Title',
        publicPath: isDev ? 'http://localhost:3000/' : 'http://localhost:9000/',
        meta: {
          'name': 'My name',
          'description': 'My desc'
        }
      })
    }
  }
});

// ENV variables
const dotEnvVars = dotenv.config();
const environmentEnv = dotenv.config({
  path: join(root, 'config', `${NODE_ENV}.config.js`),
  silent: true,
});
const envVariables =
    Object.assign({}, dotEnvVars, environmentEnv);

const defines =
  Object.keys(envVariables)
  .reduce((memo, key) => {
    const val = JSON.stringify(envVariables[key]);
    memo[`__${key.toUpperCase()}__`] = val;
    return memo;
  }, {
    __NODE_ENV__: JSON.stringify(NODE_ENV)
  });

config.plugins = [
  new webpack.DefinePlugin(defines)
].concat(config.plugins);
// END ENV variables

// CSS modules
const cssModulesNames = `${isDev ? '[path][name]__[local]__' : ''}[hash:base64:5]`;

const matchCssLoaders = /(^|!)(css-loader)($|!)/;

const findLoader = (loaders, match) => {
  const found = loaders.filter(l => l && l.loader && l.loader.match(match))
  return found ? found[0] : null;
}
// existing css loader
const cssloader =
  findLoader(config.module.loaders, matchCssLoaders);

const newloader = Object.assign({}, cssloader, {
  test: /\.module\.css$/,
  include: [src],
  loader: cssloader.loader.replace(matchCssLoaders, `$1$2?modules&localIdentName=${cssModulesNames}$3`)
})
config.module.loaders.push(newloader);
cssloader.test = new RegExp(`^(?!.*(module|bootstrap)).*${cssloader.test.source}`)
cssloader.loader = newloader.loader

config.module.loaders.push({
  test: /bootstrap\.css$/,
  include: [modules],
  loader: 'style-loader!css-loader'
})

// postcss
config.postcss = [].concat([
  require('precss')({}),
  require('autoprefixer')({}),
  require('cssnano')({})
])
// END postcss

// Roots
config.resolve.root = [src, modules]
config.resolve.alias = {
  'css': join(src, 'styles'),
  'containers': join(src, 'containers'),
  'components': join(src, 'components'),
  'utils': join(src, 'utils'),

  'styles': join(src, 'styles')
}
// end Roots

// Testing
if (isTest) {
  config.externals = {
    'react/addons': true,
    'react/lib/ReactContext': true,
    'react/lib/ExecutionEnvironment': true,
  }
  config.module.noParse = /[/\\]sinon\.js/;
  config.resolve.alias['sinon'] = 'sinon/pkg/sinon';

  config.plugins = config.plugins.filter(p => {
    const name = p.constructor.toString();
    const fnName = name.match(/^function (.*)\((.*\))/)

    const idx = [
      'DedupePlugin',
      'UglifyJsPlugin'
    ].indexOf(fnName[1]);
    return idx < 0;
  })
}
// End Testing

module.exports = config;
</code>```

I am serving the files using express using this script:

```<code>var express = require('express')
var app = express()

var path = require('path');

app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname, 'dist/index.html'));
});

app.listen(9000, function () {
  console.log('Example app listening on port 9000!')
})
</code>```

All I get is a blank page with this markup:

```<code><!doctype html>
  <head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
    <title>My title</title>
    <link rel="stylesheet" href="http://localhost:9000/stylesheet.css"/>
  </head>
  <body>
    <div id="root"></div>
    <script src="http://localhost:9000/javascript.js"></script>
  </body>
</code>```

Not sure what I'm missing, there doesn't seem to be any JS executing at all, and I'm not sure how to go about debugging minified JS...

Any help or pointers would be greatly apreciated.

Thanks

答: Your express server isn't configured to serve static files (other than the html). Add the express.static middleware before the wildcard route.

Body:
I'm pretty new to Webpack, and have followed this tutorial to add authentication to a React app I have been working on.

It all works fine in development, however I get a blank page when trying to run the distribution files.

Here's my webpack.config.js:

const NODE_ENV = process.env.NODE_ENV;
const dotenv = require('dotenv');

const webpack = require('webpack');
const fs      = require('fs');
const path    = require('path'),
      join    = path.join,
      resolve = path.resolve;

const getConfig = require('hjs-webpack');

const isDev  = NODE_ENV === 'development';
const isTest = NODE_ENV === 'test';

const root    = resolve(__dirname);
const src     = join(root, 'src');
const modules = join(root, 'node_modules');
const dest    = join(root, 'dist');

var config = getConfig({
  isDev: isDev,
  in: join(src, 'app.js'),
  out: dest,
  html: function (context) {
    return {
      'index.html': context.defaultTemplate({
        title: 'My Title',
        publicPath: isDev ? 'http://localhost:3000/' : 'http://localhost:9000/',
        meta: {
          'name': 'My name',
          'description': 'My desc'
        }
      })
    }
  }
});

// ENV variables
const dotEnvVars = dotenv.config();
const environmentEnv = dotenv.config({
  path: join(root, 'config', `${NODE_ENV}.config.js`),
  silent: true,
});
const envVariables =
    Object.assign({}, dotEnvVars, environmentEnv);

const defines =
  Object.keys(envVariables)
  .reduce((memo, key) => {
    const val = JSON.stringify(envVariables[key]);
    memo[`__${key.toUpperCase()}__`] = val;
    return memo;
  }, {
    __NODE_ENV__: JSON.stringify(NODE_ENV)
  });

config.plugins = [
  new webpack.DefinePlugin(defines)
].concat(config.plugins);
// END ENV variables

// CSS modules
const cssModulesNames = `${isDev ? '[path][name]__[local]__' : ''}[hash:base64:5]`;

const matchCssLoaders = /(^|!)(css-loader)($|!)/;

const findLoader = (loaders, match) => {
  const found = loaders.filter(l => l && l.loader && l.loader.match(match))
  return found ? found[0] : null;
}
// existing css loader
const cssloader =
  findLoader(config.module.loaders, matchCssLoaders);

const newloader = Object.assign({}, cssloader, {
  test: /\.module\.css$/,
  include: [src],
  loader: cssloader.loader.replace(matchCssLoaders, `$1$2?modules&localIdentName=${cssModulesNames}$3`)
})
config.module.loaders.push(newloader);
cssloader.test = new RegExp(`^(?!.*(module|bootstrap)).*${cssloader.test.source}`)
cssloader.loader = newloader.loader

config.module.loaders.push({
  test: /bootstrap\.css$/,
  include: [modules],
  loader: 'style-loader!css-loader'
})

// postcss
config.postcss = [].concat([
  require('precss')({}),
  require('autoprefixer')({}),
  require('cssnano')({})
])
// END postcss

// Roots
config.resolve.root = [src, modules]
config.resolve.alias = {
  'css': join(src, 'styles'),
  'containers': join(src, 'containers'),
  'components': join(src, 'components'),
  'utils': join(src, 'utils'),

  'styles': join(src, 'styles')
}
// end Roots

// Testing
if (isTest) {
  config.externals = {
    'react/addons': true,
    'react/lib/ReactContext': true,
    'react/lib/ExecutionEnvironment': true,
  }
  config.module.noParse = /[/\\]sinon\.js/;
  config.resolve.alias['sinon'] = 'sinon/pkg/sinon';

  config.plugins = config.plugins.filter(p => {
    const name = p.constructor.toString();
    const fnName = name.match(/^function (.*)\((.*\))/)

    const idx = [
      'DedupePlugin',
      'UglifyJsPlugin'
    ].indexOf(fnName[1]);
    return idx < 0;
  })
}
// End Testing

module.exports = config;

I am serving the files using express using this script:

var express = require('express')
var app = express()

var path = require('path');

app.get('*', function(req, res) {
  res.sendFile(path.resolve(__dirname, 'dist/index.html'));
});

app.listen(9000, function () {
  console.log('Example app listening on port 9000!')
})

All I get is a blank page with this markup:

<!doctype html>

    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
    <title>My title</title>
    <link rel="stylesheet" href="http://localhost:9000/stylesheet.css"/>

Not sure what I'm missing, there doesn't seem to be any JS executing at all, and I'm not sure how to go about debugging minified JS...

Any help or pointers would be greatly apreciated.

Thanks


问:
How to set horizontal progress bar based on total number of minutes in android?
Hi I want to set horizontal progress bar width based on total minutes.

For example

Total hours 7hrs 30 minutes - > 450 minutes

Xml

```<code><ProgressBar
   android:id="@+id/progress_bar_total_sleep"
   style="@style/SleepProgressFill"
   android:layout_width="270dp"
   android:layout_height="wrap_content"/>
</code>```

Please give any suggestion

答:
You can set MAX value of ProgressBar by using method ProgressBar.setMax(MAX_VALUE) from JAVA and from XML use attribute android:max="MAX_VALUE".

You need to set Progress value of ProgressBar to show the progress. You can do it by using method ProgressBar.setProgress(PROGRESS_VALUE) from JAVA and from XML use attribute android:progress="PROGRESS_VALUE".

Here is an example: (From XML)

```<code><ProgressBar
    android:id="@+id/progress_bar_total_sleep"
    android:layout_width="270dp"
    android:layout_height="wrap_content"
    android:max="1000"
    android:progress="450"
    style="?android:attr/progressBarStyleHorizontal" />
</code>```

If you want to change MAX and Progress value programmatically, Try this:

```<code>ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar_total_sleep);

// Max Minute
progressBar.setMax(1000);
// Progress Minute
progressBar.setProgress(450);
</code>```

OUTPUT:

Hope this will help~

Body:
Hi I want to set horizontal progress bar width based on total minutes.

For example

Total hours 7hrs 30 minutes - > 450 minutes

Xml

<ProgressBar
   android:id="@+id/progress_bar_total_sleep"
   style="@style/SleepProgressFill"
   android:layout_width="270dp"
   android:layout_height="wrap_content"/>

Please give any suggestion

Body:
You can set MAX value of ProgressBar by using method ProgressBar.setMax(MAX_VALUE) from JAVA and from XML use attribute android:max="MAX_VALUE".

You need to set Progress value of ProgressBar to show the progress. You can do it by using method ProgressBar.setProgress(PROGRESS_VALUE) from JAVA and from XML use attribute android:progress="PROGRESS_VALUE".

Here is an example: (From XML)

<ProgressBar
    android:id="@+id/progress_bar_total_sleep"
    android:layout_width="270dp"
    android:layout_height="wrap_content"
    android:max="1000"
    android:progress="450"
    style="?android:attr/progressBarStyleHorizontal" />

If you want to change MAX and Progress value programmatically, Try this:

ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar_total_sleep);

// Max Minute
progressBar.setMax(1000);
// Progress Minute
progressBar.setProgress(450);

OUTPUT:

Hope this will help~


问:
Invalid credentials when trying to authenticate via Facebook
Can't connect via facebook anymore on my rails app

Here is the error I get

GET https://www.myapp.com/auth/failure?message=invalid_credentials&strategy=facebook 404

No changes were made to the app and it worked fine 2 days ago

答:
Same question is asked here:

Omniauth: callback not firing, returns failure with "invalid credentials"

```<code>bundle update omniauth
bundle update omniauth-facebook
</code>```

solves the issue.

Body:
Same question is asked here:

Omniauth: callback not firing, returns failure with "invalid credentials"

bundle update omniauth
bundle update omniauth-facebook

solves the issue.


问:
Strange behaviour with for loop and size_t
```<code> size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = 0; i < size; i++) {
    printf("%d ", i);
 }
</code>```

The above code (using gcc) outptus

4

0 1 2 3

```<code> size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < size; i++) {
    printf("%d ", i);
 }
</code>```

This code (i is initialized to -1) outputs only 4 and nothing in the loop.

```<code> size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < (int) size; i++) {
    printf("%d ", i);
 }
</code>```

Adding a cast makes the code run fine again. The output is

4

-1 0 1 2 3

What's going wrong in the second code? Why doesn't printf go wrong anywhere?

答: size_t is unsigned. When you cast size to int, you're casting back to signed, and the comparison works.

Body:
 size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = 0; i < size; i++) {
    printf("%d ", i);
 }

The above code (using gcc) outptus

4

0 1 2 3

 size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < size; i++) {
    printf("%d ", i);
 }

This code (i is initialized to -1) outputs only 4 and nothing in the loop.

 size_t size = sizeof(int);
 printf("%d\n", size);

 int i;
 for (i = -1; i < (int) size; i++) {
    printf("%d ", i);
 }

Adding a cast makes the code run fine again. The output is

4

-1 0 1 2 3

What's going wrong in the second code? Why doesn't printf go wrong anywhere?


问:
Modelling a Meals / Recipes / Foods database
I am trying to model a database containing the following tables:

```<code>Meals (MealId)
MealRecipes (MealId, RecipeId)
MealFoods (MealId, FoodId)

Recipes (RecipeId)
RecipeFoods (RecipeId, FoodId)
Foods (FoodId)
</code>```

A Recipe is composed of N Foods (Apple, Salmon, ...)

But when I build a Meal it can contain Recipes (Salmond with vegetables) but also a Food (Apple) ...

My biggest problem is with building the Meal with both Recipes and Foods.

UPDATE

One important thing is the order of the Recipes / Food in a Meal. So another approach would be:

```<code>Meals (MealId)
MealSteps (MealId, StepNumber, RecipeId, FoodId)
</code>```

Where RecipeId or FoodId, either one, could be null. But not both.

答:
I think you have a couple of related concerns here - it might help you to specify the business domain in semi-formal language.

I think it's something like:

The system has many meals.

A meal is made up of one..n courses, in a sequence.

A course is either an ingredient or a recipe.

A recipe is made up of 1..n ingredients (and instructions, presumably).

If that's true, your second data model seems okay - but you have to consider how to model inheritance in your database - both a recipe and an ingredient can make up a course.
There's no single best solution to that problem, but you'll find many questions on Stack Overflow to help.

Finally, you might want to consider the possibility that a course would be made up of several ingredients or recipes served together, e.g. soup and bread.

Body:
I am trying to model a database containing the following tables:

Meals (MealId)
MealRecipes (MealId, RecipeId)
MealFoods (MealId, FoodId)

Recipes (RecipeId)
RecipeFoods (RecipeId, FoodId)
Foods (FoodId)

A Recipe is composed of N Foods (Apple, Salmon, ...)

But when I build a Meal it can contain Recipes (Salmond with vegetables) but also a Food (Apple) ...

My biggest problem is with building the Meal with both Recipes and Foods.

UPDATE

One important thing is the order of the Recipes / Food in a Meal. So another approach would be:

Meals (MealId)
MealSteps (MealId, StepNumber, RecipeId, FoodId)

Where RecipeId or FoodId, either one, could be null. But not both.


问:
Flatbutton(Input handler) doesn't seems to work
I try to use file uploader from materila-ui, but it doesn't seems to work and get the input from selecting file.
 Anyone have any advice how to get the input from file selector and handle it. </p>

```<code><FlatButton
            icon={<i className="material-icons">attachment</i>}
            onclick={e => this._handleChange(e)}
            onchange={e => this._openFileDialog(e)}
          >
            <input type="file" style={styles.uploadInput} />
          </FlatButton>
</code>```

<p>http://material-ui.com/#/components/flat-button </p>

答:
Instead of defining onChange event on FlatButton, define it on input element, Write it like this:

```<code><FlatButton
      icon={<i className="material-icons">attachment</i>}
      onClick={e => this._handleChange(e)}
>
    <input type="file" onChange={this._handleFileUpload.bind(this)}/>
</FlatButton>
</code>```

Then in onChange method by using e.target.files, you can access the selected file:

```<code>_handleFileUpload(e){
   console.log(e.target.files);
}
</code>```

Body:
I try to use file uploader from materila-ui, but it doesn't seems to work and get the input from selecting file.
 Anyone have any advice how to get the input from file selector and handle it.

<FlatButton
            icon={attachment}
            onclick={e => this._handleChange(e)}
            onchange={e => this._openFileDialog(e)}
          >
            <input type="file" style={styles.uploadInput} />
          </FlatButton>

http://material-ui.com/#/components/flat-button

Body:
Instead of defining onChange event on FlatButton, define it on input element, Write it like this:

<FlatButton
      icon={<i className="material-icons">attachment</i>}
      onClick={e => this._handleChange(e)}
>
    <input type="file" onChange={this._handleFileUpload.bind(this)}/>
</FlatButton>

Then in onChange method by using e.target.files, you can access the selected file:

_handleFileUpload(e){
   console.log(e.target.files);
}


问:
Cannot read usernames from file
I am trying to implement a registration panel with username password and email only. I put all the usernames and passwords in a text file "usernames.txt". But my problem is not working properly if user clicks the submit button and the username already exists nothing happens( it should display JOptionPane with text "Username already exists!" ). here is my code :

```<code>submitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader("usernames.txt"));
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            try {
                String line = br.readLine();
                StringBuilder sb = new StringBuilder();
                Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+)$");
                while (line != null) {
                    sb.append(line); //
                    sb.append(System.lineSeparator()); //
                    line = br.readLine();
                }
                String everything = sb.toString();
                Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(everything);

                //if username exists!
                while (userNameAndPasswordMatcher.matches()) {
                    String username = userNameAndPasswordMatcher.group(1);
                    String password = userNameAndPasswordMatcher.group(2);

                    if (username.equals(usernameTextField.getText())) {
                        int result = JOptionPane.showConfirmDialog(null, "Username already exists!", "Registration incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                    }
                }

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });
</code>```

Here you can see a pic from my panel

答:
although the answer from @StephenC works for your case it is pretty specific and I think it could be tackled more elegantly.

How about you define a RegEx-Pattern which splits the username and Password into two groups, since you stated

the usernames.txt are in the format {Username} {Password}

you could use the RegEx ^(\S+) (\S+)$, which means a non-null set of non-whitespace characters in group 1 followed by a space and then a non-null set of non-whitespace characters(check it out at https://regex101.com/)

Here is it implemented with Javas own libraries

```<code>private static final Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+)$");

public static void checkInput(String input) throws IOException {
  try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("usernames.txt"))))) {
    String line = br.readLine();
    while(line != null) {
      Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(line);

      if(userNameAndPasswordMatcher.matches()) {
        String username = userNameAndPasswordMatcher.group(1);
        String password = userNameAndPasswordMatcher.group(2);

        if(username.equals(input)) {
          System.out.println("Username exists!");
          System.out.println("Password is: " + password);
          break;
        }
      }
      line = br.readLine();
    }
  }
}
</code>```

I used this to test it

```<code>public static void main(String[] args) throws IOException {
  System.out.println("main > calling checkInput('Gary')..");
  checkInput("Gary");
  System.out.println("main > calling checkInput('Donald')..");
  checkInput("Donald");
  System.out.println("main > calling checkInput('Gordon')..");
  checkInput("Gordon");
}
</code>```

and here is my test data

```<code>Peter 123peter567
Gary newman
Gordon fr33m4n
</code>```

and my output

```<code>main > calling checkInput('Gary')..
Username exists!
Password is: newman
main > calling checkInput('Donald')..
main > calling checkInput('Gordon')..
Username exists!
Password is: fr33m4n
</code>```

Title: Cannot read usernames from file

Body:
I am trying to implement a registration panel with username password and email only. I put all the usernames and passwords in a text file "usernames.txt". But my problem is not working properly if user clicks the submit button and the username already exists nothing happens( it should display JOptionPane with text "Username already exists!" ). here is my code :

submitButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new FileReader("usernames.txt"));
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            try {
                String line = br.readLine();
                StringBuilder sb = new StringBuilder();
                Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+)$");
                while (line != null) {
                    sb.append(line); //
                    sb.append(System.lineSeparator()); //
                    line = br.readLine();
                }
                String everything = sb.toString();
                Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(everything);

                //if username exists!
                while (userNameAndPasswordMatcher.matches()) {
                    String username = userNameAndPasswordMatcher.group(1);
                    String password = userNameAndPasswordMatcher.group(2);

                    if (username.equals(usernameTextField.getText())) {
                        int result = JOptionPane.showConfirmDialog(null, "Username already exists!", "Registration incomplete", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);
                    }
                }

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                try {
                    br.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
    });

Here you can see a pic from my panel

Body:
although the answer from @StephenC works for your case it is pretty specific and I think it could be tackled more elegantly.

How about you define a RegEx-Pattern which splits the username and Password into two groups, since you stated

the usernames.txt are in the format {Username} {Password}

you could use the RegEx ^(\S+) (\S+)$, which means a non-null set of non-whitespace characters in group 1 followed by a space and then a non-null set of non-whitespace characters(check it out at https://regex101.com/)

Here is it implemented with Javas own libraries

private static final Pattern usernameAndPasswordPattern = Pattern.compile("^(\\S+) (\\S+)$");

public static void checkInput(String input) throws IOException {
  try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("usernames.txt"))))) {
    String line = br.readLine();
    while(line != null) {
      Matcher userNameAndPasswordMatcher = usernameAndPasswordPattern.matcher(line);

      if(userNameAndPasswordMatcher.matches()) {
        String username = userNameAndPasswordMatcher.group(1);
        String password = userNameAndPasswordMatcher.group(2);

        if(username.equals(input)) {
          System.out.println("Username exists!");
          System.out.println("Password is: " + password);
          break;
        }
      }
      line = br.readLine();
    }
  }
}

I used this to test it

public static void main(String[] args) throws IOException {
  System.out.println("main > calling checkInput('Gary')..");
  checkInput("Gary");
  System.out.println("main > calling checkInput('Donald')..");
  checkInput("Donald");
  System.out.println("main > calling checkInput('Gordon')..");
  checkInput("Gordon");
}

and here is my test data

Peter 123peter567
Gary newman
Gordon fr33m4n

and my output

main > calling checkInput('Gary')..
Username exists!
Password is: newman
main > calling checkInput('Donald')..
main > calling checkInput('Gordon')..
Username exists!
Password is: fr33m4n


问:
.Net Charts - X Axis with Different Intervals
I am using .Net Charts. In that, I have displayed a line chart with an Interval of 28 Days.

Here is my code:

```<code> Chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = 1;
 Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = min;
 Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = max;
 Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 28;
</code>```

But, one of my situation comes like,

28 Days Interval, 35 Days Interval, 28 Days Interval etc. Is that possible to have different Intervals.

答:
No, Interval is an Axis property and there can only be one.

You can work around this restriction by drawing gridlines and labels on your own.

Let's assume you have a list of stop points, i.e. the indices of the DataPoints where you want a GridLine to appear:

```<code>List<int> stops = new List<int>();
</code>```

After adding a few test numbers stops.AddRange(new[] { 12, 23, 42, 52, 82 }); we can code the PostPaint event of the Chart to draw lines:

```<code>private void chart_PostPaint(object sender, ChartPaintEventArgs e)
{
    Graphics g = e.ChartGraphics.Graphics;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

    ChartArea ca = chart.ChartAreas[0];

    Font font = ca.AxisX.LabelStyle.Font;
    Color col = ca.AxisX.MajorGrid.LineColor;
    int padding = 10; // pad the labels from the axis

    double aymin = ca.AxisY.Minimum;
    double aymax = ca.AxisY.Maximum;

    int y0 = (int)ca.AxisY.ValueToPixelPosition(aymin);
    int y1 = (int)ca.AxisY.ValueToPixelPosition(aymax);

    foreach (int sx  in stops)
    {
        int x = (int)ca.AxisX.ValueToPixelPosition(chart.Series[0].Points[sx].XValue);

        using (Pen pen = new Pen(col))
            g.DrawLine(pen, x, y0, x, y1);

        string s =  chart.Series[0].Points[sx].XValue + "";
        if (ca.AxisX.LabelStyle.Format != "") s = string.Format(ax.LabelStyle.Format, s);

        SizeF sz = g.MeasureString(s, font, 999);
        g.DrawString(s, font, Brushes.Black, (int)(x - sz.Width / 2) , y0 + padding);
    }
}
</code>```

After turning off the original MajorGrid etc..

```<code>ChartArea ca = chart.ChartAreas[0];

ca.AxisX.MajorGrid.Enabled = false;
ca.AxisX.MajorTickMark.Enabled = false;
ca.AxisX.LabelStyle.Enabled = false;
</code>```

..this is the result:

Notes:

Most of the code are just simple preparations and references. The actual drawing are 2 methods and three or four more lines to get the coordinates..

I have stored the DataPoint indices in my List. If you want the custom GridLines to be independent of DataPoints you can instead store the Values and change the List to a List<double> andthe two references from  chart.Series[0].Points[sx].XValue
to accessing the stop values sx directly.

Change the padding value to suit you..

We can access the axes' minima and maxima values freely, even if they are actually set to Auto. This is because we are in a Paintevent. Otherwise we would have to call RecalculateAxesScale() on the ChartArea..

Feel free to make the Black label brush dynamic as well..

Body:
I am using .Net Charts. In that, I have displayed a line chart with an Interval of 28 Days.

Here is my code:

 Chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = 1;
 Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = min;
 Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = max;
 Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 28;

But, one of my situation comes like,

28 Days Interval, 35 Days Interval, 28 Days Interval etc. Is that possible to have different Intervals.

Body:
No, Interval is an Axis property and there can only be one.

You can work around this restriction by drawing gridlines and labels on your own.

Let's assume you have a list of stop points, i.e. the indices of the DataPoints where you want a GridLine to appear:

List<int> stops = new List<int>();

After adding a few test numbers stops.AddRange(new[] { 12, 23, 42, 52, 82 }); we can code the PostPaint event of the Chart to draw lines:

private void chart_PostPaint(object sender, ChartPaintEventArgs e)
{
    Graphics g = e.ChartGraphics.Graphics;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;

    ChartArea ca = chart.ChartAreas[0];

    Font font = ca.AxisX.LabelStyle.Font;
    Color col = ca.AxisX.MajorGrid.LineColor;
    int padding = 10; // pad the labels from the axis

    double aymin = ca.AxisY.Minimum;
    double aymax = ca.AxisY.Maximum;

    int y0 = (int)ca.AxisY.ValueToPixelPosition(aymin);
    int y1 = (int)ca.AxisY.ValueToPixelPosition(aymax);

    foreach (int sx  in stops)
    {
        int x = (int)ca.AxisX.ValueToPixelPosition(chart.Series[0].Points[sx].XValue);

        using (Pen pen = new Pen(col))
            g.DrawLine(pen, x, y0, x, y1);

        string s =  chart.Series[0].Points[sx].XValue + "";
        if (ca.AxisX.LabelStyle.Format != "") s = string.Format(ax.LabelStyle.Format, s);

        SizeF sz = g.MeasureString(s, font, 999);
        g.DrawString(s, font, Brushes.Black, (int)(x - sz.Width / 2) , y0 + padding);
    }
}

After turning off the original MajorGrid etc..

ChartArea ca = chart.ChartAreas[0];

ca.AxisX.MajorGrid.Enabled = false;
ca.AxisX.MajorTickMark.Enabled = false;
ca.AxisX.LabelStyle.Enabled = false;

..this is the result:

Notes:

Most of the code are just simple preparations and references. The actual drawing are 2 methods and three or four more lines to get the coordinates..

I have stored the DataPoint indices in my List. If you want the custom GridLines to be independent of DataPoints you can instead store the Values and change the List to a List<double> andthe two references from  chart.Series[0].Points[sx].XValue
to accessing the stop values sx directly.

Change the padding value to suit you..

We can access the axes' minima and maxima values freely, even if they are actually set to Auto. This is because we are in a Paintevent. Otherwise we would have to call RecalculateAxesScale() on the ChartArea..

Feel free to make the Black label brush dynamic as well..


问:
R - Finding the first element/position in a vector satisfying an inequality, for each element in a vector
Let's say I have a vector Y. If I want to know where Y is greater than 4, I can use something like which(Y>4), something with the function Position, etc. However, now I have a vector X for which I want to obtain a vector with elements which(Y>x) for each element x of X. I could do this with a loop, but for the large vectors X I want to apply this on, this is very inefficient.

What is a more efficient, vectorised way of achieving what I want?

答:
You could use the function outer from the base package:

If you want a list of all indices that satisfy Y > X[i]:

```<code>## Test data:
Y <- c(3,6,7,2,9,6,12,5,2,8)
X <- c(4,6,8)

indicesList <- apply(X = outer(Y, X, '>'), MARGIN = 2, FUN = which)

> indicesList
[[1]]
[1]  2  3  5  6  7  8 10

[[2]]
[1]  3  5  7 10

[[3]]
[1] 5 7
</code>```

If you just want to find the first element in Y satisfying Y > X[i]:

```<code>firstIndicesVec <- apply(X = outer(Y, X, '>'), MARGIN = 2, FUN = function(x) min(which(x)))

> firstIndicesVec
[1] 2 3 5
</code>```

Body:
You could use the function outer from the base package:

If you want a list of all indices that satisfy Y > X[i]:

## Test data:
Y <- c(3,6,7,2,9,6,12,5,2,8)
X <- c(4,6,8)

indicesList <- apply(X = outer(Y, X, '>'), MARGIN = 2, FUN = which)

> indicesList
[[1]]
[1]  2  3  5  6  7  8 10

[[2]]
[1]  3  5  7 10

[[3]]
[1] 5 7

If you just want to find the first element in Y satisfying Y > X[i]:

firstIndicesVec <- apply(X = outer(Y, X, '>'), MARGIN = 2, FUN = function(x) min(which(x)))

> firstIndicesVec
[1] 2 3 5


问:
Change Text View on button click in ViewPager
I have used a viewpager in my app in which i have a number of pagers. In this pages i have a TextView and a Button and i want to be able to change the textview in the one pager when the button in that pager is clicked.

I have the code below, but the text doesn't change when i click on the button.

```<code>@Override
public Object instantiateItem(ViewGroup collection, int position) {
    View view = null;
    LayoutInflater h = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = h.inflate(R.layout.content, null);

    tvName = (TextView) view.findViewById(R.id.tvName);
    btnView = (Button) view.findViewById(R.id.viewBTN);
    tvName.setText("Original Text")

    btnView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tvName.setText("new Test")
        }
    });

    collection.addView(view);

    return view;

}
</code>```

答: Use the same code in the java file of that page. example If your first page is named as page1.java than make the change in that java file . For more details of viewpager you can visit badassandroiddevlopers.blogspot.in .  </p>

Body:
I have used a viewpager in my app in which i have a number of pagers. In this pages i have a TextView and a Button and i want to be able to change the textview in the one pager when the button in that pager is clicked.

I have the code below, but the text doesn't change when i click on the button.

@Override
public Object instantiateItem(ViewGroup collection, int position) {
    View view = null;
    LayoutInflater h = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = h.inflate(R.layout.content, null);

    tvName = (TextView) view.findViewById(R.id.tvName);
    btnView = (Button) view.findViewById(R.id.viewBTN);
    tvName.setText("Original Text")

    btnView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tvName.setText("new Test")
        }
    });

    collection.addView(view);

    return view;

}


问:
Create a symfony2 remember me cookie manually (FOSUserBundle)
Could somebody explain how you can manually create a remember me cookie in a controller?

I want the users to stay logged in after they pressed the "register"
button, without having to login with their credentials afterwards.

I've tried to create a cookie manually but i'm guessing the cookie
value is incorrect, and therefor the "remember me" functionality
doesn't work.
A cookie with the correct name gets set. I've checked that.

The remember me functionality works as expected when using the normal
login procedure with the user's credentials.

security.yml
security.yml remember me

```<code>security:
   firewalls:
       main:
           remember_me:
               lifetime: 86400
               domain:   ~
               path:     /
               key:      myKey
</code>```

This is what I have now, even though the cookie is set, it doesn't work.

```<code>$um = $this->get('fos_user.user_manager');
$member = $um->createUser();

… Form stuff with bindRequest etc.

$um->updatePassword($member);
$um->updateUser($member);

$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';

$token = new RememberMeToken($member, $providerKey, $securityKey,
$member->getRoles());
$this->container->get('security.context')->setToken($token);

$redirectResponse = new RedirectResponse($url);
$redirectResponse->headers->setCookie(
   new \Symfony\Component\HttpFoundation\Cookie(
       'REMEMBERME',
       base64_encode(implode(':', array($member->getUsername(),
$member->getPassword()))),
       time() + 60*60*24
   )
);
return $redirectResponse;
</code>```

Update:

I've also tried working with the
PersistentTokenBasedRememberMeServices class with reflection but it does not work. a cookie gets set but it's not working

```<code>$token = $this->container->get('security.context')->getToken();

$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';

$persistenService = new
PersistentTokenBasedRememberMeServices(array($um), $providerKey,
$securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' =>
null, 'secure' => false, 'httponly' => true,
'lifetime' => 86400));
$persistenService->setTokenProvider(new InMemoryTokenProvider());

$method = new \ReflectionMethod('Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices',
'onLoginSuccess');
 $method->setAccessible(true);
$method->invoke($persistenService, $request, $redirectResponse, $token);
</code>```

I'm using Symfony v2.0.5 and FOSUserBundle 1.0

UPDATE 2:

I've tried a 3rd way. The same as above but without reflection:

```<code>$token = $this->container->get('security.context')->getToken();

$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';

$persistenService = new PersistentTokenBasedRememberMeServices(array($um), $providerKey, $securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' => null, 'secure' => false, 'httponly' => true, 'lifetime' => 31536000, 'always_remember_me' => true, 'remember_me_parameter' => '_remember_me'));
$persistenService->setTokenProvider(new InMemoryTokenProvider());

$persistenService->loginSuccess($request, $redirectResponse, $token);
</code>```

答:
I had the same issue when I tried to set REMEMBERME cookie an User after a connection by token, using Guard Authentication.

In this situation I had no Response object to be able to use $response->headers->setCookie() and needs to use setcookie().
And in this situation, create a RedirectResponse is not appropriate.

This needs to be refactored but I post the raw procedural on which I based my service

```<code>$expires = time() + 2628000;
$hash = hash_hmac(
    'sha256',
     get_class($user).$user->getUsername().$expires.$user->getPassword(), 'secret in parameters.yml'
);
$value = base64_encode(implode(':', [get_class($user), base64_encode($user->getUsername()), $expires, $hash]));
setcookie(
    'REMEMBERME',
    $value,
    $expires,
    '/',
    'host',
    'ssl boolean',
    true
);
</code>```

Body:
Could somebody explain how you can manually create a remember me cookie in a controller?

I want the users to stay logged in after they pressed the "register"
button, without having to login with their credentials afterwards.

I've tried to create a cookie manually but i'm guessing the cookie
value is incorrect, and therefor the "remember me" functionality
doesn't work.
A cookie with the correct name gets set. I've checked that.

The remember me functionality works as expected when using the normal
login procedure with the user's credentials.

security.yml
security.yml remember me

security:
   firewalls:
       main:
           remember_me:
               lifetime: 86400
               domain:   ~
               path:     /
               key:      myKey

This is what I have now, even though the cookie is set, it doesn't work.

$um = $this->get('fos_user.user_manager');
$member = $um->createUser();

… Form stuff with bindRequest etc.

$um->updatePassword($member);
$um->updateUser($member);

$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';

$token = new RememberMeToken($member, $providerKey, $securityKey,
$member->getRoles());
$this->container->get('security.context')->setToken($token);

$redirectResponse = new RedirectResponse($url);
$redirectResponse->headers->setCookie(
   new \Symfony\Component\HttpFoundation\Cookie(
       'REMEMBERME',
       base64_encode(implode(':', array($member->getUsername(),
$member->getPassword()))),
       time() + 60*60*24
   )
);
return $redirectResponse;

Update:

I've also tried working with the
PersistentTokenBasedRememberMeServices class with reflection but it does not work. a cookie gets set but it's not working

$token = $this->container->get('security.context')->getToken();

$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';

$persistenService = new
PersistentTokenBasedRememberMeServices(array($um), $providerKey,
$securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' =>
null, 'secure' => false, 'httponly' => true,
'lifetime' => 86400));
$persistenService->setTokenProvider(new InMemoryTokenProvider());

$method = new \ReflectionMethod('Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices',
'onLoginSuccess');
 $method->setAccessible(true);
$method->invoke($persistenService, $request, $redirectResponse, $token);

I'm using Symfony v2.0.5 and FOSUserBundle 1.0

UPDATE 2:

I've tried a 3rd way. The same as above but without reflection:

$token = $this->container->get('security.context')->getToken();

$providerKey = $this->container->getParameter('fos_user.firewall_name');
$securityKey = 'myKey';

$persistenService = new PersistentTokenBasedRememberMeServices(array($um), $providerKey, $securityKey, array('path' => '/', 'name' => 'REMEMBERME', 'domain' => null, 'secure' => false, 'httponly' => true, 'lifetime' => 31536000, 'always_remember_me' => true, 'remember_me_parameter' => '_remember_me'));
$persistenService->setTokenProvider(new InMemoryTokenProvider());

$persistenService->loginSuccess($request, $redirectResponse, $token);

Body:
I had the same issue when I tried to set REMEMBERME cookie an User after a connection by token, using Guard Authentication.

In this situation I had no Response object to be able to use $response->headers->setCookie() and needs to use setcookie().
And in this situation, create a RedirectResponse is not appropriate.

This needs to be refactored but I post the raw procedural on which I based my service

$expires = time() + 2628000;
$hash = hash_hmac(
    'sha256',
     get_class($user).$user->getUsername().$expires.$user->getPassword(), 'secret in parameters.yml'
);
$value = base64_encode(implode(':', [get_class($user), base64_encode($user->getUsername()), $expires, $hash]));
setcookie(
    'REMEMBERME',
    $value,
    $expires,
    '/',
    'host',
    'ssl boolean',
    true
);


问:
Assigning two tables separate css styles
Why is it that when I apply a style to one table it effects the other even though I've assigned them separate classes. Table two is being pushed down by table twos padding. Have a look at this demo I created. How can I avoid this?

```<code><table id="one">
    <tr>
      <td>Hello</td>
    </tr>
  </table>

  <table id="two">
    <tr>
      <td>Goodbye</td>
    </tr>
  </table>
</code>```

css:

```<code>table{
  display: inline-block;
}

#one{
  background-color: blue;
  padding-top: 50px;
}

#two{
  background-color: orange;
}
</code>```

https://jsfiddle.net/b7qdcub1/

答:
You will have to add these styles to the tables:

```<code>table {
   display: block;
   float: left;
}
</code>```

Here is an updated fiddle:https://jsfiddle.net/b7qdcub1/2/

Body:
Why is it that when I apply a style to one table it effects the other even though I've assigned them separate classes. Table two is being pushed down by table twos padding. Have a look at this demo I created. How can I avoid this?

      Hello

      Goodbye

css:

table{
  display: inline-block;
}

#one{
  background-color: blue;
  padding-top: 50px;
}

#two{
  background-color: orange;
}

https://jsfiddle.net/b7qdcub1/

Body:
You will have to add these styles to the tables:

table {
   display: block;
   float: left;
}

Here is an updated fiddle:https://jsfiddle.net/b7qdcub1/2/


问:
Quantile results for the entire dataframe
I have a fairly large data set consisting of around 100 variables and around
1 million observations. The data set contains both numeric and categorical variables.
I want to calculate the quantile for all the numeric variables, so when I try the following:
quantile(dat1, c(.10, .30, .5, .75, .9, na.rm = TRUE)

I get an error in R saying "non-numeric argument to binary operator"

So could anyone please suggest me the appropriate codes for this? Appreciate all your help and thanks

答:
Quantile of all numeric columns

```<code># sample data with numeric and character class values
df <- data.frame(a = 1:5, b= 1:5, c = letters[1:5])
col_numeric <- which( sapply(df, is.numeric ) )   # get numeric column indices
quantile( x = unlist( df[,  col_numeric] ),
          c(.10, .30, .5, .75, .9),
          na.rm = TRUE )

# 10% 30% 50% 75% 90%
#  1   2   3   4   5
</code>```

Quantile of individual numeric column

```<code>sapply( col_numeric, function( y ) {
  quantile( x = unlist( df[,  y ] ),
            c(.10, .30, .5, .75, .9),
            na.rm = TRUE )
})

#       a   b
# 10% 1.4 1.4
# 30% 2.2 2.2
# 50% 3.0 3.0
# 75% 4.0 4.0
# 90% 4.6 4.6
</code>```

Since your real data is big, you could use data.table library for efficiency.

```<code>library('data.table')
setDT(df)[, lapply( .SD, quantile, probs = c(.10, .30, .5, .75, .9), na.rm = TRUE ), .SDcols = col_numeric ]
</code>```

Body:
Quantile of all numeric columns

# sample data with numeric and character class values
df <- data.frame(a = 1:5, b= 1:5, c = letters[1:5])
col_numeric <- which( sapply(df, is.numeric ) )   # get numeric column indices
quantile( x = unlist( df[,  col_numeric] ),
          c(.10, .30, .5, .75, .9),
          na.rm = TRUE )

# 10% 30% 50% 75% 90%
#  1   2   3   4   5

Quantile of individual numeric column

sapply( col_numeric, function( y ) {
  quantile( x = unlist( df[,  y ] ),
            c(.10, .30, .5, .75, .9),
            na.rm = TRUE )
})

#       a   b
# 10% 1.4 1.4
# 30% 2.2 2.2
# 50% 3.0 3.0
# 75% 4.0 4.0
# 90% 4.6 4.6

Since your real data is big, you could use data.table library for efficiency.

library('data.table')
setDT(df)[, lapply( .SD, quantile, probs = c(.10, .30, .5, .75, .9), na.rm = TRUE ), .SDcols = col_numeric ]


问:
Using MobX observable decorators with create-react-app
The MobX docs tell me I must "use the transform plugin transform-decorators-legacy and make sure it is first in the plugins list", in order for the decorators to work. The MobX boilerplate project suggests I need a .babelrc like:

```<code>{
  "presets": [
    "react",
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy", "react-hot-loader/babel"]
}
</code>```

How do I do that with a create-react-app generated project? Any attempt to use @ decorators errors. There is no .babelrc even after the project is 'ejected'.

答:
You can use https://www.npmjs.com/package/react-app-rewire-mobx

React App Rewired will give you access to the config than you just need to setup the package.

```<code>npm install react-app-rewired --save

// create a file named config-overrides.js

/* config-overrides.js */

const rewireMobX = require('react-app-rewire-mobx');

module.exports = function override(config, env) {
  config = rewireMobX(config, env);
  return config;
}
</code>```

Note:
This saves you from ejecting.  CRA does not support modifying the config https://github.com/facebookincubator/create-react-app/issues/99#issuecomment-234657710.

Body:
The MobX docs tell me I must "use the transform plugin transform-decorators-legacy and make sure it is first in the plugins list", in order for the decorators to work. The MobX boilerplate project suggests I need a .babelrc like:

{
  "presets": [
    "react",
    "es2015",
    "stage-1"
  ],
  "plugins": ["transform-decorators-legacy", "react-hot-loader/babel"]
}

How do I do that with a create-react-app generated project? Any attempt to use @ decorators errors. There is no .babelrc even after the project is 'ejected'.

Body:
You can use https://www.npmjs.com/package/react-app-rewire-mobx

React App Rewired will give you access to the config than you just need to setup the package.

npm install react-app-rewired --save

// create a file named config-overrides.js

/* config-overrides.js */

const rewireMobX = require('react-app-rewire-mobx');

module.exports = function override(config, env) {
  config = rewireMobX(config, env);
  return config;
}

Note:
This saves you from ejecting.  CRA does not support modifying the config https://github.com/facebookincubator/create-react-app/issues/99#issuecomment-234657710.


问:
How do I make intellij Idea to highlight Scala script correctly with #! (shebang)
How do I make intellij Idea to highlight Scala script correctly.

Attempt 1
change filename to 'test.sc' . Intellij does not like the first line i.e it is not valid scala comment syntax

Attempt 2
change filename to 'test.sh' . Intellij thinks all of the syntax is bash script.

filenName = ./test.sh

```<code>#!/usr/bin/env amm
import ammonite.ops._ , ImplicitWd._

println("Stop script")
val x = 1 + 1
</code>```

答:
If you need to preserve .sc extension here is a little trick

change shebang to #! /usr/bin/env amm which is still a valid shebang

put a file named #!.scala next to your script with the content:

class CLZ {
  def /(that: CLZ): CLZ = this
  def amm: Unit = {}
}
object #! extends CLZ
object usr extends CLZ
object bin extends CLZ
object env extends CLZ
```

Now, your script is properly highlighted

Update

JetBrains published a blog article about support for Ammonite.

Body:
How do I make intellij Idea to highlight Scala script correctly.

Attempt 1
change filename to 'test.sc' . Intellij does not like the first line i.e it is not valid scala comment syntax

Attempt 2
change filename to 'test.sh' . Intellij thinks all of the syntax is bash script.

filenName = ./test.sh

#!/usr/bin/env amm
import ammonite.ops._ , ImplicitWd._

println("Stop script")
val x = 1 + 1

Body:
If you need to preserve .sc extension here is a little trick

change shebang to #! /usr/bin/env amm which is still a valid shebang

put a file named #!.scala next to your script with the content:

class CLZ {
  def /(that: CLZ): CLZ = this
  def amm: Unit = {}
}
object #! extends CLZ
object usr extends CLZ
object bin extends CLZ
object env extends CLZ

Now, your script is properly highlighted

Update

JetBrains published a blog article about support for Ammonite.


问:
java regex pattern matching vs schema validation
Please consider the regex pattern : .*[a-zA-Z0-9\\-\\_].*.

If I use Java regex pattern matching to match "-", it says it is true.

```<code>String regexCostcode1=".*[a-zA-Z0-9\\-\\_].*";
Pattern regex_costcode=Pattern.compile(regexCostcode1);
String test="-";
Matcher m = regex_costcode.matcher(test);
System.out.println(m.matches());
</code>```

This prints true.

But same regex fails for "-" in XSD schema validation.

I checked using http://regexr.com/ it fails to match "-".

So why it is matching using Java pattern matching?

答:
For non-Java regexes you don't need to use double back-slashes. So your regex should be .*[a-zA-Z0-9\\-\\_].* in Java and .*[a-zA-Z0-9\-\_].* in XSD schema validation.

If you input .*[a-zA-Z0-9\\-\\_].* in the site you mentioned, it tells you that \\-\\ is being interpreted as a "range of characters from \ to \" since \\ is just an escaped back-slash.

If you input .*[a-zA-Z0-9\-\_].* it interprets \- as just an escaped hypen and correctly matches -.

Body:
Please consider the regex pattern : .*[a-zA-Z0-9\\-\\_].*.

If I use Java regex pattern matching to match "-", it says it is true.

String regexCostcode1=".*[a-zA-Z0-9\\-\\_].*";
Pattern regex_costcode=Pattern.compile(regexCostcode1);
String test="-";
Matcher m = regex_costcode.matcher(test);
System.out.println(m.matches());

This prints true.

But same regex fails for "-" in XSD schema validation.

I checked using http://regexr.com/ it fails to match "-".

So why it is matching using Java pattern matching?


问:
Should you lock resources when reading values?
When doing thread synchronization in C# should I also lock an object when I read a value or just changing it?

for example I have Queue<T> object. Should I just lock it when doing the Enqueue and Dequeue or should I also lock it when checking values like Count?

答: If you don't lock it, you may get an older value. A race condition could occur such that a write operation is performed changing Count, but you would get the value before the change. For example, if the queue has only one item, and a thread calls dequeue, another thread may read the count, find it still 1, and call dequeue again. The second call won't be done until the lock is granted, but at that time the queue would actually be empty.

OwnerDisplayName: Superdumbell

OwnerDisplayName: Hosam Aly


问:
Calculating days between two dates in java with time zone
As per this question, I have calculated the days between two dates in java.
The program is below

```<code>SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is  28.

答:
Using java 8 new Date Time APi</p>

```<code>    import java.time.*;
    import java.time.temporal.*;

    ZonedDateTime z1 = date1.toInstant().atZone(ZoneId.systemDefault());
    ZonedDateTime z2 = date2.toInstant().atZone(ZoneId.systemDefault());
    long diff = ChronoUnit.DAYS.between(z1, z2);  // 29
</code>```

Body:
As per this question, I have calculated the days between two dates in java.
The program is below

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is  28.

Body:
Using java 8 new Date Time APi

    import java.time.*;
    import java.time.temporal.*;

    ZonedDateTime z1 = date1.toInstant().atZone(ZoneId.systemDefault());
    ZonedDateTime z2 = date2.toInstant().atZone(ZoneId.systemDefault());
    long diff = ChronoUnit.DAYS.between(z1, z2);  // 29


问:
How to increase Google App Engine request timer. Default is 60 sec
I have a PHP script that is running on Google Cloud Engine which fires an SQL query and the query sometimes takes more than 60 second to execute.
If the request fails to return within 60 seconds and a DeadlineExceededError is thrown and not caught, the request is aborted and a 500 internal server error is returned. Following is mentioned in the documentation.

The Google App Engine request timer (Java/Python/Go) ensures that requests have a finite lifespan and do not get caught in an infinite loop. Currently, the deadline for requests to frontend instances is 60 seconds. (Backend instances have no corresponding limit.) Every request, including warmup (request to /_ah/warmup) and loading requests ("loading_request=1" log header), is subject to this restriction

I have gone through this link which explains how to avoid such error but my query is running on a heavy database, which takes a while to fetch all results.

My question is how can I increase the request timer to be able to run long running tasks. If not possible is there any alternatives to achieve such a thing.

答:
If your code is running inside a request handler, then by default there is an App-Engine-enforced 60 second deadline. You can't change it. See the "Deadlines" row / "automatic scaling" column of the chart on this page under "Scaling types":

https://developers.google.com/appengine/docs/java/modules/

However, this code will be able to run for some hours if you change your module to use "manual scaling" and a "B1"-"B4" instance. Example:

default/src/main/webapp/WEB-INF/appengine-web.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
    <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
        <application>myapp</application>
        <module>default</module>
        <version>1</version>
        <threadsafe>true</threadsafe>
        <instance-class>B1</instance-class>
        <manual-scaling>
              <instances>1</instances>
        </manual-scaling>
   </appengine-web-app>
</code>```

On this type of instance, your requests will typically not time out for hours.

Body:
If your code is running inside a request handler, then by default there is an App-Engine-enforced 60 second deadline. You can't change it. See the "Deadlines" row / "automatic scaling" column of the chart on this page under "Scaling types":

https://developers.google.com/appengine/docs/java/modules/

However, this code will be able to run for some hours if you change your module to use "manual scaling" and a "B1"-"B4" instance. Example:

default/src/main/webapp/WEB-INF/appengine-web.xml:

<?xml version="1.0" encoding="utf-8"?>
    <appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
        <application>myapp</application>
        <module>default</module>
        <version>1</version>
        <threadsafe>true</threadsafe>
        <instance-class>B1</instance-class>
        <manual-scaling>
              <instances>1</instances>
        </manual-scaling>
   </appengine-web-app>

On this type of instance, your requests will typically not time out for hours.


问:
Accesing the DAM path to view the uploaded file getting 404 error
I've uploaded some files in DAM path in CRXDE, when i try to access the file using the path, I'm able to open the file, but when i try to open the same file again I'm getting 404 error.And also in rare cases when i try to open first time itself I'm getting 404 error. But the file is available in crxde(PFA). In local i never faced any issue like 404, but in other environment I'm facing the issue.
Is might be due to server replication ?

** JSP Code:-**

```<code><td><a href="${podfiles.path}">
    <img src="../images/pdf.png"style="width: 20px;">
</a></td>  // where,  ${podfiles.path} -->/content/dam/nextgen/EHUB-POD/IN/2.pdf
</code>```

答:
Don't use getAdministrativeResourceResolver if this is your component code. Use resource.adaptTo(ResourceResolver.class). This will give you a resource resolver with equivalent permissions for logged in user. Otherwise your code will return all resources and some of them will have permissions others won't.

If your servlet is bound to a path or extension on a resource, you will have access to resource in the servlet and you can get the resource resolver from there. Alternatively you can use resourceResolver = resolverFactory.getResourceResolver(null)

The resource iterator will give you list of resources according to your permissions. You can then secure the resource access using /useradmin to allow/deny access for anonymous users.

Body:
I've uploaded some files in DAM path in CRXDE, when i try to access the file using the path, I'm able to open the file, but when i try to open the same file again I'm getting 404 error.And also in rare cases when i try to open first time itself I'm getting 404 error. But the file is available in crxde(PFA). In local i never faced any issue like 404, but in other environment I'm facing the issue.
Is might be due to server replication ?

** JSP Code:-**

	  // where,  ${podfiles.path} -->/content/dam/nextgen/EHUB-POD/IN/2.pdf