问:
How to use a DialogFragment to return either true or false?
I have a password dialog class that ask password when ever they want to delete something or add. What i want is that can reuse this dialog again and again.
 Heres my password dialog class looks like

```<code>public static class myPasswordDialog extends DialogFragment {

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater inflater = getActivity().getLayoutInflater();
            builder.setView(inflater.inflate(R.layout.password_dialog, null))
                    .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            EditText passField = (EditText) ((AlertDialog) dialog).findViewById(R.id.password);
                            String password = passField.getText().toString();
                            if (password.matches(getString(R.string.pass_key))) {

                                //it should do something when it is correct
                            } else {
                                Toast.makeText(getActivity(), "Wrong Password", Toast.LENGTH_SHORT).show();
                            }
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            return builder.create();
        }
    }
</code>```

and this is how I call my password class

```<code>deletebtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myPasswordDialog mPasswordDialog = new myPasswordDialog();
                        mPasswordDialog.show(getFragmentManager(), "delete");
                    }
                });
</code>```

What I have in mind is that the fragment will return a boolean if they inputted the right or wrong password. But in what way can I do it?

答:
Implement an interface and set a  call back

```<code>public static class MyPasswordDialog extends DialogFragment {
    public interface MyCallBack {
        public void onResult(boolean b);
    }

    public MyCallBack callBack;

    public MyPasswordDialog(MyCallBack callBack) {
        this.callBack = callBack;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // your code

    public void onClick(DialogInterface dialog, int id) {
        EditText passField = (EditText) ((AlertDialog) dialog).findViewById(R.id.password);
        String password = passField.getText().toString();
        if (password.matches(getString(R.string.pass_key))) {
            callBack.onResult(true); // pass false depends on condition
        } else {
        // code
        }
    }

    }

}
</code>```

How to call

```<code>deletebtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myPasswordDialog mPasswordDialog = new MyPasswordDialog(new MyPasswordDialog() {
                        @Override
                        public void onResult(boolean result) {
                        // result will be your ans
                        }
                    });
                    mPasswordDialog.show(getFragmentManager(), "delete");
                }
            });
</code>```

Body:
I have a password dialog class that ask password when ever they want to delete something or add. What i want is that can reuse this dialog again and again.
 Heres my password dialog class looks like

public static class myPasswordDialog extends DialogFragment {

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater inflater = getActivity().getLayoutInflater();
            builder.setView(inflater.inflate(R.layout.password_dialog, null))
                    .setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int id) {
                            EditText passField = (EditText) ((AlertDialog) dialog).findViewById(R.id.password);
                            String password = passField.getText().toString();
                            if (password.matches(getString(R.string.pass_key))) {

                                //it should do something when it is correct
                            } else {
                                Toast.makeText(getActivity(), "Wrong Password", Toast.LENGTH_SHORT).show();
                            }
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.dismiss();
                        }
                    });
            return builder.create();
        }
    }

and this is how I call my password class

deletebtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myPasswordDialog mPasswordDialog = new myPasswordDialog();
                        mPasswordDialog.show(getFragmentManager(), "delete");
                    }
                });

What I have in mind is that the fragment will return a boolean if they inputted the right or wrong password. But in what way can I do it?

Body:
Implement an interface and set a  call back

public static class MyPasswordDialog extends DialogFragment {
    public interface MyCallBack {
        public void onResult(boolean b);
    }

    public MyCallBack callBack;

    public MyPasswordDialog(MyCallBack callBack) {
        this.callBack = callBack;
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
    // your code

    public void onClick(DialogInterface dialog, int id) {
        EditText passField = (EditText) ((AlertDialog) dialog).findViewById(R.id.password);
        String password = passField.getText().toString();
        if (password.matches(getString(R.string.pass_key))) {
            callBack.onResult(true); // pass false depends on condition
        } else {
        // code
        }
    }

    }

}

How to call

deletebtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    myPasswordDialog mPasswordDialog = new MyPasswordDialog(new MyPasswordDialog() {
                        @Override
                        public void onResult(boolean result) {
                        // result will be your ans
                        }
                    });
                    mPasswordDialog.show(getFragmentManager(), "delete");
                }
            });


来源: stackexchange

问:
I got InternalError when I use getSharedPreferences in android 7.1
I got java internal error when I use "getSharedPreferences" android api.
This is my code:

```<code>private int getByte() {
    final SharedPreferences prefs = m_ctx.getSharedPreferences("config", 0);
    ...
}
</code>```

but I find the android source code and got below:

```<code>private void startLoadFromDisk() {
    synchronized (this) {
        mLoaded = false;
    }
    new Thread("SharedPreferencesImpl-load") {
        public void run() {
            loadFromDisk();
        }
    }.start();
}
</code>```

I donnot know which is wrong? Thank you very much!

The log is:

```<code>java.lang.InternalError:
at java.lang.Thread.nativeCreate(Native Method:0)
at java.lang.Thread.start(Thread.java:730)
at android.app.SharedPreferencesImpl.startLoadFromDisk(SharedPreferencesImpl.java:98)
at android.app.SharedPreferencesImpl.<init>(SharedPreferencesImpl.java:91)
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:360)
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:349)
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:164)
...
</code>```

答:
Try this,
Instead using mCtx you can try using getApplicationContext()..

(i,e).

```<code>final SharedPreferences prefs = getApplicationContext().getSharedPreferences("config", 0);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I got java internal error when I use "getSharedPreferences" android api.
This is my code:

private int getByte() {
    final SharedPreferences prefs = m_ctx.getSharedPreferences("config", 0);
    ...
}

but I find the android source code and got below:

private void startLoadFromDisk() {
    synchronized (this) {
        mLoaded = false;
    }
    new Thread("SharedPreferencesImpl-load") {
        public void run() {
            loadFromDisk();
        }
    }.start();
}

I donnot know which is wrong? Thank you very much!

The log is:

java.lang.InternalError:
at java.lang.Thread.nativeCreate(Native Method:0)
at java.lang.Thread.start(Thread.java:730)
at android.app.SharedPreferencesImpl.startLoadFromDisk(SharedPreferencesImpl.java:98)
at android.app.SharedPreferencesImpl.<init>(SharedPreferencesImpl.java:91)
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:360)
at android.app.ContextImpl.getSharedPreferences(ContextImpl.java:349)
at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:164)
...

Body:
Try this,
Instead using mCtx you can try using getApplicationContext()..

(i,e).

final SharedPreferences prefs = getApplicationContext().getSharedPreferences("config", 0);


问:
oracle sql query error while comparing date columns
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.</p>

```<code>select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'
</code>```

答:
```<code>select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE LIKE TO_DATE('11-DEC-10','DD-MON-YY')
 and a.START_DATE = b.a_date and b.code = 'JFK'
</code>```

If you stored your START_DATE as Number like 'YYYYMMDD':

```<code>a.START_DATE=TO_NUMBER(TO_DATE('20101211','YYYYMMDD'))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a following oracle sql query in which START_DATE is a number column and a_date is DATE type and the input value is also of type DATE. kindly let me know how to compare the date columns with the input date.

select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE = to_date('11-DEC-10','YYYYMMDD')
 and a.START_DATE = b.a_date and b.code = 'JFK'

Body:
select a.id ,a.v ,b.id,b.v
 from DATA a ,FDC  b  where a.START_DATE LIKE TO_DATE('11-DEC-10','DD-MON-YY')
 and a.START_DATE = b.a_date and b.code = 'JFK'

If you stored your START_DATE as Number like 'YYYYMMDD':

a.START_DATE=TO_NUMBER(TO_DATE('20101211','YYYYMMDD'))


问:
c#,Textbox not working while taking web respose
I am using the following function to get response of a url from web. when i place the response in message box it displays properly.when i put it in text box the programme gets stuck on that statement and doesn't move.why is it happening,as i am feeding the string(response_message) to textbox.

```<code>void message_send(int j)
{
    int y = 0;

        if (CONTACT_NO[j] != "")
        {

        string Message = "hello";

        string url = "some url not mentioned here ";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
              request.Timeout = 30000;
              using (WebResponse response = (HttpWebResponse)request.GetResponse())
              {
                  byte[] bytes = ReadFully(response.GetResponseStream());
            response_message = System.Text.Encoding.UTF8.GetString(bytes);
            // error_logs(str);
            MessageBox.Show(response_message);
           textBox2.Text = response_message;
              }
        //textBox3.Text = response_message;

    }
        else
        {
           messagebox.show("some message");

        }
</code>```

答:
I was using my this function in backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) function.which i guess is separate thread.due to which i wasn't able to access textbox1.hence i used the following method to access it.

```<code> private void SetText1(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText1);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox2.Text = text;
            }

        }
</code>```

Mistake that i was doing i wasn't using the try catch method to check for the exception.which helps me in understanding my issue.

Body:
I am using the following function to get response of a url from web. when i place the response in message box it displays properly.when i put it in text box the programme gets stuck on that statement and doesn't move.why is it happening,as i am feeding the string(response_message) to textbox.

