Show entire bottom sheet with EditText above Keyboard

Question: I'm implementing a UI where a bottom sheet will appear above the keyboard with an EditText for the user to enter a value. The problem is the View is being partially overlapped by the keyboard, covering up the bottom of the bottom sheet.
Here is the Bottom Sheet and no keyboard.

Here is the Bottom Sheet with the keyboard showing.

What's the best method to ensure the entire Bottom Sheet is shown?
Thanks.
Comment: Try this: https://stackoverflow.com/a/50948146/7958563
Comment: Just add this to your BottomSheetDialogFragment "getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)"
Comment: "android:windowSoftInputMode="stateHidden" " in activity inside manifest file where you declare your activity.it will prevent keyboard popup till then you touch in the edittext.
Comment: I need the keyboard to show up so people can enter their values.
Comment: they can give values by clicking on the edittext. The keyboard will popup after it was clicked. So do not worry about it. Try once.
Comment: I did, the same thing happens if the keyboard is up before or after. It'll still cover the bottom of the view.
Comment: See also https://stackoverflow.com/questions/44625365/keyboard-hides-bottomsheetdialogfragment.
Answer: Just reposting @jblejder from this question Keyboard hides BottomSheetDialogFragment since it worked for me, to make it easier for others to find:
The most convenient way that I found to change this is by creating style:

And set this in onCreate method of your BottomSheetDialogFragment:
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setStyle(DialogFragment.STYLE_NORMAL, R.style.DialogStyle)
}

This is how it looks on my device:

==== UPDATE ====
As already mentioned in the Comments a few times, you might also need to set the state of the BottomSheetDialog to STATE_EXPANDED like in Nordknight's answer below
dialog = new BottomSheetDialog(getContext(), R.style.BottomSheetDialog);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    BottomSheetDialog d = (BottomSheetDialog) dialog;
                    FrameLayout bottomSheet = d.findViewById(R.id.design_bottom_sheet);
                    BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
            },0);
        }
    });

Comment: Doesn't work for me. Before a keyboard appeared above `EditText`, so `EditText` lifted up and allowed to type, but not press a `Button` below. After I applied your solution, nothing changed.
Comment: Just add following lines in onCreateDialog() along with above style in OnCreateView().

`override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
  val bottomSheetDialog =  super.onCreateDialog(savedInstanceState)
        if(bottomSheetDialog is BottomSheetDialog){
            bottomSheetDialog.behavior.skipCollapsed = true
            bottomSheetDialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
        }
        return bottomSheetDialog
}`
Comment: Works when bottom sheet fragment layout's root is ScrollView
Comment: works like a charm. For dynamic bottomsheet just set it style when declaring. BottomSheetDialog bd = new BottomSheetDialog(this, R.style.DialogStyle);
Comment: it works, but you need to set state expanded to BottomSheetDialog => this solution + https://stackoverflow.com/a/50798800/5698198
Comment: @CoolMind I was also having the same issue. To solve this I override onShow(DialogInterface dialog) and added  BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED) along with the code posted in this answer.
Comment: this  works only when i wrapped ConstraintLayout with NestedScrollView (ScrollView is not working)
Comment: If anyone faced issues with the style, try changing `parent="Theme.Design.Light.BottomSheetDialog"` to `parent="Theme.MaterialComponents.Light.BottomSheetDialog"` or whatever your app theme is.
Answer: This might be a redundant answer. Although just pointing out the issue.
If you're using BottomSheetDialogFragment, the only way is to enable the attribute android:windowIsFloating to true. This will enable the whole window to be on top of whatever is trying to take the space behind it.

Then in your onCreate() of your dialog, set this style.
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // set the window no floating style
        setStyle(DialogFragment.STYLE_NORMAL, R.style.AppRoundedBottomSheetDialogThemeNoFloating)
}

This is handy for those who frequently use bottom sheets and may want to deal with EditText and soft keyboard overlapping each other.
Note: The class KeyboardUtil by mikepenz has an issue in which on certain phones, the content view with input field is automatically pushed above keyboard despite giving bottom padding to the whole content view supplied.
Comment: This has worked for me when using ```BottomSheetDialogFragment```
Comment: You say "set it to `true`", but write `false`. Which one is it?
Comment: If I do this then I am not able to see my corner radius.
Comment: Where to place this style xml ? which path please
Answer: Some answers seem to do the trick better than others but will need modification when using the new material design components instead of the older support libraries while also using kotlin
Hope this will help someone.
BottomSheetDialog(this, R.style.DialogStyle).apply {
    setContentView(layoutInflater.inflate(R.layout.bottom_sheet, null))
    window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE)
    findViewById<EditText>(R.id.time_et)?.requestFocus()

    show()
}

layout/bottom_sheet.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ffffff"
        android:padding="16dp">

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

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

            <View
                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1" />

            <LinearLayout
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="5"
                    android:orientation="vertical">

                <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Time"
                        android:textColor="#000000"
                        android:textSize="24sp"
                        android:textStyle="bold" />

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

                    <EditText
                            android:id="@+id/time_et"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:inputType="numberSigned"
                            android:minWidth="50dp"
                            android:text="15" />

                    <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginLeft="8dp"
                            android:text="min" />

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

        <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:background="#000"
                android:text="Save"
                android:textColor="#fff" />

    </LinearLayout>

</ScrollView>

styes.xml (Split for v-21 for using statusBarColor)

Comment: This is the only DialogStyle that worked for me I use BottomSheetDialogFragment
Comment: Setting the `windowSoftInputMode`, specifically, was what did the trick for me with a BottomSheetDialogFragment.

        adjustResize
Answer: dialog = new BottomSheetDialog(getContext(), R.style.BottomSheetDialog);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    BottomSheetDialog d = (BottomSheetDialog) dialog;
                    FrameLayout bottomSheet = d.findViewById(R.id.design_bottom_sheet);
                    BottomSheetBehavior bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
            },0);
        }
    });

This code works fine at Fragment's onCreateView method (thanks for ADM)
Comment: It reminds https://stackoverflow.com/a/45706484/2914140 (and doesn't work in my case).
Answer: This is the easiest and best way to handle a BottomSheet dialog:
private fun enterMobileNumberPopUp() {
val dialog = BottomSheetDialog(this,R.style.DialogStyle)
val view = layoutInflater.inflate(R.layout.layout_otp, null)
dialog.setContentView(view)
dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
dialog.show()}

Reference for styles.xml:

Comment: really thank you man , you are a great support
 adjustResize. solved my problem
Answer: A BottomSheetDialog can be helpful for this. it will open with Softkeyboard open with focus on edit text.But user can still close the Softkeyboard and Dialog will be reset to Bottom. Again focusing will make dialog appear at top of Softkeyboard.
 public void showDialog()  {
    final BottomSheetDialog dialog=new BottomSheetDialog(this);
    dialog.setContentView(R.layout.item_dialog);
    dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    dialog.show();
}

You can make the BottomSheetDialog expanded over keyboard . But for this you need to call it after SoftKeyboard Open. the Expand code is .
 BottomSheetDialog d = (BottomSheetDialog) dialog;
            FrameLayout bottomSheet = (FrameLayout) d.findViewById(android.support.design.R.id.design_bottom_sheet);
            BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);

I have tested it on DialogInterface.OnShowListener() but its not working . Tested with it 1 second delay its working . But Delay is not the solution . You need to figure out the on which action you should expand the dialog.
 final BottomSheetDialog dialog=new BottomSheetDialog(this);
    dialog.setContentView(R.layout.item_dialog);
    dialog.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|
                    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            FrameLayout bottomSheet = (FrameLayout) dialog.findViewById(android.support.design.R.id.design_bottom_sheet);
            BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
        }
    },2000);
    dialog.show();

Comment: I'm trying to show the entire `BottomSheetDialog` so I can have things below the `EditText` and still have them visible.
Comment: Using a `BottomSheetDialog` and it's still covering the bottom area below the `EditText`.
Comment: I tried your `expand` code with a timer but it didn't have any effect for me.
Comment: Yeah it is . Thats the behavior.
Comment: Well i have tested it with `handler.postDelay()` and it worked.  Anyway try to look about `BottomSheetFragment` maybe it will work as you want.
Comment: I actually used `handler.postDelayed()` too, and I was using `BottomSheetFragment` before but it seems to be the same issue.
Comment: Ok i am posting what i have tested . You can have a look,its just a test code. Good luck .
Answer: An updated answer for those using Material Components theme, and also an improved answer to remove the need to add anything into each dialog's onCreate().
In your main AppTheme style, you can add the attribute bottomSheetDialogTheme to apply the style to all of your BottomSheetDialogFragments:

So with the above, no need to add anything to your BottomSheetDialogFragment code.
And then, as previous answers, your Dialog style, noting to also match the style to the same Material Components library (or you'll get some weird looking buttons, edittexts etc):

Note that I am adding my app theme colors back in here; as you can't have multiple inheritance in Android styles, you may want these colors defining here so any buttons and accents align with the rest of your app.
Answer:         bottomSheetDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

It will work for sure.
Comment: Where do you get bottomSheetDialog from?
Comment: from BottomSheetDialog class in Material. You can find it in documentation but to make it above the mobile keyboard you have to write the mentioned code
Answer: If you are using bottom sheet fragment overeide getTheme(). setStyle haven't worked for me. Wrap your whole layout inside NestedScrollView
themes.xml

Bottomsheet fragment
@Override
public int getTheme() {
    return R.style.BottomSheetDialogStyle;
}

Answer: Just write the following programmatically
override fun setupDialog(dialog: Dialog, style: Int) {
        super.setupDialog(dialog, style)
        dialog.window?.setSoftInputMode(             WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE or
      WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
      );
      }

Answer: This trick solved me
in manifest put
android:windowSoftInputMode="adjustPan"

in your activity
and
        bottomSheetDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    bottomSheetDialog.getBehavior().setState(BottomSheetBehavior.STATE_EXPANDED);

Answer: This one working
 BottomSheetDialog dialog = new BottomSheetDialog(this, R.style.DialogStyle);
    View sheetView = getLayoutInflater().inflate(R.layout.dialog_remark, null);
    Objects.requireNonNull(dialog.getWindow())
            .setSoftInputMode(SOFT_INPUT_STATE_VISIBLE);
    dialog.setContentView(sheetView);
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            BottomSheetDialog d = (BottomSheetDialog) dialog;
            View bottomSheetInternal = d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            BottomSheetBehavior.from(bottomSheetInternal).setState(BottomSheetBehavior.STATE_EXPANDED);
        }
    });
    dialog.show();

add this style to your styles.xml

add your layout like this
 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
android:id="@+id/scrollview"

    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        android:layout_margin="8dp">

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="8dp"
                android:fontFamily="@font/montserratmedium"
                android:text="Add Remarks"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="24dp"
                android:fontFamily="@font/montserratmedium"
                android:text="Branch"
                android:textColor="#8B8B8B"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:fontFamily="@font/montserratmedium"
                android:text="BLR-CO-SINDHUBHAVAN-384"
                android:textColor="@android:color/black"
                android:textSize="18sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="24dp"
                android:fontFamily="@font/montserratmedium"
                android:text="Enter Remarks"
                android:textColor="#8B8B8B"
                android:textSize="18sp" />

            <EditText

                android:id="@+id/input_remark"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="10dp"
                android:layout_marginTop="8dp"
                android:background="@drawable/remark_inputbg"
                android:gravity="start"

                android:inputType="textMultiLine"
                android:lines="5" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <LinearLayout
                    android:id="@+id/action"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal"
                    android:weightSum="2">

                    <Button
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_margin="8dp"
                        android:layout_weight="1"
                        android:background="@drawable/reset_bg"
                        android:padding="8dp"
                        android:text="CANCEL" />

                    <Button
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_margin="8dp"
                        android:layout_weight="1"
                        android:background="#4F4DBB"
                        android:padding="8dp"
                        android:text="CANCEL"
                        android:textColor="@android:color/white" />
                </LinearLayout>
            </RelativeLayout>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</ScrollView>

Comment: Only `android:windowSoftInputMode="stateHidden|adjustPan"` in AndroidManifest did the trick for me. Thanks for.!
Answer: Kotlin, +viewBinding, +by using the accepted answer's dialog style
val bottomSheet = BottomSheetDialog(this, R.style.BottomSheetDialogStyle)
val binding = [YourSheetBinding].inflate(LayoutInflater.from(YourActivity.this))
bottomSheet.setContentView(binding.root)
bottomSheet.behavior.state = BottomSheetBehavior.STATE_EXPANDED
bottomSheet.show()

Answer:  override fun onStart() {
    super.onStart()
    bottomSheetBehavior?.skipCollapsed = true
    bottomSheetBehavior?.state = BottomSheetBehavior.STATE_EXPANDED
}

Putting this in BottomSheet helped without setting styles and without ScrollView
(correct me if I'm wrong or if I'm missing something)
Answer: For this, I found an AlertDialog worked best. While it doesn't sit flush against the bottom or side of the screen, it still looks good enough.
First, create the AlertDialog with your view.
val view = LayoutInflater.from(context).inflate(R.layout.alert, null)

dialog = AlertDialog.Builder(context)
             .setView(view)
             .create()

Next, set the gravity.
    dialog.window.attributes.gravity = Gravity.BOTTOM

And finally, show it.
dialog.show()

You can also bind the keyboard to stay with the dialog, by using an onDismissListener.
After showing the AlertDialog, I force up the keyboard.
Call this method, passing in your EditText.
fun showKeyboard(view: View?) {
        if (view == null) return;

        val imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

And for dismissing within the onDismissListener.
private fun hideKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
    }

Answer: My answer might be useful for someone who is still looking for solution. If keyboard is covering edittext in BottomSheetDialogFragment then in setupDialog() method create instance of a class KeyboardUtil and pass your rootview.
    @Override
    public void setupDialog(final Dialog dialog, int style) {
        super.setupDialog(dialog, style);
        View view = View.inflate(getActivity(), R.layout.reopen_dialog_layout, null);
        new KeyboardUtil(getActivity(), view);
}

Create a new class
    public class KeyboardUtil {
        private View decorView;
        private View contentView;
        //a small helper to allow showing the editText focus
        ViewTreeObserver.OnGlobalLayoutListener onGlobalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                //r will be populated with the coordinates of your view that area still visible.
                decorView.getWindowVisibleDisplayFrame(r);

                //get screen height and calculate the difference with the useable area from the r
                int height = decorView.getContext().getResources().getDisplayMetrics().heightPixels;
                int diff = height - r.bottom;

                //if it could be a keyboard add the padding to the view
                if (diff != 0) {
                    // if the use-able screen height differs from the total screen height we assume that it shows a keyboard now
                    //check if the padding is 0 (if yes set the padding for the keyboard)
                    if (contentView.getPaddingBottom() != diff) {
                        //set the padding of the contentView for the keyboard
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    //check if the padding is != 0 (if yes reset the padding)
                    if (contentView.getPaddingBottom() != 0) {
                        //reset the padding of the contentView
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };

        public KeyboardUtil(Activity act, View contentView) {
            this.decorView = act.getWindow().getDecorView();
            this.contentView = contentView;

            //only required on newer android versions. it was working on API level 19
            if (Build.VERSION.SDK_INT >= 19) {
                decorView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
            }
        }

        /**
         * Helper to hide the keyboard
         *
         * @param act
         */
        public static void hideKeyboard(Activity act) {
            if (act != null && act.getCurrentFocus() != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) act.getSystemService(Activity.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(act.getCurrentFocus().getWindowToken(), 0);
            }
        }

        public void enable() {
            if (Build.VERSION.SDK_INT >= 19) {
                decorView.getViewTreeObserver().addOnGlobalLayoutListener(onGlobalLayoutListener);
            }
        }

        public void disable() {
            if (Build.VERSION.SDK_INT >= 19) {
                decorView.getViewTreeObserver().removeOnGlobalLayoutListener(onGlobalLayoutListener);
            }
        }
    }

Answer: See https://stackoverflow.com/a/61813321/2914140:
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    val dialog = super.onCreateDialog(savedInstanceState) as BottomSheetDialog
    dialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
    return dialog
}

But if a layout is not tall enough, you can use https://stackoverflow.com/a/66287187/2914140 instead. It will open BottomSheetDialog almost fullscreen:

Answer: If you are using Compose you can just add Modifier.imePadding() on the most bottom Composable. Then the keyboard top will snap to that element instead.
Answer: Fiddling with BottomSheetDialogFragment wasn't really worth it. So I just changed it to a simple DialogFragment and just set its gravity to bottom:
window.setGravity(Gravity.BOTTOM);

Worked like a charm.


Return to "Main" View Controller when app closes (and then starts)

Question: I have a project with 2 view controllers, basically as Weather app or Stocks. App uses storyboard and switching between views with segues.
1-st view is "main", 2-nd is in-app settings.
So I go to "settings" and then press home button.
I need when I launch app next time to be in main view, not in settings. How do I switch from 2-nd vc to 1-st after app goes to background (when home button is pressed)?
Do I need to use "performSegueWithIdentifier:" somewhere? Can I execute it from app delegate?
Answer: Make the switch in your AppDelegate's applicationWillResignActive. This is called a moment before your app becomes inactive.


To show sum of two sets is closed in R^2

Question: Let $A=\{(x,y)\in \mathbb R^2:\max\{|y|,|x|\}\leq 1\}$ and $B=\{(0,y)\in \mathbb R^2:y\in \mathbb R\}$. Show that $A+B$ is a closed subset of $\mathbb R^2$
My try:
let $z_n=x_n+y_n$ be a sequence in $A+B$ converging to $z\in \mathbb R^2$ .To show $z\in A+B$. Now $x_n\in A$
$\implies x_n=(a_n,b_n) $
where $|a_n|,|b_n|\leq 1$and $y_n=(0,c_n)$. Can you help me to proceed further please
Answer: $A$ is compact and $B$ is closed. Now it is a general fact that (in Euclidean spaces) in this case $A+B$ is closed (try to prove this before reading further).
In fact, take any sequence $p_n=a_n+b_n\to p\in\mathbb{R}^2$, where $a_n\in A$ and $b_n\in B$. We have to prove that $p\in A+B$.
As $A$ is compact, upon possibly passing to a subsequence, we have $a_n\to a\in A$.
So $b_n=p_n-a_n\to p-a$ and since $B$ is closed we have $p-a\in B$.
Call $b:=p-a$; we just proved that $p=a+b$ with $a\in A$ and $b\in B$, so we are done.
Comment: I will add some links about the result you mention: http://math.stackexchange.com/questions/515496/sum-of-closed-and-compact-set-in-a-tvs and http://math.stackexchange.com/questions/80974/closed-sum-of-sets (Maybe more of them can be found on this site.)
Answer: Despite the fact that there is a more general result mentioned in another answer, in this specific case it might be easier to show that $$A+B=\{(x,y)\in\mathbb R^2; |x|\le 1\}$$ and then show that this set is closed.
If you try to draw a picture, you should see almost immediately what $A+B$ is, but let us try to do also a formal proof.
Let $C=\{(x,y)\in\mathbb R^2; |x|\le 1\}$. It is easy to see $A+B\subseteq C$.
On the other hand if $(x,y)$ is arbitrary point from $C$, i.e., if $|x|\le 1$, you wan to express it as the sum
$$(x,y)=(x,y_1)+(0,y_2)$$
where $|y_1|\le1$ and $y_2$ is arbitrary. Finding such $y_{1,2}$ should be rather straightforward, too.


how to change "noopener nofollow external noreferrer" to "dofollow" / Wordpress?

Question: I would like to give a dofollow link on my wordpress blog, which leads the readers to another page.
For this I have tried to simply deposit the link normally. This did not work.
In the frontend it looked like this: rel="noopener nofollow external noreferrer".
Then I tried a dofollow link with the attribute rel="dofollow".
In the frontend it looked like this: rel="dofollow noopener nofollow external noreferrer".
Answer: This is a security measure when target="_blank" is used (external linking). Natively as soon as you remove target="_blank" the default behaviour is to "follow".

Strictly speaking, a dofollow link isn't a thing. dofollow is simply the default state for a link. Said another way, any link without the nofollow attribute is a dofollow link.

Source @ https://blog.alexa.com/dofollow-vs-nofollow-links/

You can refer to @ https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types for more informations regarding link types.

Are you using Gutenberg? you should be able to control some behaviour straight from the publishing section. If you disable Open in a new tab it should remove any link type restrictions.


Evaluate :$\int_0^1 \frac{1}{\left(1+\sqrt{\frac{1}{x}-1}\right)(x^2-x-1)}\mathrm dx$

Question: Evaluate :$$\int_0^1 \frac{1}{\left(1+\sqrt{\frac{1}{x}-1}\right)(x^2-x-1) }\mathrm dx$$
How to evaluating this integral, I don't know how to do it, and any help  is welcome .
I tried using wolframalpha ,but the result is too complicated.
Answer: Hint: $y=1-x$ in the integral $I$, then show that $$2I=\int_0^1 \frac{dx}{x^2-x-1}$$
Comment: this is pretty nice :) $+1$
Comment: +1 Can you please add some detail?
Comment: By summing both expressions of the same integral: $I=\int_0^1 \frac{\sqrt{1-y}}{(\sqrt{y}+\sqrt{1-y})(y^2-y-1)}\,dy$ and $I=\int_0^1 \frac{\sqrt{x}}{(\sqrt{x}+\sqrt{1-x})(x^2-x-1)}\,dx$ one gets a simpler form: $I=\frac{1}{2}\int_0^\infty \frac{dx}{x^2-x-1}$. Then, by changing $z=(2x-1)/\sqrt{5}$ reduces to $I=-\frac{1}{\sqrt{5}}\int_{-1/\sqrt{5}}^{1/\sqrt{5}}\frac{dz}{1-z^2}=-\frac{2}{\sqrt{5}}\tanh^{-1}\frac{1}{\sqrt{5}}$, as given in Connor Evans' answer.
Comment: @Paul Enta Thank you very much for your answer.
Answer: If you are just looking for the answer its
$$ -\frac{2}{5}\sqrt{5}\tanh^{-1}(\frac{1}{5}\sqrt{5}) $$
(by Maple)
Comment: it kinda reduces to $-2\tanh ^{-1}(\frac15)$
Comment: Well, you did edit the post, buddy
Comment: Not according to Maple buddy