void message_send(int j)
{
    int y = 0;

        if (CONTACT_NO[j] != "")
        {

        string Message = "hello";

        string url = "some url not mentioned here ";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
              request.Timeout = 30000;
              using (WebResponse response = (HttpWebResponse)request.GetResponse())
              {
                  byte[] bytes = ReadFully(response.GetResponseStream());
            response_message = System.Text.Encoding.UTF8.GetString(bytes);
            // error_logs(str);
            MessageBox.Show(response_message);
           textBox2.Text = response_message;
              }
        //textBox3.Text = response_message;

    }
        else
        {
           messagebox.show("some message");

        }

Body:
I was using my this function in backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) function.which i guess is separate thread.due to which i wasn't able to access textbox1.hence i used the following method to access it.

 private void SetText1(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText1);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.textBox2.Text = text;
            }

        }

Mistake that i was doing i wasn't using the try catch method to check for the exception.which helps me in understanding my issue.


问:
SQL query to get the count by applying group by
I want to get the below result:

source table :

```<code>Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE
</code>```

Result:

```<code>Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE
</code>```

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

答:
You can get your string till '/' by using SUBSTRING.

```<code>select
count(SUBSTRING(reverse(B),0,charindex('/',reverse(B)))),
A,
SUBSTRING(reverse(B),0,charindex('/',reverse(B)))
from source_table group by B;
</code>```

Body:
I want to get the below result:

source table :

Cnt  A    B
4   ABC YU/FGH
5   ABC YU/DFE
5   ABC KL
2   LKP BN/ER
4   JK  RE

Result:

Cnt  A  B
9   ABC YU
5   ABC KL
2   LKP BN
4   JK  RE

Here I want the count by grouping 'B' and want to display the 'B' record only till the special character (/)

Body:
You can get your string till '/' by using SUBSTRING.

select
count(SUBSTRING(reverse(B),0,charindex('/',reverse(B)))),
A,
SUBSTRING(reverse(B),0,charindex('/',reverse(B)))
from source_table group by B;


问:
Bad base-64 in my android application
I want to decode an image from a server, when i try to decode this string:

```<code>x1a
                                                                     x00x00x00IHDRx00x00x06@x00x00x03,x08x02x00x00x00x83`xf9vx00x00x00x03sBITx08x08x08xdbxe1Oxe0x00x00x00x96zTXtRaw profile type APP1x00x00xx9cUx8eAx0exc3 x0cx04xefxbcx82'x8cm0xf0x1cTx91*Rxd5Vxf9xffxa1x07Hxdbxecexa5Ykxd7xe1>x9exe3xd8oxf1}xbcxb6xfd1Bx8c1Fx91x1aRKM;Px99R0APxa0,xe4xd3xbdxd5Bx02dxf1xc1Ex19on.xc5|^x18@x9b=x89x85LMxa4xcf|u}=wxfe7xf2xf9xd7)]x99xfe:xb3Zxb3xbaxd8uKl>x01@xf8x00xe7U5txef,xfdxd5x00x00 x00IDATxx9cxecxddxe9{x1cxc7x91xefxfbx88xc8xacxeax05x80x92xa8xcdx1exdb3xf6xxe6xc5xb9xffxffxdb{x9e3xf7xccxe6xd9mKxb6lilkx19/xa2Hx8a$x80xeexaexccxb8/2xb3xbaxd0x00ayx91Xx92xbex9fxe7xb1x0cxf6ZUhx00xd5xbfx8ex88Twx17x00x00x00x00x00x00`xaexecEox00x00x00x00x00x00x00px17x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xa
</code>```

It gives me this error bad base-64

My Code for encoding is:

```<code>public Bitmap StringToBitMap(String encodedString){
    try {
        byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT  );
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    } catch(Exception e) {
      e.getMessage();
        return null;
    }
}
</code>```

答: x1a is not a base64 encoded string. Base64 encoded strings end with = or ==. Base64.decode() can only decode strings encoded with Base64. I hope it makes sense.

Title: Bad base-64 in my android application

Body:
I want to decode an image from a server, when i try to decode this string:

x1a
                                                                     x00x00x00IHDRx00x00x06@x00x00x03,x08x02x00x00x00x83`xf9vx00x00x00x03sBITx08x08x08xdbxe1Oxe0x00x00x00x96zTXtRaw profile type APP1x00x00xx9cUx8eAx0exc3 x0cx04xefxbcx82'x8cm0xf0x1cTx91*Rxd5Vxf9xffxa1x07Hxdbxecexa5Ykxd7xe1>x9exe3xd8oxf1}xbcxb6xfd1Bx8c1Fx91x1aRKM;Px99R0APxa0,xe4xd3xbdxd5Bx02dxf1xc1Ex19on.xc5|^x18@x9b=x89x85LMxa4xcf|u}=wxfe7xf2xf9xd7)]x99xfe:xb3Zxb3xbaxd8uKl>x01@xf8x00xe7U5txef,xfdxd5x00x00 x00IDATxx9cxecxddxe9{x1cxc7x91xefxfbx88xc8xacxeax05x80x92xa8xcdx1exdb3xf6xxe6xc5xb9xffxffxdb{x9e3xf7xccxe6xd9mKxb6lilkx19/xa2Hx8a$x80xeexaexccxb8/2xb3xbaxd0x00ayx91Xx92xbex9fxe7xb1x0cxf6ZUhx00xd5xbfx8ex88Twx17x00x00x00x00x00x00`xaexecEox00x00x00x00x00x00x00px17x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xacx11`x01x00x00x00x00x00`xd6x08xb0x00x00x00x00x00x000kx04Xx00x00x00x00x00x00x985x02,x00x00x00x00x00x00xccx1ax01x16x00x00x00x00x00x00fx8dx00x0bx00x00x00x00x00x00xb3Fx80x05x00x00x00x00x00x80Y#xc0x02x00x00x00x00x00xc0xa

It gives me this error bad base-64

My Code for encoding is:

public Bitmap StringToBitMap(String encodedString){
    try {
        byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT  );
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    } catch(Exception e) {
      e.getMessage();
        return null;
    }
}


问:
Find two fields with the same value within separate arrays
```<code>"first_name" : [

    ]
</code>```

I have database like above . I want find field first_name and last_name have type = primary . I tried this code but it get all data :

```<code> var fieledUsers = {
            'first_name': 1,
            'last_name': 1,

            };
            var matching = {
                'first_name.type' :'primary',
                'last_name.type' :'primary'
            }
            var conditionUsers = {"_id": users_id};
            db.collection('users').aggregate([{$project:fieledUsers},{$match:matching}],function (err, resUsers) {
</code>```

How can I do it . Thank in advance

答:
You can always "match" the document that contains both properties by supplying the values to both properties as the query condition. But to get the positional match to both you need $filter with aggregate:

```<code>db.collection.aggregate([
  { "$match": {
    "_id": users_id,
    "first_name.type": "primary",
    "last_name.type": "primary"
  }},
  { "$addFields": {
    "first_name": {
      "$arrayElemAt": [
        { "$filter": {
          "input": "$first_name",
          "as": "el",
          "cond": { "$eq": [ "$$el.type", "primary" ] }
        }},
        0
      ]
    },
    "last_name": {
      "$arrayElemAt": [
        { "$filter": {
          "input": "$last_name",
          "as": "el",
          "cond": { "$eq": [ "$$el.type", "primary" ] }
        }},
        0
      ]
    }
  }}
])
</code>```

The positional $ operator which can be used with a standard query is fine for matching a "single" element in array. But for multiple matches, or as in this case where the matches can be in "different" positions in each array, then then this sort of operation with $filter is required. Also using $arrayElemAt as example to just extract the single element from the array.

Body:
"first_name" : [

    ]