Problem with IE7 JQuery, Ajax and CSS

Question: In a simple web page I load some new HTML into a div using load(url)
Works fine in most browsers but, surprise, surprise, IE7 behaves differently.
All the other browsers apply the pages CSS styles to the newly loaded HTML but IE7 doesn't.
Any ideas?
Ken

Update
The new HTML is just a code fragment, e.g.

blah blah blah

Update I think I'm calling it OK.
This isn't what I'm actually doing but a simplified version which reproduces the problem ...
.
.
.
google.load("jquery", "1.3.2");
    google.setOnLoadCallback(function() {
       $(document).ready(function() {
         $("#nav-home").click(function() {
           $("#girc-content").load("home.html");
         });
.
.
.

Update On further investigation the problem appears to be slightly more odd than I thought.
I tried Steerpike's suggestion because I originally thought the problem was that the CSS styles were not being applied.
However, it now appears that only some of the styles are being applied.
For example, the text color attribute for the
 tag is applied, but the width attribute for the
 tag is not.
Comment: And yeah, cletus, that *is* pretty insane, although I guess when I think about it not hugely surprising - I imagine google recognises how good the content is here generally and how rapidly it changes, makes sense they'd spider it with alarming regularity :)
Comment: Are you loading HTML chunk from the same domain?
Comment: Can you post a cutdown jquery fragment?
Comment: You wanna hear something scary?  After 8 minutes, this question already shows up in a Google search...
Comment: I can't duplicate your problem using your supplied code. Using your javascript to load my test content has IE7 (actually IE8 in 7 mode) apply the CSS styles I gave it without issue. There must be something about the HTML you're trying to load or maybe your CSS rules?
Comment: Jeff has commented in the SO blog or codinghorror (can't remember whcih) that ***70%*** of the site's traffic is google crawling.
Comment: Having more of the actual semantic markup and specific css rules used would likely help if you're still having trouble finding the solution, kenneedham
Comment: I'm creating a small example which exhibits the same problem
Answer: In light of extra information, take 2...
Are the styles not being applied in the master HTML page or the page you're loading?  If they're in the page you're loading it seems that IE strips out script and style tags from XMLHttpRequest objects.
Given that it's not that and I'm intrigued I constructed a sample:

<title>test</title>

blah blah blah

<input type="button" value="click me" id="nav-home">

and test2.html:

This is a test

This works perfectly for me in IE8 standards and compatibility mode (sorry no IE7 any more).
I did notice when I copied your google onload snippet that you were missing some closing braces/parentheses. Was this just a cut and paste error or a problem with your Javascript?  It might explain the inconsistent behaviour.
Comment: You can revert IE8 back to 7 by using Tools > Developer Tools > Browser Mode > Internet Explorer 7. The IE team says that the mode is functionally identical to actual IE7, but apparently there are slight discrepencies.
Comment: I only reference the external style sheet in the static part of my page. The HTML which is loaded dynamically has no such references but uses the styles defined in the static portion. There is no script in the dynamic portion.
Comment: Ah I knew I'd heard about that somewhere. Tried that, same deal. works fine.
Comment: I modified that code sample to look more like what I have and it still works in IE7.
Which, I think, means there is something wrong with my CSS template.
I should have thought of that earlier.
The fact that the  tage works but the  ones don't should have been a clue.
Thanks for the help.
Comment: Found it.
I had a border="0"; in one of the styles
The other browsers didn't seem to mind but IE just stopped applying any styles after that point.

I'll give you the TICK as your questions prompted me to look in the right place.

Thanks again
Answer: Try 'touching' the content again after you load it. The simplest way tends to just add a null string to the innerHTML
$("#nav-home").click(function() {
    $("#girc-content").load("home.html");
    $("#girc-content")[0].innerHTML += '';
});

Answer: The link helped me; essentially, adding the style tag into the head, even dynamically, applies the styles through ie. I added this to the top of the onready handler and it worked well.
http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/
$("head").append("<link>");
css = $("head").children(":last");
css.attr({
  rel:  "stylesheet",
  type: "text/css",
  href: "/javascripts/jwysiwyg/jquery.wysiwyg.css"
});

Answer: I had similar problem - IE8 sometimes has a problem with apply styles in content loaded by ajax jQuery function. I don't know why but this helped:
$.ajax({
url: 'content.html',
success: function(data) {
   $('#content').html(data); //styles doeas not appear in ie8
   document.getElementById('content').innerHTML = data; /* ie8 - now it works oO */
}

Comment: I might know why, because innerHTML will force browser to render DOM again.

Problem with IE7 JQuery, Ajax and CSS


boot IBM p series 650 from 3580-L23 LTO-2 tape

Question: We have a p series 650 that has a dds4 tape drive built-in. In the past, recover has been as simple as putting a mksysb tape into the drive and booting the machine. During boot, the machine detects that a tape is in the drive and goes into the restore setup. This all works well.
We are trying to upgrade to a bigger, faster tape. The drive we are moving to is a 3580-L23 drive, which uses LTO-2 tapes. We are able to run the mksysb command and write the tape successfully. We've also done a file listing from the tape and verified that the root vg looks good.
The last hurdle for us is getting the system to boot from the 3580. The problem is that when the system boots, it doesn't boot from the 3580 - it skips straight to the internal hard drives. We've tried looking around in the AIX bootlist, but it doesn't list any tape drive of any kind, including the dd4 drive. At this point we're pretty sure there's some config in the IPL that we're just missing that lists the boot order, but we can't seem to find it.
Comment: Nobody seems to have any comments, so here is a link to a thread I made on a different site: http://unix.ittoolbox.com/groups/technical-functional/ibm-aix-l/boot-ibm-p-series-650-from-3580l23-lto2-tape-4713827
Comment: If that site happens to disappear in the future, the end result was that I gave up trying to figure out why the system was attempting to boot from the dds4 tape and changed the bootlist like this: `>bootlist -m normal rmt0 rmt1 hdisk2 hdisk3`
Comment: Isn't much easier just to boot into SMS and select from where do you want to boot? chsysstate -m pserver -r lpar -o on -f profilename -n lparname -b sms (IIRC).
Answer: If that site happens to disappear in the future, the end result was that I gave up trying to figure out why the system was attempting to boot from the dds4 tape and changed the bootlist like this: >bootlist -m normal rmt0 rmt1 hdisk2 hdisk3


Can a partition of a set be constructed from relations that are NOT equivalence relations?

Question: Is it true that only kind of relations that can completely and uniquely define a partition in a set is the equivalence relation ?
I'm having a hard problem believing that.
Given an original set $A = \{a,b,c,d\}$ and certain partition $\{P_1,P_2\}$ where $P_1 = \{a,b,d\}$ and $P_2 = \{c\}$ I could introduce a relation (not equivalence relation) $A \rightarrow A = \{ (a,d),(a,b),(b,d),(c,c) \}$ and from that relation I could still uniquely partition the original set $A$ into $\{P_1,P_2\}$. How? Well the informal process of building subsets out of the ordered pairs, one-by-one.
First $(a,d)$ implies a subset that contains $a,d$.
then $(a,b)$ implies a subset that contains $a,b,d$ (by transitive property).
then $(b,d)$ adds no information
then $(c,c)$ implies a subset containing $c$.
The unique result is the partition $\{a,b,d\}, \{c\}$.
Am I doing something wrong or forgetting something crucial?
Comment: @MJD: Could you please explicate how and why $$(a,b) \& (b, d) \Longrightarrow \text{a subset that contains $a, b, d$ by transitivity ?}$$ We don't know that $A \longrightarrow A$ subsumes transitivity? Also, $(a, d) \notin A$.
Answer: It all depends on what exactly you mean by a relation "completely and uniquely defining a partition". In one sense, a partition and an equivalence relation are basically the same thing. That doesn't mean that you can't use other types of relations to define partitions; but it does mean that in doing so you necessarily also define an equivalence relation.
In your example, it seems that you intend to define a partition using the reflexive transitive symmetric closure of a relation $R$. This is the intersection of all equivalence relations containing $R$, or equivalently the unique minimal equivalence relation containing $R$. By defining an equivalence relation, you are at the same time defining a partition.
Comment: @nerdy: Did you follow the link I provided? Do you understand the concept of a closure? Do you understand the two definitions I provided in the second paragraph of the answer? (They're the same as the ones MJD gave in response to your comment.)
Comment: I'm trying real hard to understand what is the equivalence relation that i'm implicitly defining when i use my informal process to build a unique partition from my non-equivalence relation but i have no sucess so far.How is it defined and what would be its domain and codomain ?
Comment: I just followed your link and it became a lot clear.Btw, is it true that the "function" that builds a closure out of a relation is not necessarily injective ? For example, i could choose my old R to be  (d,b),(d,a),(d,b),(c,c)  and that would yield me the same equivalence closure, right ?
Answer: Suppose you have a partition of $A$.  Then the natural equivalence relation that corresponds to it is that $p$ is related to $q$ whenever $q$ is in the same part as $p$.
What you are doing is taking a non-equivalence relation and then constructing the "equivalence closure", which is the smallest equivalence relation that contains it.
Your partition, for example, has $d$ in the same part as $b$, even though the original relation omits the pair $(d, b)$. The relation says that the relationship between $d$ and $b$ is asymmetric: It has $(b,d)$ but not $(d,b)$, so $d$ is related to $b$ but $b$ is not related to $d$.  But your partition doesn't capture this asymmetry.
Similarly, your partition has $a$ in the same part as itself, but your original relation says that $a$ should not be related to itself, because your original  relation does not include $(a,a)$.  So your partition fails to capture this aspect of the relation.
So the partition that you've constructed is derived from the original relation, but not in the special way that we mean when we say that every partition corresponds to an equivalence relation in a special way.
Comment: The equivalence closure of a relation $R$ is defined as the smallest equivalence relation that contains $R$, or alternatively as the intersection of every equivalence relation that contains $R$.  (It comes to the same thing.)  Its domain and codomain are the same as those of $R$.  In your example, you've started with $R=\{ (a,d),(a,b),(b,d),(c,c) \}$ and constructed the equivalence closure $\{ (a,a),(a,d),(a,b),(b,a),(b,b),(b,d),(c,c),(d,a),(d,b), (d,d) \}$.
Comment: How is the equivalence closure that i'm implictly using, defined ? What is its domain and codomain ?
Comment: Thanks a lot, you and joriki quickly helped me clarify this doubt.I hadn't heard of the the possibility of buildind new sets that safisfy certain property from old sets.I wish i could choose 2 best answers :(
Comment: I'm glad I could help.


Learning C* Algebra via Problems

Question: I have been reading the book "C*-Algebras and Operator Theory" by G.J.Murphy. I have almost finished reading the first two chapters. I was wondering if someone could suggest me some book/Lecture notes/source with some good problems to go over. Murphy's book has some. But they are at the end of the chapter and very few.
Thanks for the help!!
Answer: I think the book An Introduction to Operator Algebras written by Kehe Zhu is very well suited to learn about $C^*$-algebras actively. The book consists of 26 (very) short chapters and each of these chapters contains several well-chosen exercises.

Learning C* Algebra via Problems


Non server specific proxy?

Question: I have a widget that is added to random websites. The widget needs to fill an iframe with content. I need the iframe source to be from the same domain as the website it is embedded in.
To do this I want to ask the site owners to put a file in their root folder that will be used as a proxy to my server.
My question is -how can I implement such proxy with static html/js/? file without using a server side scripting?
Answer: I'm not really clear how such a proxy would work/help either way. Are you looking for something like <base />?
The only issue with the base element is that it can't be turned off once it's turned on. If the iframe is the last thing on the page, or at least the last thing with either src or href, you could set it just above.  But I'm not sure that this will allow js to access the iframe as though it were by proxy.
And again, I'm still not sure how a file on the remote server will make the iframe seem like it's on your domain. And I have serious doubts whether the site owners will extend such a favor, since doing so would allow hackers to use your site as a backdoor into their server.
I'm not sure how browsers/js policy is in terms of redirects and rewrites, but maybe you could go with something like pointing the iframe to your own server, and having that page actually go to their page, either by mod_rewrite or a redirect. Either way would be server side, so maybe that's not an option.  I have heard tale of another thing that works, but have yet to see it in action... You have the site owners add a script with:
 document.domain = "yourserver.net";

And be sure to set it on your script as well. This makes them play nice, supposedly. But they may not go for that if it breaks their site for other things, unless there is someway their page can tell it's inside of an iframe and can set that property conditionally.
Good luck
Comment: Thanks for the answer. Perhaps I was not clear. the file will reside on the server of the sites that will have the widget integrated, not on my server.
Comment: Right, I got that. I don't know how such a file would work (which is probably my own ignorance), especially client-side. Are you saying the other servers will be inclined to do this because they are using your widget on their site?
Comment: yes, I want them to put a static file on their path that will allow the iframe to have my contnent via a src in their own domain.

Non server specific proxy?


Enroll user on course module error due to permissions

Question: I want that a role called "Profesor" can enroll users on a course created using the course module, using the course-enrollments/search-add view but I'm getting the following error:
Type: views bulk operation
User: profesor1
Message: Skipped Enroll user on user alumno2 due to insufficient permissions.
Here is my permissions configuration:

Administrator can enroll users, any help?
EDIT:
The course permissions are configured as follows:
Answer: I haven't used the course module in quite a while but aren't there other permissions specific to the module itself?
Comment: I am totally out of touch with this module by now Pierre but my opinion of education modules in general is that they should all be avoided. Everything they offer can be achieved with clever use of the key well-supported modules that work well together. I don't mean to insult the creators of said modules because isolated, they work very well. But by nature, an LMS is one of the most complex site builds possible and specific modules make it needlessly complex in the long-run.. Serious technical debt when adding something simple like badges or points etc.
Comment: Yes, the course module includes other permissions, I have edited the question with the configuration
Comment: Hey Niall, I think there is another explanation / answer for this question. Curious about your feedback on it ...
Answer: Your issue appears to be similar to the VBO issue "Custom Action Stopped Working", which  includes some possible work around (such as going back to a prior VBO release, if that's what you want to consider ...).
But this issue also appears to be related to "Default action behaviors in getAccessMask()". And that issue contains a patch attached to comment nr 29, which in subsequent comments seems to confirm that it does solve the issue (I've not QA-tested that patch ...).


Adding connection to LINQPad gives Unity.ResolutionFailedException

Question: I'm trying to create a simple C# Program in LINQPad to test some DbContext stuff. I set up the connection to my DataModels Assembly and config file. However, when trying to run the program I receive this message:

ResolutionFailedException: Resolution of the dependency failed, type = "Clark.Logging.ILogger", name = "(none)".
  Exception occurred while: while resolving.
Exception is: InvalidOperationException - The current type, Clark.Logging.ILogger, is an interface and cannot be constructed. Are you missing a type mapping?
At the time of the exception, the container was:
Resolving Clark.Logging.ILogger,(none)

So far, the program is simply:
void Main()
{
    var testString = "Testing";
    testString.Dump();

    // More code to eventually go here, which will use the connection and context.
}

This works if I do not select my connection.
I believe that the DataModel assembly uses Unity IoC for a custom logging setup. For some reason just associating this LINQPad file to the connection causes the error.
I may need to provide more information here, but what can I do to use my connection?
Comment: It looks like the DataContext library that you are using for your EF connection properties depends on another library that you have not referenced, or that, when it is used in your main project, there are other bindings that aren't part of the DataContext library that are required to satisfy (at least one of) its dependencies.
Answer: Unity doesn't find a map, it will try to construct the type. In your case it fails since you cannot construct an interface.
With Unity, you can do it either by configuration using:
container.RegisterType<InterfaceType, ConcreteType>();
Update#
Kindly try below and see, if this helps.
void Main()
{
  ILogger log = new Logger();
  var source = new Subject<int>();
  source.Log(log, "Sample")
      .Subscribe();

  source.OnNext(1);
  source.OnCompleted();
}

Broadcasts a log entry for any of the configured listener/appender instances to write if appropriate

The log level
The message to log
An optional Exception instance to be associated with the log. Useful for capturing stack traces.
public interface ILogger
{
    void Write(LogLevel level, string message, Exception exception);
}
public class Logger : ILogger
{
    public void Write(LogLevel level, string message, Exception exception)
        {
                message.Dump(level.ToString());
        }
}
public enum LogLevel
{
  ///
  /// The lowest level, for any information that is considered verbose.
  ///
  Verbose,
  ///
  /// The second lowest level, for tracing the workflow in detail logging.
  ///
  Trace,
  ///
  /// For logging information that may help debugging problems.
  ///
  Debug,
  ///
  /// A non-critical error has occurred that will not interrupt the application but may degrade the user experience.
  ///
  Warn,
  ///
  /// For interesting business or technical actions such as a process starting or a request being made.
  ///
  Info,
  ///
  /// For errors that need immediate attention.
  ///
  Error,
  ///
  /// For catastrophic failures.
  ///
  Fatal
}

Extensions methods to the  interface.
public static class LoggerExtensions
{
    ///
    /// Logs a message with an exception as Fatal.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Fatal(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Fatal, formattedMessage, exception);
    }
    ///
    /// Logs a message with an exception as Fatal.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Fatal(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Fatal(null, format, args);
    }

    ///
    /// Logs a message with an exception as Error.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Error(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Error, formattedMessage, exception);
    }
    ///
    /// Logs a message with an exception as Error.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Error(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Error(null, format, args);
    }

    ///
    /// Logs a message with an exception as Info.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Info(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Info, formattedMessage, exception);
    }
    ///
    /// Logs a message with an exception as Info.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Info(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Info(null, format, args);
    }

    ///
    /// Logs a message with an exception as Warn.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Warn(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Warn, formattedMessage, exception);
    }
    ///
    /// Logs a message with an exception as Warn.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Warn(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Warn(null, format, args);
    }

    ///
    /// Logs a message with an exception as Debug.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Debug(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Debug, formattedMessage, exception);
    }
    ///
    /// Logs a message as Debug.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Debug(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Debug(null, format, args);
    }

    ///
    /// Logs a message with an exception as Trace, the second lowest level.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Trace(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Trace, formattedMessage, exception);
    }
    ///
    /// Logs a message as Trace, the second lowest level.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Trace(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Trace(null, format, args);
    }

    ///
    /// Logs a message with an exception as Verbose, the lowest level.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="exception">The related <see cref="Exception"/> for the message</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Verbose(this ILogger logger, Exception exception, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var formattedMessage = Format(format, args);
        logger.Write(LogLevel.Verbose, formattedMessage, exception);
    }
    ///
    /// Logs a message as Verbose, the lowest level.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="format">The message as a string format</param>
    /// <param name="args">The arguments for the message</param>
    //[StringFormatMethod("format")]
    public static void Verbose(this ILogger logger, string format, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        logger.Verbose(null, format, args);
    }

    private static string Format(string format, params object[] args)
    {
        if (args == null || args.Length == 0)
            return format;
        return string.Format(CultureInfo.CurrentCulture, format, args);
    }

    ///
    /// Logs the entry to a method as a string like "MyType.MyMethod(1, ABC)".
    /// Ensure the method being logged is not in-lined by the compiler/jitter with the
    /// [MethodImpl(MethodImplOptions.NoInlining)] attribute.
    ///
    /// <param name="logger">The instance of a logger to log with</param>
    /// <param name="args">The arguments passed to the method</param>
    /// <remarks>
    /// The <see cref="MethodEntry"/> logging method is useful for logging that a method has
    /// been entered and also capturing the arguments of the method in the log.
    /// <example>
    /// In this example we log a method entry and the arguments.
    ///
    /// <![CDATA[
    /// [MethodImpl(MethodImplOptions.NoInlining)]
    /// public void MyLoggedMethod(string s, DateTime dateTime)
    /// {
    ///     _logger.MethodEntry(s, dateTime);
    ///     //Method body goes here...
    /// }
    ///
    /// ]]>
    ///
    /// The output may look something like this
    /// 2012-01-31 12:00 [UI] DEBUG MyLoggedType.MyLoggedMethod(A, 31/12/2001 13:45:27)
    /// </example>
    /// </remarks>
    public static void MethodEntry(this ILogger logger, params object[] args)
    {
        if (logger == null) throw new ArgumentNullException("logger");
        var stackTrace = new StackTrace();
        var method = stackTrace.GetFrame(1).GetMethod();
        var type = method.DeclaringType;
        var typeName = string.Empty;
        if (type != null) typeName = type.Name;
        string parenth = "()";
        var parameterDefinitions = method.GetParameters();
        if (parameterDefinitions.Length > 0)
        {
            if (args == null || args.Length == 0)
            {
                parenth = "(...)";
            }
            else
            {
                var values = string.Join(", ", args);
                parenth = string.Format(CultureInfo.CurrentCulture, "({0})", values);
            }
        }

        logger.Debug("{0}.{1}{2}", typeName, method.Name, parenth);
    }

    public static IObservable<T> Log<T>(this IObservable<T> source, ILogger logger, string name)
    {
        return Observable.Using(
            () => logger.Time(name),
            timer => Observable.Create<T>(
                o =>
                {
                    logger.Trace("{0}.Subscribe()", name);
                    var subscription = source
                        .Do(
                            i => logger.Trace("{0}.OnNext({1})", name, i),
                            ex => logger.Trace("{0}.OnError({1})", name, ex),
                            () => logger.Trace("{0}.OnCompleted()", name))
                        .Subscribe(o);
                    var disposal = Disposable.Create(() => logger.Trace("{0}.Dispose()", name));
                    return new CompositeDisposable(subscription, disposal);
                })
            );
    }

    public static IDisposable Time(this ILogger logger, string name)
    {
        return new Timer(logger, name);
    }

    private sealed class Timer : IDisposable
    {
        private readonly ILogger _logger;
        private readonly string _name;
        private readonly Stopwatch _stopwatch;

        public Timer(ILogger logger, string name)
        {
            _logger = logger;
            _name = name;
            _stopwatch = Stopwatch.StartNew();
        }

        public void Dispose()
        {
            _stopwatch.Stop();
            _logger.Debug("{0} took {1}", _name, _stopwatch.Elapsed);
        }
    }
}

Comment: In my code I do something like `var multiLogger = new MultiLogger(); IoCHelper.RegisterInstance(multiLogger);`. But just adding that to my `Main()` in LINQPad doesn't fix the error.
Comment: Editing with sample code which you can try in LinqPad
Comment: I receive `CS0246 The type or namespace name 'Logger' could not be found (press F4 to add a using directive or assembly reference)`. Trying to use log4net interferes with our custom logging class.
Comment: Press F4 and add the below references,

`System
 System.Reactive
 System.Reactive.Concurrency
 System.Reactive.Disposables
 System.Reactive.Joins
 System.Reactive.Linq
 System.Reactive.Subjects
 System.Reactive.Threading.Tasks
 System.Windows.Forms
 System.Globalization`
Comment: I'm not sure how that will help me. The original code that uses this DbContext does not use Reactive.
Comment: It's a sample related to your posted issue logger. Is it possible to share your code snippet of linqpad that throws up the error. So that I can check and provide the info.
Comment: As I mentioned, the above code is ALL that is in LINQPad. I do not get the error until I 'connect' to the DbContext and config file. I do not know what part of the DbContext is causing the error.
Comment: Yes, I've already seen that. I've connected to DbContexts before. It's more complicated than that. This doesn't seem to be something you're familiar with.
Comment: @MKenyonII : As you have said I do not know what part of the DbContext is causing the error.