I have database like above . I want find field first_name and last_name have type = primary . I tried this code but it get all data :

 var fieledUsers = {
            'first_name': 1,
            'last_name': 1,

            };
            var matching = {
                'first_name.type' :'primary',
                'last_name.type' :'primary'
            }
            var conditionUsers = {"_id": users_id};
            db.collection('users').aggregate([{$project:fieledUsers},{$match:matching}],function (err, resUsers) {

How can I do it . Thank in advance

Body:
You can always "match" the document that contains both properties by supplying the values to both properties as the query condition. But to get the positional match to both you need $filter with aggregate:

db.collection.aggregate([
  { "$match": {
    "_id": users_id,
    "first_name.type": "primary",
    "last_name.type": "primary"
  }},
  { "$addFields": {
    "first_name": {
      "$arrayElemAt": [
        { "$filter": {
          "input": "$first_name",
          "as": "el",
          "cond": { "$eq": [ "$$el.type", "primary" ] }
        }},
        0
      ]
    },
    "last_name": {
      "$arrayElemAt": [
        { "$filter": {
          "input": "$last_name",
          "as": "el",
          "cond": { "$eq": [ "$$el.type", "primary" ] }
        }},
        0
      ]
    }
  }}
])

The positional $ operator which can be used with a standard query is fine for matching a "single" element in array. But for multiple matches, or as in this case where the matches can be in "different" positions in each array, then then this sort of operation with $filter is required. Also using $arrayElemAt as example to just extract the single element from the array.


问:
Possible to set attributes of ActionViewClass through xml in Android Action Bar?
I have the following menu xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/action_select_appshare"
    android:showAsAction="always"
    android:title="@string/action_select_appshare"
    android:actionViewClass="android.widget.Spinner" />

</menu>
</code>```

Because a Spinner seem to require the definition of the android:spinnerMode attribute from the get-go, and there doesn't seem to be a proper way to set it later on after the Spinner object is created. I was wondering if there's a way to specify additional attributes (such as android:spinnerMode in my e.g.) for an android:actionViewClass within the menu XML?

Thanks!

答:
Finally found it:

Related links: 1, 2 and 3

Create a new res/layout file. Put the spinner in it, with all the properties you need/want. Note that the Spinner should be the root view.

In your menu file containing the actionClassProvider=spinner, remove actionClassProvider, and replace it with actionLayout="@layout/my_spinner"

All Done

I hope this helps somebody!

Body:
I have the following menu xml code:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
    android:id="@+id/action_select_appshare"
    android:showAsAction="always"
    android:title="@string/action_select_appshare"
    android:actionViewClass="android.widget.Spinner" />

</menu>

Because a Spinner seem to require the definition of the android:spinnerMode attribute from the get-go, and there doesn't seem to be a proper way to set it later on after the Spinner object is created. I was wondering if there's a way to specify additional attributes (such as android:spinnerMode in my e.g.) for an android:actionViewClass within the menu XML?

Thanks!


问:
Sqoop Merge : Class name not found
Error shown below I am getting class name not found error while doing Sqoop merge. I took the path of the jar file gettting created. But still getting the error.

1.Sqoop import command and the jar file created path below..

```<code>**sqoop import --connect jdbc:mysql://ip-172-31-13-154:3306/sqoopex --username sqoopuser --password NHkkP876rp --query "select * from departments where \$CONDITIONS" --target-dir /user/sakthimuruganv2214/sakthi/sqoop_import/departments_new --split-by department_id**
17/06/03 15:10:51 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6.2.3.4.0-3485
17/06/03 15:10:51 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/06/03 15:10:51 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.17/06/03 15:10:51 INFO tool.CodeGenTool: Beginning code generation
17/06/03 15:10:51 INFO manager.SqlManager: Executing SQL statement: select * from departments where  (1 = 0)
17/06/03 15:10:51 INFO manager.SqlManager: Executing SQL statement: select * from departments where  (1 = 0)
17/06/03 15:10:51 INFO manager.SqlManager: Executing SQL statement: select * from departments where  (1 = 0)
17/06/03 15:10:51 INFO orm.CompilationManager: HADOOP_MAPRED_HOME is /usr/hdp/2.3.4.0-3485/hadoop-mapreduce
Note: /tmp/sqoop-sakthimuruganv2214/compile/eb54f9171acb69d7044867fba5396b7a/QueryResult.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
17/06/03 15:10:53 INFO orm.CompilationManager: **Writing jar file: /tmp/sqoop-sakthimuruganv2214/compile/eb54f9171acb69d7044867fba5396b7a/QueryResult.jar**
17/06/03 15:10:53 INFO mapreduce.ImportJobBase: Beginning query import.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/hadoop/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/zookeeper/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/accumulo/lib/slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See htt://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
17/06/03 15:10:54 INFO impl.TimelineClientImpl: Timeline service address: htt://ip-172-31-13-154.ec2.internal:8188/ws/v1/timeline/
17/06/03 15:10:54 INFO client.RMProxy: Connecting to ResourceManager at ip-172-31-53-48.ec2.internal/172.31.53.48:8050
17/06/03 15:10:57 INFO db.DBInputFormat: Using read commited transaction isolation
17/06/03 15:10:57 INFO db.DataDrivenDBInputFormat: BoundingValsQuery: SELECT MIN(department_id), MAX(department_id) FROM (select * from departments where  (1 = 1) ) AS t1
17/06/03 15:10:57 INFO mapreduce.JobSubmitter: number of splits:4
17/06/03 15:10:57 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1495368194937_3155
17/06/03 15:10:57 INFO impl.YarnClientImpl: Submitted application application_1495368194937_3155
17/06/03 15:10:57 INFO mapreduce.Job: The url to track the job: htt://a.cloudxlab.com:8088/proxy/application_1495368194937_3155/
17/06/03 15:10:57 INFO mapreduce.Job: Running job: job_1495368194937_3155
17/06/03 15:11:05 INFO mapreduce.Job: Job job_1495368194937_3155 running in uber mode : false
17/06/03 15:11:05 INFO mapreduce.Job:  map 0% reduce 0%
17/06/03 15:11:10 INFO mapreduce.Job:  map 100% reduce 0%
17/06/03 15:11:11 INFO mapreduce.Job: Job job_1495368194937_3155 completed successfully
17/06/03 15:11:11 INFO mapreduce.Job: Counters: 30
        File System Counters
                FILE: Number of bytes read=0
                FILE: Number of bytes written=597796
                FILE: Number of read operations=0
                FILE: Number of large read operations=0
                FILE: Number of write operations=0
                HDFS: Number of bytes read=486
                HDFS: Number of bytes written=305
                HDFS: Number of read operations=16
                HDFS: Number of large read operations=0
                HDFS: Number of write operations=8
        Job Counters
                Launched map tasks=4
                Other local map tasks=4
                Total time spent by all maps in occupied slots (ms)=36480
                Total time spent by all reduces in occupied slots (ms)=0
                Total time spent by all map tasks (ms)=12160
                Total vcore-seconds taken by all map tasks=12160
                Total megabyte-seconds taken by all map tasks=18677760
        Map-Reduce Framework
                Map input records=25
                Map output records=25
                Input split bytes=486
                Spilled Records=0
                Failed Shuffles=0
                Merged Map outputs=0
                GC time elapsed (ms)=204
                CPU time spent (ms)=4940
                Physical memory (bytes) snapshot=878874624
                Virtual memory (bytes) snapshot=12966318080
                Total committed heap usage (bytes)=726138880
        File Input Format Counters
                Bytes Read=0
        File Output Format Counters
                Bytes Written=305
17/06/03 15:11:11 INFO mapreduce.ImportJobBase: Transferred 305 bytes in 16.9768 seconds (17.9657 bytes/sec)
17/06/03 15:11:11 INFO mapreduce.ImportJobBase: Retrieved 25 records.
</code>```

2.Sqoop merge Command and Error

```<code>**sqoop merge --merge-key department_id --new-data /user/sakthimuruganv2214/sakthi/sqoop_import/departments_new --onto /user/sakthimuruganv2214/sakthi/sqoop_import/departments_update --target-dir /user/sakthimuruganv2214/sakthi/sqoop_import/departments_merge/ --class-name departments --jar-file  /tmp/sqoop-sakthimuruganv2214/compile/eb54f9171acb69d7044867fba5396b7a/QueryResult.jar**

17/06/03 15:16:06 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6.2.3.4.0-3485
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/hadoop/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/zookeeper/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/accumulo/lib/slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
17/06/03 15:16:07 INFO impl.TimelineClientImpl: Timeline service address: htt://ip-172-31-13-154.ec2.internal:8188/ws/v1/timeline/
17/06/03 15:16:07 INFO client.RMProxy: Connecting to ResourceManager at ip-172-31-53-48.ec2.internal/172.31.53.48:8050
17/06/03 15:16:09 INFO input.FileInputFormat: Total input paths to process : 5
17/06/03 15:16:09 INFO mapreduce.JobSubmitter: number of splits:5
17/06/03 15:16:09 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1495368194937_3156
17/06/03 15:16:10 INFO impl.YarnClientImpl: Submitted application application_1495368194937_3156
17/06/03 15:16:10 INFO mapreduce.Job: The url to track the job: http://a.cloudxlab.com:8088/proxy/application_1495368194937_3156/
17/06/03 15:16:10 INFO mapreduce.Job: Running job: job_1495368194937_3156
17/06/03 15:16:16 INFO mapreduce.Job: Job job_1495368194937_3156 running in uber mode : false
17/06/03 15:16:16 INFO mapreduce.Job:  map 0% reduce 0%
17/06/03 15:16:20 INFO mapreduce.Job: Task Id : attempt_1495368194937_3156_m_000002_0, Status : FAILED
**Error: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class departments not found at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2195)at org.apache.sqoop.mapreduce.MergeTextMapper.setup(MergeTextMapper.java:42)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:143)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
 at **