Without sharing any info of source we cant get you the answer. And we can give the sample solution to follow. If you find the solution please post, so we can learn from that and see what i am missing.


Gdbserver strange error while debugging native app

Question: I'm trying to debug an native app on my android device.
I followed this tutorial: http://blog.thecobraden.com/2012/02/debugging-apps-with-native-code-part-1_09.html
And everything went good, I built the app and installed it, once I wanted to debug it with ndk-gdb I got this error: Could not open remote device: Invalid argument.
I searched this error and found this answer: Android NDK debugging: device can't be opened It's very similar to my problem, I tried this method and now I get this error: Can't open socket: Permission denied.
My phone is rooted so I don't understand why gdbserver can't open the socket.. I tried to give the gdbserver binary different permissions but it still won't work.
Any solutions?
Answer: Are you running the ndk gdb command as root? Do adb root to get the root access of the device and then start the debugging. Hopefully this should help.
Comment: Yes, I run ndk-gdb as root. Before the debugging I did adb root to run the service on the phone as root, and it still didn't work. It is very strange, because the native app have permissions for Internet, and gdbserver runs with the permissions of the app, so it must work.


Apache connection pooling

Question: I want to implement apache connection pooling between two apache2 servers. So that there are connections already established and my response time is reduced.
I am aware that we need to use either Worker or Event MPM. I also need to know how to identify the same in log files.
Thanks in advance,
Paresh
Comment: I think the goal is not really clear. Do you want a loadbalancing?
Comment: i have two servers 1 in uk and the other in us. My http request is sent from UK servers to my clients server in US which takes 300ms to get the response. I have placed a new server in US so that a pool of connection is established between both of my servers such that next time my response time would be less. Since the US and UK server will already have connection established.
Answer: This started off as a comment but got a bit long.
There is no such thing as connection pooling in HTTP. Transaction pipelining is possible (see HTTP keepalives) but this has nothing to do with the process engine. (SPDY also allows for transaction multiplexing - but that's something different again). Adding servers (appropriately configured) will decrease connection re-use hence worsening your performance.
In addition to what appears to be a flawed premise and incorrect assumptions, you've omitted a lot of information which is relevant - What OS is running at both ends? Are you using SSL? What is your SSL session timeout? Are you using a shared SSL session cache?
If network latency is the big problem here, then running the HTTP through a VPN or IPSEC instead of SSL will improve the situation (no need for SSL [re-]negotiation for every request but you still have a TCP handshake).
If SSL is not a consideration, then make sure you've got window scaling set up properly with appropriate RWINs at both ends. Most OS will cache the slow start threshold across connections which means that it shouldn't have too much impact unless connections between the end-points are relatively infrequent - in which case you might want to set a higher default.
Comment: On both the ends i have debian 6.0 running. We are not using ssl. Is it possible to reduce TCP handshake.
Comment: No, youn only reduce the time for TCP handshake by reducing the latency of the network connection. But you can use pipelining and increase the initial cwnd to reduce the slow start impact.

Apache connection pooling


Erro de compilação: "Resource leak" ao usar Scanner

Question: Estou resolvendo uma questão do livro de Deitel questão 3.17, porém estou com um problema na classe principal (estou fazendo pelo Eclipse, no ambiente Linux).
O código está assim:
public class HealthProfile{

    private String nome;
    private String sobrenome;
    private String sexo;
    private int dia;
    private int mes;
    private int ano;
    private float altura;
    private float peso;

    public HealthProfile(String nome, String sobrenome,
            String sexo, int dia, int mes, int ano, float altura,
            float peso)
    {
        this.nome = nome;
        this.sobrenome = sobrenome;
        this.sexo = sexo;
        this.dia = dia;
        this.mes = mes;
        this.ano = ano;
        this.altura = altura;
        this.peso = peso;
    }

    public void setNome(String nome)
    {
        this.nome = nome;
    }

    public String getNome()
    {
        return nome;
    }

    public void setSobrenome(String sobrenome)
    {
        this.sobrenome = sobrenome;
    }

    public String getSobrenome()
    {
        return sobrenome;
    }

    public void setSexo(String sexo)
    {
        this.sexo = sexo;
    }

    public String getSexo()
    {
        return sexo;
    }

    public void setDia(int dia)
    {
        if ((dia >= 1) && (dia <= 31))
            this.dia = dia;
    }

    public int getDia()
    {
        return dia;
    }

    public void setMes(int mes)
    {
        if ((mes >= 1) && (mes <= 12))
            this.mes = mes;
    }

    public int getMes()
    {
        return mes;
    }

    public void setAno(int ano)
    {
        if (ano >= 1900)
            this.ano = ano;
    }

    public int getAno()
    {
        return ano;
    }

    public void setAltura(float altura)
    {
        if (altura >= 100)
            this.altura = altura;
    }

    public float getAltura()
    {
        return altura;
    }

    public void setPeso(float peso)
    {
        if (peso >= 70)
            this.peso = peso;
    }

    public float getPeso()
    {
        return peso;
    }

    public int idadeEmAnos()
    {
        return 2019 - getAno();
    }

    public int maximumFrequenciaCardiaca()
    {
        return 220 - idadeEmAnos();
    }

    public double MinFrequenciaCardiacaAlvo()
    {
        return 0.5 * maximumFrequenciaCardiaca();
    }

    public double MaxFrequenciaCardiacaAlvo()
    {
        return 0.85 * maximumFrequenciaCardiaca();
    }

    public float getIMC()
    {
        float IMC = getPeso() / (getAltura() * getAltura());
        return IMC;
    }
}

E a classe principal está assim:
import java.util.Scanner;

public class Principal {

    public static void main() {

        HealthProfile health = new HealthProfile(null, null, null, 0, 0, 0, 0, 0);

        Scanner input = new Scanner( System.in );

        System.out.println("Informe seu nome: ");
        String nome = input.nextLine();
        health.setNome(nome);

        System.out.println("Informe seu sobrenome: ");
        String sobrenome = input.nextLine();
        health.setSobrenome(sobrenome);

        System.out.println("Informe seu sexo: ");
        String sexo = input.nextLine();
        health.setSexo(sexo);

        System.out.println("Informe seu dia de nascimento: ");
        int dia = input.nextInt();
        health.setDia(dia);

        System.out.println("Informe seu mes de nascimento: ");
        int mes = input.nextInt();
        health.setMes(mes);

        System.out.println("Informe seu ano de nascimento: ");
        int ano = input.nextInt();
        health.setAno(ano);

        System.out.println("Informe sua altura: ");
        float altura = input.nextFloat();
        health.setAltura(altura);

        System.out.println("Informe seu peso: ");
        float peso = input.nextFloat();
        health.setPeso(peso);

        System.out.printf("%s ", health.getNome());
        System.out.printf("%s%n", health.getSobrenome());
        System.out.printf("%d anos", health.idadeEmAnos());
        System.out.printf("Sua frequencia máxima é %d%n", health.maximumFrequenciaCardiaca());
        System.out.println("Frequencia Cardiaca Alvo:");
        System.out.printf("A Minima frequencia alvo é : %.0f%n", health.MinFrequenciaCardiacaAlvo());
        System.out.printf("A Maxima frequencia alvo é : %.0f%n", health.MaxFrequenciaCardiacaAlvo());
    }
}

Gostaria de entender esse problema que está dando no eclipse:
Description Resource    Path    Location    Type
Resource leak: 'input' is never closed  Principal.java
/ComputadorizacaoScannerSaude/src   line 9  Java Problem

Ele diz que esse problema está na linha 9 que é essa aqui:
Scanner input = new Scanner( System.in );

Na função principal.
E isso não está deixando eu compilar o programa.

Obs.:
Uma outra forma que eu implementei e não houve nenhum problema foi usando o JOptionPane:
import javax.swing.JOptionPane;

public class Principal{
    public static void main(String[] args) {

        int dia, mes, ano;
        float altura, peso;

        String nome = JOptionPane.showInputDialog("Nome: ");
        String sobrenome = JOptionPane.showInputDialog("Sobrenome: ");
        String sexo = JOptionPane.showInputDialog("Sexo: ");
        dia = Integer.parseInt(JOptionPane.showInputDialog("Digite o dia do seu nascimento (em digitos)"));
        mes = Integer.parseInt(JOptionPane.showInputDialog("Digite o mês do nascimento (como antes)"));
        ano = Integer.parseInt(JOptionPane.showInputDialog("Digite o ano do seu nascimento (como antes)"));
        altura = Float.parseFloat(JOptionPane.showInputDialog("Altura(em metros): "));
        peso = Float.parseFloat(JOptionPane.showInputDialog("Peso(em quilogramas): "));

        HealthProfile health = new HealthProfile(nome, sobrenome, sexo, dia, mes, ano, altura, peso);

        String message = String.format(
                "Nome:%s\nSobrenome:%s\nSexo:%s\nData de Nascimento:%d/%d/%d\nIdade em Anos:%d\nFrequencia Cardiaca Maxima:%d\nFrequencia Cardiaca Alvo:[%.2f;%.2f]\nIMC:%.2f",
                health.getNome(), health.getSobrenome(), health.getSexo(), health.getDia(), health.getMes(),
                health.getAno(), health.idadeEmAnos(), health.maximumFrequenciaCardiaca(), health.MinFrequenciaCardiacaAlvo(),
                health.MaxFrequenciaCardiacaAlvo(), health.getIMC());

        JOptionPane.showMessageDialog(null, message);
    }

}

Answer: Como regra geral, é importante fechar tudo que você abriu, seja um Scanner, um arquivo (FileInputStream/FileReader), uma conexão com uma URL ou com um banco de dados, ou o que quer que seja que possa ser "aberto" e "fechado". É isso que o Eclipse está reclamando: você abriu o Scanner, mas em nenhum lugar ele é fechado. Então bastaria chamar o método close() no final do código.
Apenas um detalhe, se você fizer assim:
Scanner input = new Scanner(System.in);
// usa o Scanner ...

input.close();

Isso não garante que o método close() sempre será chamado. Se ocorrer algum erro no meio do caminho (por exemplo, o usuário digitou abc quando era esperado um número), é lançada uma exceção e o close() não é executado (na verdade qualquer exceção que ocorra no meio do caminho, mesmo que não tenha relação com o Scanner, provocará esta mesma situação). Para garantir a execução do close(), você pode usar um bloco try com finally:
Scanner input = null;
try {
    input = new Scanner(System.in);
    // usar o Scanner
} catch (Exception e) {
    // tratar os erros
} finally {
    if (input != null)
        input.close();
}

Com isso, o método close() é chamado, mesmo que ocorra algum erro no meio do caminho (sobre o catch (Exception e), essa não é a melhor maneira de lidar com os erros, mas esse já é um tópico à parte).
Outra alternativa é usar a sintaxe de try-with-resources (disponível a partir do Java 7):
try (Scanner input = new Scanner(System.in)) {
    // usar o Scanner
} catch (Exception e) {
    // tratar os erros
}

Nesse caso, o bloco try-with-resources já chama o método close() automaticamente ao seu final (mesmo que ocorra uma exceção dentro do bloco try).

Devo fechar System.in?
As soluções acima são mais gerais, podendo ser usadas com quaisquer recursos que devam ser fechados (arquivos, streams de dados, conexões de rede/banco de dados, etc). Especificamente no try-with-resources, qualquer classe que implemente java.lang.AutoCloseable pode ser usada dentro da inicialização do try.
Mas falando especificamente do System.in, há alguns cuidados extras a se tomar. Quando você fecha o Scanner, o objeto encapsulado pelo mesmo também é fechado. No seu caso, o método close() acabará fechando o System.in, e com isso, ele não poderá mais ser usado pela sua aplicação. Exemplo:
while (true) { // loop infinito
    try (Scanner input = new Scanner(System.in)) {
        System.out.println("digite um número: ");
        System.out.println(input.nextInt());
    } catch (Exception e) {
        e.printStackTrace();
        break; // se der erro, sai do while
    }
}

Na primeira iteração do while, o Scanner lê um número. Logo em seguida (assumindo que um número foi corretamente digitado) este número é impresso, o bloco try-with-resources termina e o método close() do Scanner é chamado, fazendo com que System.in seja fechado. E na segunda iteração do while, é criado outro Scanner com o System.in, mas como este está fechado, dá erro na hora de ler o número (o erro ocorre antes mesmo que o usuário possa digitar algo):
java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextInt(Scanner.java:2117)
    at java.util.Scanner.nextInt(Scanner.java:2076)

E nesse ponto as opiniões divergem. Há quem diga que nunca se deve fechar um Scanner que usa System.in, pois é a JVM que gerencia o System.in e você não deveria se preocupar com ele ("quem abriu que feche"). Até porque não é possível reabri-lo.
Mas pesquisando na internet você também encontrará soluções que sugerem criar um InputStream cujo método close() não faz nada:
Scanner input = new Scanner(new BufferedInputStream(System.in){ public void close(){} });

// ou
public class MyInputStream extends FilterInputStream {
    public MyInputStream(InputStream in) {
        super(in);
    }
    @Override
    public void close() throws IOException {
        // não faz nada
    }
}

Scanner input = new Scanner(new MyInputStream(System.in));

Assim, você usa o Scanner normalmente, e chama o close() no final (ou usa o bloco try-with-resources), assim o Eclipse para de dar erro de compilação. Mas lembre-se que nesse caso o método close() apenas "finge" que está fechando o System.in, sem fechá-lo de fato.
Outra opção (que foi sugerida na outra resposta) é chamar o método close() no final do seu programa, garantindo que o Scanner - e também o System.in - só será fechado quando ninguém mais precisar dele. Mas nesse caso poderia ter um grande try com um bloco finally (ou um try-with-resources) em torno de todo o seu código, para garantir a execução do método mesmo que ocorra algum erro.

Você também pode ignorar o erro do Eclipse, "fingindo que não viu": basta ir nas configurações (Java -> Compiler -> Errors/Warnings) e setar a opção "Ignore" no item "Resource leak" (só que ele vai deixar de acusar o erro para outros recursos que devem ser fechados, como arquivos e conexões - mas se você garante que nunca vai esquecer de fechar nenhum recurso, vá em frente).
Outra opção é deixar esta opção como "Warning" (em vez de "Ignore"), assim o código compila (mas é mostrado um warning indicando que há um problema ali). Mas se quiser, dá para ignorar warnings específicos com a anotação java.lang.SuppressWarnings:
@SuppressWarnings("resource")
Scanner input = new Scanner(System.in);

Assim você ignora o warning do System.in, mas não os outros (caso haja arquivos/conexões sendo abertos em outros pontos do código, por exemplo).

No caso específico do System.in, não acho que é tão grave ignorar o erro e "esquecer" de fechá-lo (mas também não fará mal chamar close() no final do seu programa), mas para todos os demais recursos (arquivos, conexões, etc), é importante fechá-los sempre que não for precisar mais deles.
Eu diria que o System.in é a exceção desta regra (da mesma forma que System.out e System.err), por ser "especial" e gerenciado pela JVM, e neste caso específico, até daria para "ignorar" o erro do Eclipse. Mas fique à vontade para escolher qualquer uma das abordagens acima, desde que esteja ciente das implicações de cada uma.
Comment: Bem, eu diria que o que mais vale é a dica do link que você deu, em letras grandes, maiúsculas, negrito e vermelho: "***DO NOT CLOSE A SCANNER OBJECT INITIALIZED WITH System.in !***" - Na minha opinião, fechar o `System.in` ou um `Scanner` que o utilize é algo simplesmente muito idiota a se fazer. Enganar o método `close()` é apenas mais uma forma de fazer gambiarra. Se o eclipse não é capaz de identificar esse caso especial e dá uma *warning*, isso é problema do eclipse, e não do código, e portanto o `@SuppressWarnings` é mais que justificado.
Comment: @VictorStafusa Concordo, eu também acho desnecessário fechar o `System.in` (e "fingir" que está fechando é de fato uma gambiarra). Mas optei por uma resposta mais "neutra", mostrando várias alternativas, e aí cada um tira suas próprias conclusões...
Answer: No final da sua classe main, coloque a chamada close().
input.close();

As classes que utilizam recursos que não sejam de memória (no caso a
  Scanner) devem fornecer maneiras de alocar / desalinhar explicitamente
  esses recursos. Precisamos explicitamente chamar métodos close () para
  desalocação de descritores de arquivos em finally {}, já que ele irá
  executar se uma exceção é lançada ou não.
  Fonte: https://stackoverflow.com/questions/24573084/why-we-should-i-close-a-java-util-scanner-variable

No caso, sua classe ficaria assim:
import java.util.Scanner;

public class Principal {

    public static void main() {

        HealthProfile health = new HealthProfile(null, null, null, 0, 0, 0, 0, 0);

        Scanner input = new Scanner( System.in );

        System.out.println("Informe seu nome: ");
        String nome = input.nextLine();
        health.setNome(nome);

        System.out.println("Informe seu sobrenome: ");
        String sobrenome = input.nextLine();
        health.setSobrenome(sobrenome);

        System.out.println("Informe seu sexo: ");
        String sexo = input.nextLine();
        health.setSexo(sexo);

        System.out.println("Informe seu dia de nascimento: ");
        int dia = input.nextInt();
        health.setDia(dia);

        System.out.println("Informe seu mes de nascimento: ");
        int mes = input.nextInt();
        health.setMes(mes);

        System.out.println("Informe seu ano de nascimento: ");
        int ano = input.nextInt();
        health.setAno(ano);

        System.out.println("Informe sua altura: ");
        float altura = input.nextFloat();
        health.setAltura(altura);

        System.out.println("Informe seu peso: ");
        float peso = input.nextFloat();
        health.setPeso(peso);

        System.out.printf("%s ", health.getNome());
        System.out.printf("%s%n", health.getSobrenome());
        System.out.printf("%d anos", health.idadeEmAnos());
        System.out.printf("Sua frequencia máxima é %d%n", health.maximumFrequenciaCardiaca());
        System.out.println("Frequencia Cardiaca Alvo:");
        System.out.printf("A Minima frequencia alvo é : %.0f%n", health.MinFrequenciaCardiacaAlvo());
        System.out.printf("A Maxima frequencia alvo é : %.0f%n", health.MaxFrequenciaCardiacaAlvo());

        input.close();

    }
}

Comment: Parece que agora desapareceu os problemas. O eclipse não está mais sinalizando. Porém, quando eu vou dou um Ctrl + F11, aparece uma janela pop-up com essa mensagem:
"The selection cannot be launched, and there are no recent launches.".
Será que você saberia me dizer o que eu estou errando?
Comment: Bom, isso é problema no launch do eclipse. Procure o botão play  em verde e selecione a classe principal, deve funcionar. Caso tenha resolvido seu problema, marque a resposta como correta, para que outros possam se basear caso passem pelo mesmo problema.
Comment: Cara, descobri o problema:
Está bem aqui:
   "public static void main()"
Observe o que estava faltando:
"public static void main(String [] args)"
Agora o programa rodou tranquilamente.


Universal Link broken in iOS 11.2

Question: I am using Branch deep links in an app for sharing links to content in the app via social media. Everything was working fine quite a while.
When updating to iOS 11.2 I encountered the following behavior:
1) After the update the Universal Links still worked.
2) I uninstalled the app and reinstalled it.
3) Since then, all links always open the Branch deep view in Safari.
4) Tapping "Open The App", opens the AppStore.
It does not matter in which app I tap on the link (Notes, WhatsApp, Messages, Facebook, ...), it is always the same behavior.
The Universal Link was not bypassed by tapping the "go to link" button in the upper right corner (when app was opened). I tested on three different devices (iPhone 5s, iPhone 6s, iPhone 7). All led to the same result.
I found out that there was a bug in iOS 11 beta 2 which was fixed in the beta 3 (Ios 11.2 beta universal links open my app and safari), but it might have reappeared?!
Anyone having the same issues or a way to fix it?
Comment: I have this problem too: iOS 11.2.1 was released a couple of days ago and still seems to have this issue. There is a beta release in the developer centre (11.2.5) which may address this, but I cannot test this right now.
Answer: Sometimes universal links don't work on iOS 11.2 for newly installed apps.
The symptoms are that clicking on a universal link won't open an app that is newly installed on a phone. The universal link takes the user to a web page and is prompted to download the app again.
Through testing here at Branch HQ we've discovered that the Apple App Site Associated Domains  file (apple-app-site-association file) isn't always downloaded after the app is installed, either when it's installed from the app store or from Xcode.
Removing the app, restarting the phone, re-installing the app, and waiting a minute or so seems to clear this up.  This is a horrible user experience obviously.
We have filed a radar with Apple and will continue to track this issue.
Mitigations
Set $uri_redirect_mode
Setting the $uri_redirect_mode option on links can have Branch try to force the link to open the app, even if it might show an error to the user. You can read about this option here, in the Branch docs.
Here's more info about turning on $uri_redirect_mode in your Branch Journey or Deepview banner, the web snippet that Branch shows the user if the ends up deep linking into a web browser:
Advanced Journey Configuration
Deferred Deep Linking Mitigates This Problem
This issue is mitigated by Branch's deferred deep linking tech:  If the user opens the app from their home screen after the universal link is clicked, deferred deep linking still works, and the link content is shown in the app.
Comment: On all my test devices a first click on any link leads to the store. From then on I'm always redirected to the app. Annoying enough that it doesn't work on the first click but finally at least it works afterwards.
Answer: As an addition to @clayjones94's Answer, I have been unable to get my iPad 2nd gen (iOS 12.1.1) to recover the ability to use Universal links after switching between release and debug targets.
Yesterday it suddenly started to work, but then after changing build-target, the universal link has again broken.
I've uninstalled, rebooted, installed, rebooted and so on.
I was, however able to test the functionality in a simulator, so for now, I would recommend attempting a fresh simulator to make sure your AASA file is correct on the server.
EDIT: if you have a proxy involved, that may also break the validation between the app and the website

Universal Link broken in iOS 11.2


Flask and Apache2: No module named app

Question: I'm trying to deploy Flask app via Apache2 but I'm getting No module named app error. I'm also using virtualenv
planer(Flask app)
(venv)jdoe@jdoe-virtual-machine:/var/www/planer$ la
app.py   forms.py   .git        helpers.py   __init__.py  main.pyc   models.pyc   README.md         setup.cfg  templates  views.py
app.pyc  forms.pyc  .gitignore  helpers.pyc  main.py      models.py  planer.wsgi  requirements.txt  static     venv       views.pyc

planer.conf
<VirtualHost *:80>
        ServerName planer.dev
        ServerAdmin email@example.com
        WSGIScriptAlias / /var/www/planer/planer.wsgi
        <Directory /var/www/planer/planer/>
            Order allow,deny
            Allow from all
        </Directory>
        Alias /static /var/www/planer/static
        <Directory /var/www/planer/static/>
            Order allow,deny
            Allow from all
        </Directory>
        ErrorLog ${APACHE_LOG_DIR}/error.log
        LogLevel warn
        CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

planer.wsgi
import sys, os
sys.path.insert (0,'/var/www/planer')

    sys.path = [
        '/var/www/planer/venv/lib/python2.7/lib-dynload',
        '/usr/lib/python2.7',
    ]

    activate_this = '/var/www/planer/venv/bin/activate_this.py'
    execfile(activate_this, dict(__file__=activate_this))

    import app as application