</code>```

答:
Since you have not specified --class-name during Sqoop Import, therefore it has created default class name QueryResult

Replace --class-name departments to --class-name QueryResult in Sqoop merge command

Title: Sqoop Merge : Class name not found

Body:
Error shown below I am getting class name not found error while doing Sqoop merge. I took the path of the jar file gettting created. But still getting the error.

1.Sqoop import command and the jar file created path below..

**sqoop import --connect jdbc:mysql://ip-172-31-13-154:3306/sqoopex --username sqoopuser --password NHkkP876rp --query "select * from departments where \$CONDITIONS" --target-dir /user/sakthimuruganv2214/sakthi/sqoop_import/departments_new --split-by department_id**
17/06/03 15:10:51 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6.2.3.4.0-3485
17/06/03 15:10:51 WARN tool.BaseSqoopTool: Setting your password on the command-line is insecure. Consider using -P instead.
17/06/03 15:10:51 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.17/06/03 15:10:51 INFO tool.CodeGenTool: Beginning code generation
17/06/03 15:10:51 INFO manager.SqlManager: Executing SQL statement: select * from departments where  (1 = 0)
17/06/03 15:10:51 INFO manager.SqlManager: Executing SQL statement: select * from departments where  (1 = 0)
17/06/03 15:10:51 INFO manager.SqlManager: Executing SQL statement: select * from departments where  (1 = 0)
17/06/03 15:10:51 INFO orm.CompilationManager: HADOOP_MAPRED_HOME is /usr/hdp/2.3.4.0-3485/hadoop-mapreduce
Note: /tmp/sqoop-sakthimuruganv2214/compile/eb54f9171acb69d7044867fba5396b7a/QueryResult.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
17/06/03 15:10:53 INFO orm.CompilationManager: **Writing jar file: /tmp/sqoop-sakthimuruganv2214/compile/eb54f9171acb69d7044867fba5396b7a/QueryResult.jar**
17/06/03 15:10:53 INFO mapreduce.ImportJobBase: Beginning query import.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/hadoop/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/zookeeper/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/accumulo/lib/slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See htt://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
17/06/03 15:10:54 INFO impl.TimelineClientImpl: Timeline service address: htt://ip-172-31-13-154.ec2.internal:8188/ws/v1/timeline/
17/06/03 15:10:54 INFO client.RMProxy: Connecting to ResourceManager at ip-172-31-53-48.ec2.internal/172.31.53.48:8050
17/06/03 15:10:57 INFO db.DBInputFormat: Using read commited transaction isolation
17/06/03 15:10:57 INFO db.DataDrivenDBInputFormat: BoundingValsQuery: SELECT MIN(department_id), MAX(department_id) FROM (select * from departments where  (1 = 1) ) AS t1
17/06/03 15:10:57 INFO mapreduce.JobSubmitter: number of splits:4
17/06/03 15:10:57 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1495368194937_3155
17/06/03 15:10:57 INFO impl.YarnClientImpl: Submitted application application_1495368194937_3155
17/06/03 15:10:57 INFO mapreduce.Job: The url to track the job: htt://a.cloudxlab.com:8088/proxy/application_1495368194937_3155/
17/06/03 15:10:57 INFO mapreduce.Job: Running job: job_1495368194937_3155
17/06/03 15:11:05 INFO mapreduce.Job: Job job_1495368194937_3155 running in uber mode : false
17/06/03 15:11:05 INFO mapreduce.Job:  map 0% reduce 0%
17/06/03 15:11:10 INFO mapreduce.Job:  map 100% reduce 0%
17/06/03 15:11:11 INFO mapreduce.Job: Job job_1495368194937_3155 completed successfully
17/06/03 15:11:11 INFO mapreduce.Job: Counters: 30
        File System Counters
                FILE: Number of bytes read=0
                FILE: Number of bytes written=597796
                FILE: Number of read operations=0
                FILE: Number of large read operations=0
                FILE: Number of write operations=0
                HDFS: Number of bytes read=486
                HDFS: Number of bytes written=305
                HDFS: Number of read operations=16
                HDFS: Number of large read operations=0
                HDFS: Number of write operations=8
        Job Counters
                Launched map tasks=4
                Other local map tasks=4
                Total time spent by all maps in occupied slots (ms)=36480
                Total time spent by all reduces in occupied slots (ms)=0
                Total time spent by all map tasks (ms)=12160
                Total vcore-seconds taken by all map tasks=12160
                Total megabyte-seconds taken by all map tasks=18677760
        Map-Reduce Framework
                Map input records=25
                Map output records=25
                Input split bytes=486
                Spilled Records=0
                Failed Shuffles=0
                Merged Map outputs=0
                GC time elapsed (ms)=204
                CPU time spent (ms)=4940
                Physical memory (bytes) snapshot=878874624
                Virtual memory (bytes) snapshot=12966318080
                Total committed heap usage (bytes)=726138880
        File Input Format Counters
                Bytes Read=0
        File Output Format Counters
                Bytes Written=305
17/06/03 15:11:11 INFO mapreduce.ImportJobBase: Transferred 305 bytes in 16.9768 seconds (17.9657 bytes/sec)
17/06/03 15:11:11 INFO mapreduce.ImportJobBase: Retrieved 25 records.

2.Sqoop merge Command and Error

**sqoop merge --merge-key department_id --new-data /user/sakthimuruganv2214/sakthi/sqoop_import/departments_new --onto /user/sakthimuruganv2214/sakthi/sqoop_import/departments_update --target-dir /user/sakthimuruganv2214/sakthi/sqoop_import/departments_merge/ --class-name departments --jar-file  /tmp/sqoop-sakthimuruganv2214/compile/eb54f9171acb69d7044867fba5396b7a/QueryResult.jar**

17/06/03 15:16:06 INFO sqoop.Sqoop: Running Sqoop version: 1.4.6.2.3.4.0-3485
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/hadoop/lib/slf4j-log4j12-1.7.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/zookeeper/lib/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/hdp/2.3.4.0-3485/accumulo/lib/slf4j-log4j12.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
17/06/03 15:16:07 INFO impl.TimelineClientImpl: Timeline service address: htt://ip-172-31-13-154.ec2.internal:8188/ws/v1/timeline/
17/06/03 15:16:07 INFO client.RMProxy: Connecting to ResourceManager at ip-172-31-53-48.ec2.internal/172.31.53.48:8050
17/06/03 15:16:09 INFO input.FileInputFormat: Total input paths to process : 5
17/06/03 15:16:09 INFO mapreduce.JobSubmitter: number of splits:5
17/06/03 15:16:09 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1495368194937_3156
17/06/03 15:16:10 INFO impl.YarnClientImpl: Submitted application application_1495368194937_3156
17/06/03 15:16:10 INFO mapreduce.Job: The url to track the job: http://a.cloudxlab.com:8088/proxy/application_1495368194937_3156/
17/06/03 15:16:10 INFO mapreduce.Job: Running job: job_1495368194937_3156
17/06/03 15:16:16 INFO mapreduce.Job: Job job_1495368194937_3156 running in uber mode : false
17/06/03 15:16:16 INFO mapreduce.Job:  map 0% reduce 0%
17/06/03 15:16:20 INFO mapreduce.Job: Task Id : attempt_1495368194937_3156_m_000002_0, Status : FAILED
**Error: java.lang.RuntimeException: java.lang.ClassNotFoundException: Class departments not found at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2195)at org.apache.sqoop.mapreduce.MergeTextMapper.setup(MergeTextMapper.java:42)
at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:143)
at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:787)
at org.apache.hadoop.mapred.MapTask.run(MapTask.java:341)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:422)
 at **


问:
How to delete section of UITableView on click of view in swift3
I want to remove a table cell on click of view which is on cell in swift3.

Following function is called on click of View and remove method is used to delete table section.But this solution is not working.

```<code>func remove(sender: UITapGestureRecognizer)
        {
            let indexView = sender.view
            let index = indexView?.tag

            self.removeAddresses(position: index!)
        }

    func remove(position: Int)
    {
        tableView.deleteSections(IndexSet(index: position,with. automatic))
        tableView.reloadData()
    }
</code>```

答:
To remove a table cell, I suggest you can use Editing Style

Methods:

```<code>func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

            }
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {

        }
</code>```

And I think ,

```<code>  func remove(sender: UITapGestureRecognizer){
            let indexView = sender.view
            let index = indexView?.tag
            self.removeAddresses(position: index!)
        }

  func removeAddresses(position: Int){
     tableView.beginUpdates()
     yourDataSourceArray.removeObject(at: position)
     table.deleteRows(at: [indexPathCreated] , with: .automatic)
     table.endUpdates()
   }
</code>```

Body:
I want to remove a table cell on click of view which is on cell in swift3.

Following function is called on click of View and remove method is used to delete table section.But this solution is not working.

func remove(sender: UITapGestureRecognizer)
        {
            let indexView = sender.view
            let index = indexView?.tag

            self.removeAddresses(position: index!)
        }

    func remove(position: Int)
    {
        tableView.deleteSections(IndexSet(index: position,with. automatic))
        tableView.reloadData()
    }

Body:
To remove a table cell, I suggest you can use Editing Style

Methods:

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

            }
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCellEditingStyle {

        }

And I think ,

  func remove(sender: UITapGestureRecognizer){
            let indexView = sender.view
            let index = indexView?.tag
            self.removeAddresses(position: index!)
        }

  func removeAddresses(position: Int){
     tableView.beginUpdates()
     yourDataSourceArray.removeObject(at: position)
     table.deleteRows(at: [indexPathCreated] , with: .automatic)
     table.endUpdates()
   }


问:
What i should use to convert specific json format
I have problem that I want to solve. I'm using EJB3.1 to create my webservice. I'm having trouble composing a Java bean structure that will return this format in json

```<code>{
    "test": {
        "v1": "1",
        "v2": "2"
    }
}
</code>```

I used a Map to create it but it gave me this format:

```<code>{
"test": {
    "entry": [
      {
        "key": "v1",
        "value": "1"
      },
      {
        "key": "v2",
        "value": "2"
      }
    ]
  }
}
</code>```

The class looks like this:

```<code>@XmlRootElement
public class TestClass {

    @XmlElement(name="test")
    private Map<String, String> map;

}
</code>```

And this my WS method

```<code>@POST
@Path("new")
@Produces("application/json")
public TestClass startNew () {
    TestClass testClass = new TestClass();
    Map<String, String> map = new HashMap<>();
    map.put("v1", "1");
    map.put("v2", "2");
    testClass.setMap(map);
    return testClass;
}
</code>```

Should I use something else instead of a map or how do I handle this format?

答:
It may be easier for you to use the JSON Processing API (and part of Java EE 7):</p>

```<code>@POST
@Path("new")
@Produces("application/json")
public JsonObject startNew() {
    JsonBuilderFactory factory = Json.createBuilderFactory(Collections.emptyMap());
    return factory.createObjectBuilder().
            add("test", factory.createObjectBuilder().
                    add("v1", 1).
                    add("v2", 2).
                    build()
            ).
            build();
}
</code>```

Body:
I have problem that I want to solve. I'm using EJB3.1 to create my webservice. I'm having trouble composing a Java bean structure that will return this format in json

{
    "test": {
        "v1": "1",
        "v2": "2"
    }
}

I used a Map to create it but it gave me this format:

{
"test": {
    "entry": [
      {
        "key": "v1",
        "value": "1"
      },
      {
        "key": "v2",
        "value": "2"
      }
    ]
  }
}

The class looks like this:

@XmlRootElement
public class TestClass {

    @XmlElement(name="test")
    private Map<String, String> map;

}

And this my WS method

@POST
@Path("new")
@Produces("application/json")
public TestClass startNew () {
    TestClass testClass = new TestClass();
    Map<String, String> map = new HashMap<>();
    map.put("v1", "1");
    map.put("v2", "2");
    testClass.setMap(map);
    return testClass;
}

Should I use something else instead of a map or how do I handle this format?

Body:
It may be easier for you to use the JSON Processing API (and part of Java EE 7):

@POST
@Path("new")
@Produces("application/json")
public JsonObject startNew() {
    JsonBuilderFactory factory = Json.createBuilderFactory(Collections.emptyMap());
    return factory.createObjectBuilder().
            add("test", factory.createObjectBuilder().
                    add("v1", 1).
                    add("v2", 2).
                    build()
            ).
            build();
}


问:
Gettting Error 500 when trying Get from website using lwp::useragent
Someone help me with this using lwp::Useragent please

```<code>my $mech = WWW::Mechanize->new(autocheck => 0);
$mech->get($url);
my $content=$mech->content;
</code>```

but getting Error 500 when trying to get https://camelcamelcamel.com/

答:
It seems that the site blocks requests from "bad" (undesired) user agents.  You may make WWW::Mechanize (LWP::UserAgent) present itself as another user agent using agent parameter for new or by calling agent method.  Full IE8 identification string fixed the problem.

I have tested it using Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1.

[As listed by "User Agent Switcher" plugin for Firefox]

Short list of user agents (xml file)

Long list of user agents

WARNING

The site(s) may use or choose to use other means to block unwanted requests.

Body:
Someone help me with this using lwp::Useragent please

my $mech = WWW::Mechanize->new(autocheck => 0);
$mech->get($url);
my $content=$mech->content;

but getting Error 500 when trying to get https://camelcamelcamel.com/


答:
Since you're multithreading your update to your textbox, you need to be aware that your worker thread can't update the textbox because the textbox wasn't created on the worker thread.

To update the textbox in a thread safe way, I'd recommend the easiest way of invoking:

```<code>TextBox2.Invoke((MethodInvoker)(() => { TextBox2.Text = response_message });
</code>```

Title: c#,Textbox not working while taking web respose

Body:
Since you're multithreading your update to your textbox, you need to be aware that your worker thread can't update the textbox because the textbox wasn't created on the worker thread.

To update the textbox in a thread safe way, I'd recommend the easiest way of invoking:

TextBox2.Invoke((MethodInvoker)(() => { TextBox2.Text = response_message });


问:
Microsoft.ace.oledb.12.0 provider is not registered while connecting to access database to my website
I'm using windows 64 and I got Microsoft office 2016 64 bit and when i try to connect to the database I get the error:

the microsoft.ace.oledb.12.0 provider is not registered on the local machine

I also tried to enable 32-bit application in the internet information services (ISS) Application's pool just in case, but that didn't work either.

答:
did u try to change the solution platform as described [here]
(https://www.codeproject.com/Tips/417397/OLEDB-Provider-is-Not-Registered-on-the-Local-Mach "codeproj")?</p>


问:
iOS - Iteration in some folders
I need to get some files in definite folders. For this purpose I use this answer and it works fine. However, my folder structure is like:

```<code>Documents/
  idOfFolder1/
    images/
      image1.jpg
      image2.png
    sounds/
      sound1.mp3
    files/
      file1.pdf
  idOfFolder2/
    images/
      ...
</code>```

I need to iterate through all folders having a specific id and get images. Since the answer written iterates through all folders it takes much more time than normal (we have many files). To optimize process, I want to skip "sounds" and "files" folders. Is there a way to handle this?

Thank you!

答: That's right. The upstairs is right, and the index will be named directly based on the picture so that CPU can find the files accurately</p>

Title: iOS - Iteration in some folders

Body:
I need to get some files in definite folders. For this purpose I use this answer and it works fine. However, my folder structure is like:

Documents/
  idOfFolder1/
    images/
      image1.jpg
      image2.png
    sounds/
      sound1.mp3
    files/
      file1.pdf
  idOfFolder2/
    images/
      ...

I need to iterate through all folders having a specific id and get images. Since the answer written iterates through all folders it takes much more time than normal (we have many files). To optimize process, I want to skip "sounds" and "files" folders. Is there a way to handle this?

Thank you!


问:
How to refer to a cell outside of cellForRowAtIndexPath
I am trying to update a label in a cell outside of

```<code>override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
</code>```

by using

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell
</code>```

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

```<code>let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell
</code>```

that does not return an error, but the label cell.time.text is not updated.

答:
Use this:

```<code>tableView.cellForRow(at: IndexPath(row: row, section: section)) as! CustomCell
</code>```

If your cell has properties like

```<code>@IBOutlet label: UILabel!
</code>```

you can use this:

```<code>tableView.cellForRow(at: IndexPath(row: row, section: section)) as! CustomCell).label.text = "Test123" // smth like this
</code>```

Hope it helps

Body:
I am trying to update a label in a cell outside of

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell

by using

let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! Cell

in another function. However, I keep getting errors. Therefore, I tried to refer to the cell by using let cell = Cell(), but I get the error unexpectedly found nil. Lastly, I tried

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! Cell

that does not return an error, but the label cell.time.text is not updated.

Body:
Use this:

tableView.cellForRow(at: IndexPath(row: row, section: section)) as! CustomCell

If your cell has properties like

@IBOutlet label: UILabel!

you can use this:

tableView.cellForRow(at: IndexPath(row: row, section: section)) as! CustomCell).label.text = "Test123" // smth like this

Hope it helps


问:
Hiding Table Rows with jQuery
I'm trying to hide a bunch of table rows using javascript.
I think i've got most of the code correct, I just don't know why it isn't running the hide.

Any help is appreciated.

The code is:

```<code><script type="text/javascript">
    function hideButton()
    {
    $("#showHideButton").on("click", function (e) {
    var button = e.target;
    var node = $(button).parent().parent().next();

    while (!node.hasClass("service-header")) {
        if ($(node).is(":visible")) {
            $(node).hide();
        } else {
            $(node).show();
        }
        node = node.next();
    }
    })}
    </script>
</code>```

The HTML is:

```<code>for (loopHere)
{
    echo "<tr class='service-header'><th>InfoHere</th><th>" . InfoHere . "<button style='float:right' type='button' id='showHideButton' class='btn btn-default' onclick='hideButton()'><span class='dashicons dashicons-arrow-down-alt2'></span></button></th></tr>";
    echo "<tr><td>More Stuff</td></tr>";
    echo "<tr><td>More Stuff</td></tr>";
}
loop
</code>```