error
[Wed Jan 06 09:45:29.781102 2016] [:error] [pid 20727] [client 127.0.0.1:42448] mod_wsgi (pid=20727): Target WSGI script '/var/www/planer/planer.wsgi' cannot be loaded as Python module.
[Wed Jan 06 09:45:29.781137 2016] [:error] [pid 20727] [client 127.0.0.1:42448] mod_wsgi (pid=20727): Exception occurred processing WSGI script '/var/www/planer/planer.wsgi'.
[Wed Jan 06 09:45:29.781208 2016] [:error] [pid 20727] [client 127.0.0.1:42448] Traceback (most recent call last):
[Wed Jan 06 09:45:29.781235 2016] [:error] [pid 20727] [client 127.0.0.1:42448]   File "/var/www/planer/planer.wsgi", line 12, in <module>
[Wed Jan 06 09:45:29.781302 2016] [:error] [pid 20727] [client 127.0.0.1:42448]     import app as application
[Wed Jan 06 09:45:29.781327 2016] [:error] [pid 20727] [client 127.0.0.1:42448] ImportError: No module named app

Comment: in `planer.wsgi`, use `from app import app as application` works?
Comment: Delete all the *.pyc and try `from planer.app import app as application` works? If still not work, you may show us the content of `app.py` and `__init__.py`.
Answer: Make sure the .wsgi file is executable:
sudo chmod a+x planer.wsgi