I've got no idea why it won't hide the rows on the click, I have tested it on a table with multiple rows that have the class service-header, but haven't had any luck.

答:
Here are some suggestion to make this work.

hideButton() and $("#showHideButton").on("click"...... both are doing the same thing (initializing click function). So i suggest to remove function hideButton(){ } from your code.

Now your id "#showHideButton" must be unique in a single web page.

If it still not works then do check your HTML structure.

Try after these changes. Hope this helps.

Title: Hiding Table Rows with jQuery

Body:
I'm trying to hide a bunch of table rows using javascript.
I think i've got most of the code correct, I just don't know why it isn't running the hide.

Any help is appreciated.

The code is:

The HTML is:

for (loopHere)
{
    echo "
InfoHere	" . InfoHere . "<button style='float:right' type='button' id='showHideButton' class='btn btn-default' onclick='hideButton()'></button>
";
    echo "
More Stuff
";
    echo "
More Stuff
";
}
loop

I've got no idea why it won't hide the rows on the click, I have tested it on a table with multiple rows that have the class service-header, but haven't had any luck.


问:
Primary Key - Random Bytes Good or Bad
Ive read a few articles on this subject and just wanted to get some clarificiation regarding using random primary keys instead of auto increment. I am building an application and instead of using auto-increment primary keys, I am using the following code to generate a random primary key that includes both numbers and letters:

```<code>$bytes = random_bytes(8);
$bytes = bin2hex($bytes);
</code>```

The reason I would like to use random primary keys is to prevent url tampering. My application also has record level security but I wanted random primary key as a secondary measure. Also, I have this column set to unique as to prevent any rare collisions. If there is a collision i just throw on on screen error asking using to resubmit the form which generates another random key. So my questions are as follows:

My db is innodb and my application is all relationship based (PK/FK relationships). Does having a random key (using the code above) effect search performance and/or indexing speed as compared to auto increment key?

Are there any reasons I should not be using a random key (as the primary / indexed key) other than possible collision which I have protected against using duplicate error handling?

Before I finalize this application, are there any other suggestions or best practices I should be using as it relates to primary key other than how I am doing it above?

Thank you. Again, i know there are other articles out there but many of them are outdated (prior to php 7 random bytes) so I thought id get a fresh take on whether or not random primary keys are considered best practice (why or why not). Thanks.

答:
Bad -- very bad, in fact. Random primary keys play havoc with MySQL's page cache, which will make performance poor under load. It also means some SQL features will be unavailable to you, like multiple-row INSERT.

If you want to protect the ID in a URL from tampering, consider including a keyed hash (e.g, HMAC) of the identifier in the URL.

Title: Primary Key - Random Bytes Good or Bad

Body:
Ive read a few articles on this subject and just wanted to get some clarificiation regarding using random primary keys instead of auto increment. I am building an application and instead of using auto-increment primary keys, I am using the following code to generate a random primary key that includes both numbers and letters:

$bytes = random_bytes(8);
$bytes = bin2hex($bytes);

The reason I would like to use random primary keys is to prevent url tampering. My application also has record level security but I wanted random primary key as a secondary measure. Also, I have this column set to unique as to prevent any rare collisions. If there is a collision i just throw on on screen error asking using to resubmit the form which generates another random key. So my questions are as follows:

My db is innodb and my application is all relationship based (PK/FK relationships). Does having a random key (using the code above) effect search performance and/or indexing speed as compared to auto increment key?

Are there any reasons I should not be using a random key (as the primary / indexed key) other than possible collision which I have protected against using duplicate error handling?

Before I finalize this application, are there any other suggestions or best practices I should be using as it relates to primary key other than how I am doing it above?

Thank you. Again, i know there are other articles out there but many of them are outdated (prior to php 7 random bytes) so I thought id get a fresh take on whether or not random primary keys are considered best practice (why or why not). Thanks.


问:
iOS Httpclient cannot connect: {System.Threading.Tasks.TaskCanceledException}
I'm building an app with Xamarin Forms. I have no issues with Android, but when I attempt to simulate or deploy the iOS app, my HttpClient can't seem to connect to the server. After the timeout expires, I get a TaskCanceledException.

The HttpClient is actually used in a separate project that is referenced by the iOS app, if that matters. Here's my usage:

```<code>string serviceUri = service + methodName;

            HttpRequestMessage request = new HttpRequestMessage(methodRequestType, serviceUri)
            {
                Content = new StringContent(content, Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await _client.SendAsync(request).ConfigureAwait(false);
            string returnString = await response.Content.ReadAsStringAsync();
            return returnString;
</code>```

I'm not using any waits or accessing .Result, as I've seen many people try that don't understand async operations.

I've seen older posts (circa 2013) where the wrong HttpClient is used. Is this still an issue in current releases? I've also tried changing the HttpClient implementation in the iOS project settings, to no avail.

Thanks in advance!

答:
The issue was an invalid Deployment Target - It was set to "80" instead of "8.0

In come cases, the build server does not communicate this invalidity back to your machine - hence why it took so long to notice it!

Body:
I'm building an app with Xamarin Forms. I have no issues with Android, but when I attempt to simulate or deploy the iOS app, my HttpClient can't seem to connect to the server. After the timeout expires, I get a TaskCanceledException.

The HttpClient is actually used in a separate project that is referenced by the iOS app, if that matters. Here's my usage:

string serviceUri = service + methodName;

            HttpRequestMessage request = new HttpRequestMessage(methodRequestType, serviceUri)
            {
                Content = new StringContent(content, Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await _client.SendAsync(request).ConfigureAwait(false);
            string returnString = await response.Content.ReadAsStringAsync();
            return returnString;

I'm not using any waits or accessing .Result, as I've seen many people try that don't understand async operations.

I've seen older posts (circa 2013) where the wrong HttpClient is used. Is this still an issue in current releases? I've also tried changing the HttpClient implementation in the iOS project settings, to no avail.

Thanks in advance!


问:
Div with text wont stay centered
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row" id="locations">

  <div class="locationName">
    City
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="1.jpg">
    </div>
  </div>

  <div class="col-lg-4 col-sm-6">
    <div class="thumbnail">
      <img src="2.jpg">
    </div>
  </div>
</div></code>```

Obviously the code is doubled inside the "row" div.

答:
Looks like there is a conflict with the bootstrap you are using. Try moving the title (City) before the div with class row.</p>

```<code><div class="locationName">
    City
</div>

<div class="row" id="locations">
    <div class="col-lg-4 col-sm-6">
        <div class="thumbnail">
            <img src="2.jpg">
        </div>
    </div>

    <div class="col-lg-4 col-sm-6">
        <div class="thumbnail">
            <img src="1.jpg">
        </div>
    </div>

    <div class="col-lg-4 col-sm-6">
        <div class="thumbnail">
            <img src="2.jpg">
        </div>
    </div>
</div>
</code>```

Title: Div with text wont stay centered

Body:
I'm creating a simple image gallery. Above the images I name the place where the pictures were taken, but the second and every another row has issues - div with the name is being pushed to the right instead of staying centered. Here is how it looks: http://prntscr.com/fg10u4

@import url(https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css);
.locationName {
  text-align: center;
  padding: 0px 0px 20px 20px;
}

    City

Obviously the code is doubled inside the "row" div.

Body:
Looks like there is a conflict with the bootstrap you are using. Try moving the title (City) before the div with class row.

<div class="locationName">
    City
</div>

<div class="row" id="locations">
    <div class="col-lg-4 col-sm-6">
        <div class="thumbnail">
            <img src="2.jpg">
        </div>
    </div>

    <div class="col-lg-4 col-sm-6">
        <div class="thumbnail">
            <img src="1.jpg">
        </div>
    </div>

    <div class="col-lg-4 col-sm-6">
        <div class="thumbnail">
            <img src="2.jpg">
        </div>
    </div>
</div>


问:
Priority of execution of runs in angularjs
Suppose there are two run function in app:

angular.module('exmple',[])
.run(function(){
    console.log('second');
})
.run(function(){
    console.log('first');
});```

Is there any way to execute runs based on priority?

答:
If code is in a service, it will run in order of dependency:

```<code>angular.module('exmple',[])
.run(function(firstService){
    console.log('second');
})
.service("firstService", function(){
    console.log('first');
});
</code>```

By having the run block define firstService as a dependency, the dependency injector will initialize that service before running the code of the run block.

The Demo

angular.module('app',[])
.run(function(firstService){
    console.log('second');
})
.service("firstService", function(){
    console.log('first');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app">
</div></code>```

Body:
Suppose there are two run function in app:

angular.module('exmple',[])
.run(function(){
    console.log('second');
})
.run(function(){
    console.log('first');
});

Is there any way to execute runs based on priority?

Body:
If code is in a service, it will run in order of dependency:

angular.module('exmple',[])
.run(function(firstService){
    console.log('second');
})
.service("firstService", function(){
    console.log('first');
});

By having the run block define firstService as a dependency, the dependency injector will initialize that service before running the code of the run block.

The Demo

angular.module('app',[])
.run(function(firstService){
    console.log('second');
})
.service("firstService", function(){
    console.log('first');
});

<script src="//unpkg.com/angular/angular.js"></script>
<div ng-app="app">
</div>


问:
How to ask choices from user in multi line?
I'm asking user to select from multiple options as follows

```<code>var reportData = {
    "Report A Traffic Violation": {
        intent: 'report_a_traffic_violation'
    },
    "Report a Lost Property": {
        intent: 'report_a_traffic_violation'
    },
    "Describe Incident": {
        intent: '/describeIncident'
    }
};

builder.Prompts.choice(session, "please select from options", reportData);
</code>```

But the options shows to the user in single line. How can I show the options to the user using multiple lines as follows?

option one

option two

option three

答:
For js : Although '\n' is the universal newline characters.
For c# SDK : Environment.NewLine.</p>

Body:
I'm asking user to select from multiple options as follows

var reportData = {
    "Report A Traffic Violation": {
        intent: 'report_a_traffic_violation'
    },
    "Report a Lost Property": {
        intent: 'report_a_traffic_violation'
    },
    "Describe Incident": {
        intent: '/describeIncident'
    }
};

builder.Prompts.choice(session, "please select from options", reportData);

But the options shows to the user in single line. How can I show the options to the user using multiple lines as follows?

option one

option two

option three


Title: IF function and nested function

Body:
Please help with this formula

=if(C27>=16000,16M,if(C27,=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))

Body:
You have a type-o near 16999.

Try this:

=if(C27>=16000,16M,if(C27>=16999,16M,if(c27>=17000,17M,if(C27<=17999,17M,if(C27>=18000,18M,if(C27<=18999,18M,if(C27>=19000,19M)))))))


问:
How to set the size of a newly created TextField without a reference for it
My code for creating a Textfield using new TextFieldwas used as a parameter for a method like this

```<code>x.getChildren.addAll(new TextField());
</code>```

My program has a button that creates TextField.

It's a loop to create a number TextFields until the condition is satisfied.

   My own code looks like this:

```<code>sub.setOnAction(e-> {
    v.getChildren().clear(); //just clearing things
    v1.getChildren().clear(); //just clearing things

    makeStr(Integer.valueOf(numOpt.getText()));
    for(int i = 0; i < list.size(); i++){
        v.getChildren().addAll(new Label(list.get(i).toString()));
        v1.getChildren().addAll(new TextField());
    }
    list.clear();
});
</code>```

However I cant just change its size like this.

```<code>v1.getChildren().addAll(new TextField().setPrefWidth(800));
</code>```

Maybe a better code can fix the problem!

答:
As long as you only need to do this in one or 2 locations you do not gain much by writing some code that allows you to do this in a single expression. Simply using a local variable to store the field would be the best way to do this in such a scenario.

```<code>for(Object element : list){
    v.getChildren().add(new Label(element.toString()));

    TextField textField = new TextField();
    textField.setPrefWidth(800);
    v1.getChildren().add(textField);
}
</code>```

Using a method to create & init the field

If you need to create a TextField and initialize the prefWidth property at the same time in multiple locations in your code, creating a method returning the initialized field would be beneficial.

```<code>public static TextField createTextField(double prefWidth) {
    TextField textField = new TextField();
    textField.setPrefWidth(prefWidth);
    return textField;
}
</code>```

which allows you write

```<code>v1.getChildren().add(createTextField(800));
</code>```

instead of

```<code>TextField textField = new TextField();
textField.setPrefWidth(800);
v1.getChildren().add(textField);
</code>```

To be more flexible when initializing you could also create a builder for TextFields.

Using a CSS stylesheet

CSS allows you to set properties of multiple nodes at once. You simply need a way to identify the correct nodes to apply a rule to. In this case the rule is applied to all children of v1 so by adding a style class to this node you can identify the target nodes:

java

```<code>// after creating v1/the scene
v1.getStyleClass().add("v1");
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
</code>```

```<code>for(int i = 0; i < list.size(); i++){
    v.getChildren().addAll(new Label(list.get(i).toString()));
    v1.getChildren().addAll(new TextField());
}
</code>```

style.css

v1>* {
    -fx-pref-width: 800;
}
```

Body:
My code for creating a Textfield using new TextFieldwas used as a parameter for a method like this

x.getChildren.addAll(new TextField());

My program has a button that creates TextField.

It's a loop to create a number TextFields until the condition is satisfied.

   My own code looks like this:

sub.setOnAction(e-> {
    v.getChildren().clear(); //just clearing things
    v1.getChildren().clear(); //just clearing things

    makeStr(Integer.valueOf(numOpt.getText()));
    for(int i = 0; i < list.size(); i++){
        v.getChildren().addAll(new Label(list.get(i).toString()));
        v1.getChildren().addAll(new TextField());
    }
    list.clear();
});

However I cant just change its size like this.

v1.getChildren().addAll(new TextField().setPrefWidth(800));

Maybe a better code can fix the problem!

Body:
As long as you only need to do this in one or 2 locations you do not gain much by writing some code that allows you to do this in a single expression. Simply using a local variable to store the field would be the best way to do this in such a scenario.

for(Object element : list){
    v.getChildren().add(new Label(element.toString()));

    TextField textField = new TextField();
    textField.setPrefWidth(800);
    v1.getChildren().add(textField);
}

Using a method to create & init the field

If you need to create a TextField and initialize the prefWidth property at the same time in multiple locations in your code, creating a method returning the initialized field would be beneficial.

public static TextField createTextField(double prefWidth) {
    TextField textField = new TextField();
    textField.setPrefWidth(prefWidth);
    return textField;
}

which allows you write

v1.getChildren().add(createTextField(800));

instead of

TextField textField = new TextField();
textField.setPrefWidth(800);
v1.getChildren().add(textField);

To be more flexible when initializing you could also create a builder for TextFields.

Using a CSS stylesheet

CSS allows you to set properties of multiple nodes at once. You simply need a way to identify the correct nodes to apply a rule to. In this case the rule is applied to all children of v1 so by adding a style class to this node you can identify the target nodes:

java

// after creating v1/the scene
v1.getStyleClass().add("v1");
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

for(int i = 0; i < list.size(); i++){
    v.getChildren().addAll(new Label(list.get(i).toString()));
    v1.getChildren().addAll(new TextField());
}

style.css

v1>* {
    -fx-pref-width: 800;
}


问:
When I change the page orientation it come at the beginning of page
I am using barteksc-AndroidPdfViewer. I am using this code

```<code>package com.epubtest.hxfy.epubtest;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;

public class PDFReaderActivity2 extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener, OnErrorListener, OnPageScrollListener {

    private PDFView pdfview;
    private SharedPreferences pdfReader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdfreader2);
        pdfReader = this.getSharedPreferences("PDFReader", Context.MODE_PRIVATE);

        pdfview = (PDFView) findViewById(R.id.pdfView);
        pdfview.fromAsset("test4.pdf")
                .defaultPage(pdfReader.getInt("pages",0))
                .onPageChange(this)
                .swipeHorizontal(false)
                .enableAnnotationRendering(true)
                .scrollHandle(null)
                .onLoad(this)
                .onDraw(this)
                .enableSwipe(true)
                .onError(this)
                .enableDoubletap(true)
                .onPageScroll(this)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        SharedPreferences.Editor edit = pdfReader.edit();
        edit.putInt("pages",page);
        edit.commit();
    }

    @Override
    public void loadComplete(int nbPages) {

    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }

    @Override
    public void onError(Throwable t) {

    }

    @Override
    public void onPageScrolled(int page, float positionOffset) {
    }
}
</code>```

to change the orientation of the page. But if I have to assume if the portrait mode and page number 15 in change page orientation of the page when we started the landscape.

SharedPreferences is not working. It can't keep record last page where we were. Please help me in this regard, Please help me about this.

答:
Don't use SharePreferences for this. When you change screen orientation, system recalls onCreate() method again and it redraws your views. For solution of this problem, you have 2 ways. First one is forcing to save state in manifest file.

```<code><activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>
</code>```

If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.

Another way is recommended by google developers which is better way for handling this problems in orientation changes. You can get more information in thislink. It will be better for reading this article also. It is about lifecycle of activity.

If you want source example, i can share my source with you. Enjoy!

For handling orientation changes, add this few lines to your source.

```<code>    Configurator.onRender(new OnRenderListener() {
    @Override
    public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) {
        pdfView.fitToWidth(); // optionally pass page number
    }
});
</code>```

Body:
I am using barteksc-AndroidPdfViewer. I am using this code

package com.epubtest.hxfy.epubtest;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnDrawListener;
import com.github.barteksc.pdfviewer.listener.OnErrorListener;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageScrollListener;

public class PDFReaderActivity2 extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener, OnDrawListener, OnErrorListener, OnPageScrollListener {

    private PDFView pdfview;
    private SharedPreferences pdfReader;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdfreader2);
        pdfReader = this.getSharedPreferences("PDFReader", Context.MODE_PRIVATE);

        pdfview = (PDFView) findViewById(R.id.pdfView);
        pdfview.fromAsset("test4.pdf")
                .defaultPage(pdfReader.getInt("pages",0))
                .onPageChange(this)
                .swipeHorizontal(false)
                .enableAnnotationRendering(true)
                .scrollHandle(null)
                .onLoad(this)
                .onDraw(this)
                .enableSwipe(true)
                .onError(this)
                .enableDoubletap(true)
                .onPageScroll(this)
                .load();
    }

    @Override
    public void onPageChanged(int page, int pageCount) {
        SharedPreferences.Editor edit = pdfReader.edit();
        edit.putInt("pages",page);
        edit.commit();
    }

    @Override
    public void loadComplete(int nbPages) {

    }

    @Override
    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {

    }

    @Override
    public void onError(Throwable t) {

    }

    @Override
    public void onPageScrolled(int page, float positionOffset) {
    }
}

to change the orientation of the page. But if I have to assume if the portrait mode and page number 15 in change page orientation of the page when we started the landscape.

SharedPreferences is not working. It can't keep record last page where we were. Please help me in this regard, Please help me about this.

Body:
Don't use SharePreferences for this. When you change screen orientation, system recalls onCreate() method again and it redraws your views. For solution of this problem, you have 2 ways. First one is forcing to save state in manifest file.

<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>

If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.

Another way is recommended by google developers which is better way for handling this problems in orientation changes. You can get more information in thislink. It will be better for reading this article also. It is about lifecycle of activity.

If you want source example, i can share my source with you. Enjoy!

For handling orientation changes, add this few lines to your source.

    Configurator.onRender(new OnRenderListener() {
    @Override
    public void onInitiallyRendered(int pages, float pageWidth, float pageHeight) {
        pdfView.fitToWidth(); // optionally pass page number
    }
});


问:
method in class can not be applied to given type
I made a class called that creates a constructer and a method.

```<code>public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}
</code>```

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

```<code>public class CarTester
{
public static void main (String[] args){

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}
</code>```

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

答:
Method

```<code>public void accelerate(double speed){
speed=speed+1.0;
}
</code>```

Should not be expecting to be passed a "speed"  parameter. It should look simply just like that:

```<code>public void accelerate(){
speed=speed+1.0;
}
</code>```

Also you should call this method on the Object (p1 in this case).

```<code>p1.accelerate();
</code>```

Not

```<code>Car.accelerate();
</code>```

Hope it will help you to solve this problem :)

Body:
I made a class called that creates a constructer and a method.

public class Car
{
private double speed;
private String make;
private int year;

public Car(int year, String make, double speed) {
this.year = year;
this.make = make;
this.speed = speed;
}

public String getMake(){
  return make;
}
public double getSpeed(){
  return speed;
}
public int getYear(){
     return year;
}

  public void accelerate (double speed)
{
        speed = speed + 1.00;
}

}

the only problem i am having here is that when I go to my driver class to try and run it, this is the error I'm receiving

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

Car p1 = new Car(2010, "toyota", 4.50);
Car.accelerate();
Car.accelerate();

}
}

"error: method accelerate in class Car cannot be applied to given types"

why is that so? because it says "required: double" but the "speed" variable is a double?

Body:
Method

public void accelerate(double speed){
speed=speed+1.0;
}

Should not be expecting to be passed a "speed"  parameter. It should look simply just like that:

public void accelerate(){
speed=speed+1.0;
}

Also you should call this method on the Object (p1 in this case).

p1.accelerate();

Not

Car.accelerate();

Hope it will help you to solve this problem :)


问:
Fetch the Next Record to the percentile value in a Pandas Column
I have a following data Frame

```<code>Year    Sector  Number   Count
2015    AA      173      277
2015    AA      172      278
2015    AA      173      234
2015    BB      173      234
2015    BB      171      273
2015    BB      173      272
2015    CC      172      272
2015    CC      172      234
2015    CC      173      234
2015    CC      173      345
2016    AA      173      277
2016    AA      173      277
2016    BB      173      277
2016    BB      173      277
2016    CC      173      277
2016    CC      173      272
2016    CC      170      273
2016    CC      170      275
</code>```

I need to calculcate the 90th percentile value of 'Count' for each group of ['Year','Sector','Number'] and return the next closest highest record in the group.

For example:

```<code>In the group
2015    CC      172      272
2015    CC      172      234
2015    CC      173      234
2015    CC      173      345
</code>```