And try to load it with this:
python /absolute/path/to/planer.wsgi

Comment: @intelis what was the problem?
Comment: What happens when you do python /absolute/path/to/planer.wsgi?

Flask and Apache2: No module named app


JSF Primefaces pass parameter to fileupload

Question: JSF 2.2 - Primefaces 4.0 - JBoss Wildfly
Hi, I am trying to pass a parameter value to the file upload handler.
I tried a few suggestions I found, but can't get it to work.
I stepped a few steps back
I need the #{fileUploadController.newItemId} in the controller
When going to the file update page it is done with i.e. this URL
/fileUpload.jsf?newItemId=10
I tried what it mentioned in
How to send parameter to fileUploadListener in PrimeFaces fileUpload
and
Passing value to the backing bean with PrimeFaces file upload
fileUpload.xhtml
<code> <f:metadata>
                <f:viewParam name="newItemId"
                    value="#{fileUploadController.newItemId}" />
                <f:viewAction action="#{fileUploadController.loadData()}" />
            </f:metadata>
            <h:form id="item" enctype="multipart/form-data">
                <p:messages id="messages" />

                <p:panelGrid styleClass="panelGridCenter">
                    <p:row>
                        <p:column>
                            <p:fileUpload
                                fileUploadListener="#{fileUploadController.handleFileUpload}"
                                validator="#{fileUploadController.validateFile}" mode="advanced"
                                dragDropSupport="false" update="messages" sizeLimit="1000000"
                                fileLimit="100" allowTypes="/(\.|\/)(gif|jpe?g|png)$/">

                            </p:fileUpload>
                        </p:column>
                    </p:row>
                </p:panelGrid>

            </h:form>
</code>
FileUploadController.java
<code>public void handleFileUpload(FileUploadEvent event) {
        try {

            // Need item id here :)

            UploadedFile file = event.getFile();
            InputStream inputStream = file.getInputstream();
            FileOutputStream outputStream = new FileOutputStream(file.getFileName());
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while (true) {
                bytesRead = inputStream.read(buffer);
                if (bytesRead > 0) {
                    outputStream.write(buffer, 0, bytesRead);
                } else {
                    break;
                }
            }
            outputStream.close();
            inputStream.close();
            Long imageId = serviceSLSB.saveImage(itemId, file, buffer);
            FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded and saved with id." + imageId);
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } catch (Exception e) {
            String errorMessage = getRootErrorMessage(e);
            FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Saving unsuccessful");
            facesContext.addMessage(null, m);
        }
    }

public void loadData() {
    if (newItemId == null) {
        String message = "Bad request. Please use a link from within the system.";
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
        return;
    } else {
        String message = "Your are adding images to item with id : " + newItemId;
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, message, null));
        return;
    }
}
</code>
Comment: What is newItemId and where is it coming from ?
Comment: Passing parameter to the event handler is not possible. Just accepts PF FileUpload event. Apart from that you say you need `#{fileUploadController.newItemId}`, but don't you already have it?
Answer: I just found that my controller was only request scoped, after changing it to
@ViewScoped
@Named
public class FileUploadController implements Serializable
I of cause still have the item id, and can now add images to that item.
Thanks for the comments guys


Doctrine 2 join table + extra fields

Question: I've got two tables and a join table: 'staff', 'classification' and 'staff_classification'. In the join table I've got an extra boolean field: 'showclassification'. My annotation is as follows:
<code> /**
 * @ManyToMany(targetEntity="Staff", inversedBy="classifications")
 * @JoinTable(name="staff_classifications",
 *  joinColumns={@JoinColumn(name="staffid", referencedColumnName="id")},
 *  inverseJoinColumns={@JoinColumn(name="classificationid", referencedColumnName="id", unique=true)});
 */
</code>

How do I add the extra field 'showclassifications' to the join table?
How do I reference the field via DQL? E.g. What query would get all of a staff's classifications that are allowed to be shown?
Do I place the above annotation in one class and a @ManyToMany annotation with no @joinTable in the other? E.g. @ManyToMany (targetEntity="Classification")?
Comment: Here you can find a great article about the approach to follow in this case: http://future500.nl/articles/2013/09/doctrine-2-how-to-handle-join-tables-with-extra-columns/
Answer: You want an entity that describes the relationship (StaffClassifications), which has OneToMany relationships with both staff and classifications.
ManyToMany doesn't allow you have any "extra" properties, because the join table is not an entity, and thus can't have any properties.
Comment: +1 It's the logical OO way to do things. This exact question gets asked a lot on the mailing list, and it's what the Doctrine team suggests as well.
Comment: Using the OO pattern, what is the answer to question 2 above? What would the DQL look like?
Comment: awesome. Thanks, I'll follow that pattern and see how I go. Cheers.
Comment: Somethlink like `select s, sc, c from Staff s join StaffClassificaiton sc join Classification c ...`

Doctrine 2 join table + extra fields