90th percentile value is 323.1 using np.percentile() function. I would want to return value of 345 which is the next highest in the group. Any help here ?

答:
You can implement it as a 5 steps process:

Group by

Finding 90% percentile

Finding all the values above

Keep the id of the minimal

Retrieve all necessary ids

assume your dataframe named df:

```<code>ids = [data[data.Count>=np.percentile(data.Count,90)].Count.idxmin()
       for group,data in df.groupby('Sector')]

df.loc[ids]
</code>```

I'll break it down into steps:

1 - iterate over groups by Sector:

```<code>for group,data in df.groupby('Sector')
</code>```

2 - find the percentile:

```<code>perc = np.percentile(data.Count,90)
</code>```

3 - filter the values:

```<code>subdf = data[data.Count>=np.percentile(data.Count,90)]
</code>```

4 -  find the id of the minimal value:

```<code>subdf.Count.idmin()
</code>```

5 - return the rows with minimal id:

```<code>df.loc[ids]
</code>```

Body:
I have a following data Frame

Year    Sector  Number   Count
2015    AA      173      277
2015    AA      172      278
2015    AA      173      234
2015    BB      173      234
2015    BB      171      273
2015    BB      173      272
2015    CC      172      272
2015    CC      172      234
2015    CC      173      234
2015    CC      173      345
2016    AA      173      277
2016    AA      173      277
2016    BB      173      277
2016    BB      173      277
2016    CC      173      277
2016    CC      173      272
2016    CC      170      273
2016    CC      170      275

I need to calculcate the 90th percentile value of 'Count' for each group of ['Year','Sector','Number'] and return the next closest highest record in the group.

For example:

In the group
2015    CC      172      272
2015    CC      172      234
2015    CC      173      234
2015    CC      173      345

90th percentile value is 323.1 using np.percentile() function. I would want to return value of 345 which is the next highest in the group. Any help here ?

Body:
You can implement it as a 5 steps process:

Group by

Finding 90% percentile

Finding all the values above

Keep the id of the minimal

Retrieve all necessary ids

assume your dataframe named df:

ids = [data[data.Count>=np.percentile(data.Count,90)].Count.idxmin()
       for group,data in df.groupby('Sector')]

df.loc[ids]

I'll break it down into steps:

1 - iterate over groups by Sector:

for group,data in df.groupby('Sector')

2 - find the percentile:

perc = np.percentile(data.Count,90)

3 - filter the values:

subdf = data[data.Count>=np.percentile(data.Count,90)]

4 -  find the id of the minimal value:

subdf.Count.idmin()

5 - return the rows with minimal id:

df.loc[ids]


问:
How to write the correct sum function?
I want to find the total amount of profit and the average in the sales table of each person who sells it. How to use the sum and average functions correctly?</p>

```<code>public function index()
{
  $sales_data = Auth::user()->sales()->paginate(30);
  $sum = $sales_data['sales']->sum('profit');
  $average = $sales_data['sales']->average('profit');
  $amount = $sales_data->total();
  return view('sales_page.index', ['user' => Auth::user()], compact('sales_data', 'amount', 'sum', 'average'));
}
</code>```

答:
Run collection function on collection object.

use collect() function to wrap your $sales_data and use count() instead of total().

```<code>public function index()
{
  $sales_data = Auth::user()->sales()->paginate(30);
  $sum = collect($sales_data['sales'])->sum('profit');
  $average = collect($sales_data['sales'])->average('profit');
  $amount = collect($sales_data)->count();
  return view('sales_page.index', ['user' => Auth::user()],compact('sales_data', 'amount', 'sum', 'average'));
}
</code>```

Title: How to write the correct sum function?

Body:
I want to find the total amount of profit and the average in the sales table of each person who sells it. How to use the sum and average functions correctly?

public function index()
{
  $sales_data = Auth::user()->sales()->paginate(30);
  $sum = $sales_data['sales']->sum('profit');
  $average = $sales_data['sales']->average('profit');
  $amount = $sales_data->total();
  return view('sales_page.index', ['user' => Auth::user()], compact('sales_data', 'amount', 'sum', 'average'));
}

Body:
Run collection function on collection object.

use collect() function to wrap your $sales_data and use count() instead of total().

public function index()
{
  $sales_data = Auth::user()->sales()->paginate(30);
  $sum = collect($sales_data['sales'])->sum('profit');
  $average = collect($sales_data['sales'])->average('profit');
  $amount = collect($sales_data)->count();
  return view('sales_page.index', ['user' => Auth::user()],compact('sales_data', 'amount', 'sum', 'average'));
}