问:
MySQL Pivot table, get rows with max created_at date
I have a pivot table with the following structure:

```<code>property_id   user_id   role       created_at
1             23        Manager    2019-05-20 00:00:00
1             45        Resident   2018-03-12 00:00:00
1             67        Manager    2020-05-19 00:00:00
</code>```

In the above example, user 67 is the current Manager for the Property. User 23 was the prior Manager.

How do I extract all rows of current roles and users for each property?

答:
With NOT EXISTS:

```<code>select t.* from tablename t
where not exists (
  select 1 from tablename
  where property_id = t.property_id and role = t.role and created_at > t.created_at
)
</code>```

Or with a correlated subquery:

```<code>select t.* from tablename t
where t.created_at = (
  select max(created_at) from tablename
  where property_id = t.property_id and role = t.role
)
</code>```

For MySql 8.0+ you can use ROW_NUMBER() window function:

```<code>select t.property_id, t.user_id, t.role, t.created_at
from  (
  select *, row_number() over (partition by property_id, role order by created_at desc) rn
  from tablename
) t
where t.rn = 1
</code>```

Body:
I have a pivot table with the following structure:

property_id   user_id   role       created_at
1             23        Manager    2019-05-20 00:00:00
1             45        Resident   2018-03-12 00:00:00
1             67        Manager    2020-05-19 00:00:00

In the above example, user 67 is the current Manager for the Property. User 23 was the prior Manager.

How do I extract all rows of current roles and users for each property?

Body:
With NOT EXISTS:

select t.* from tablename t
where not exists (
  select 1 from tablename
  where property_id = t.property_id and role = t.role and created_at > t.created_at
)

Or with a correlated subquery:

select t.* from tablename t
where t.created_at = (
  select max(created_at) from tablename
  where property_id = t.property_id and role = t.role
)

For MySql 8.0+ you can use ROW_NUMBER() window function:

select t.property_id, t.user_id, t.role, t.created_at
from  (
  select *, row_number() over (partition by property_id, role order by created_at desc) rn
  from tablename
) t
where t.rn = 1


来源: stackexchange

问:
How to show Hexadecimal unique ID NFC Tag have in my android NFC application?
I already make a write tag application that working find, I store data text to labeled thing ( example : computer 1) in NFC tag. Both write and read working fine. But I need to read the Hexadecimal ID that every tag have when I read the information text I know the have unique Hexadecimal ID (Cause I see that one when I test it with google play application there). But I don't know how to do it. I'm really bad at coding, so please help me.

Here is the code :

```<code>public class MainActivity extends Activity {

    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[];
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low;

    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;

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

        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);
        tvNFCContent.addTextChangedListener(watch);

        handler = new Handler() ;

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }

        readFromIntent(getIntent());
    }

    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }

    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

     tvNFCContent.setText("NFC Content: " + text);
     TimeBuff += MillisecondTime;
     handler.removeCallbacks(runnable);

    }

    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }

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

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();

            StartTime = SystemClock.uptimeMillis();
            handler.postDelayed(runnable, 0);

            NdefMessage[] messages = getNdefMessage(intent);
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] payload = messages[0].getRecords()[0].getPayload();
            userData = new String(payload);
        } else {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }

    }

    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;
            UpdateTime = TimeBuff + MillisecondTime;
            Seconds = (int) (UpdateTime / 1000);
            Minutes = Seconds / 60;
            Seconds = Seconds % 60;
            MilliSeconds = (int) (UpdateTime % 1000);
            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);

    }

    TextWatcher watch = new TextWatcher(){

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence s, int a, int b, int c) {
            // TODO Auto-generated method stub

        }
    };
}

</code>```

I'm sorry I upload the whole code, I just want to make it easy fpr anyone that would like to help me.

答:
Finally I can make it. Thanks for everyone that helped me. Here is the full code I share it with you.</p>

```<code>package com.nfcreadfull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.List;

import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[];
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low, Uid;

    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;

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

        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);
        Uid = (TextView)findViewById(R.id.uid);

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};

    mAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mAdapter == null) {
        // Stop here, we definitely need NFC
        Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
        finish();
    }

    readFromIntent(getIntent());

    }

    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))

        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];

                }
            }
            buildTagViews(msgs);
        }

}

    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

     tvNFCContent.setText("NFC Content: " + text);

    }

    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }

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

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        Uid.setText(ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));

        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            NdefMessage[] messages = getNdefMessage(intent);
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] payload = messages[0].getRecords()[0].getPayload();
            userData = new String(payload);

        }else
        {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            // While with ForegroundDispatch the NDEF message has already been read
            // And passed to us in the intent and thus the time the App spends "read" the NFC card is Zero
            // We want to time time the read, so now we have been notified that a NDEF card is in range
            // Try and read from it

            // Get the Tag from the intent
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            long startTime = 0;
            long endTime = 0;

            try {
                // Create an NDEF tag object
                Ndef ndefTag = Ndef.get(tag);

                // This is the I/O operation to read the card and format the result to an NDEF message
                // Nothing is done with the result to not add any time to it, as we are timing this
                startTime = System.currentTimeMillis();
                ndefTag.connect();
                ndefTag.getNdefMessage();
                endTime = System.currentTimeMillis();
                ndefTag.close();
            } catch (Exception e) {
                Log.e("NFC", e.toString());
            }

            MillisecondTime = endTime - startTime;

            UpdateTime = MillisecondTime;

            Seconds = (int) (UpdateTime / 1000);

            Minutes = Seconds / 60;

            Seconds = Seconds % 60;

            MilliSeconds = (int) (UpdateTime % 1000);

            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + "."
                    + String.format("%03d", MilliSeconds));

            //Log.v("NFC", "Time to read in milliseconds is: " + (endTime - startTime));
          //Timer.setText("00:00:0.0"+(endTime - startTime));

        }

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndefDetected.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {}
        IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if(mAdapter!= null)
            mAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

    }

     private String getHex(byte[] bytes) {
         if (bytes == null) {
                return null;
            }
            char[] hexChars = new char[bytes.length * 2];
            final char[] hexArray = "0123456789abcdef".toCharArray();
            for (int j = 0; j < bytes.length; j++) {
                int v = bytes[j] & 0xFF;
                hexChars[j * 2] = hexArray[v >>> 4];
                hexChars[j * 2 + 1] = hexArray[v & 0x0F];
            }
            return new String(hexChars);
        }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private String ByteArrayToHexString(byte [] inarray) {

        Log.d("ByteArrayToHexString", inarray.toString());

        int i, j, in;
        String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        String out= "";

        for(j = 0 ; j < inarray.length ; ++j)
        {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }

        Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));

        return out;
    }

}

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I already make a write tag application that working find, I store data text to labeled thing ( example : computer 1) in NFC tag. Both write and read working fine. But I need to read the Hexadecimal ID that every tag have when I read the information text I know the have unique Hexadecimal ID (Cause I see that one when I test it with google play application there). But I don't know how to do it. I'm really bad at coding, so please help me.

Here is the code :

public class MainActivity extends Activity {

    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[];
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low;

    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    Handler handler;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;

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

        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);
        tvNFCContent.addTextChangedListener(watch);

        handler = new Handler() ;

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }

        readFromIntent(getIntent());
    }

    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))
        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }

    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

     tvNFCContent.setText("NFC Content: " + text);
     TimeBuff += MillisecondTime;
     handler.removeCallbacks(runnable);

    }

    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }

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

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            Toast.makeText(getApplicationContext(),"Ndefdiscovered",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();

            StartTime = SystemClock.uptimeMillis();
            handler.postDelayed(runnable, 0);

            NdefMessage[] messages = getNdefMessage(intent);
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] payload = messages[0].getRecords()[0].getPayload();
            userData = new String(payload);
        } else {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }

    }

    public Runnable runnable = new Runnable() {

        public void run() {

            MillisecondTime = SystemClock.uptimeMillis() - StartTime;
            UpdateTime = TimeBuff + MillisecondTime;
            Seconds = (int) (UpdateTime / 1000);
            Minutes = Seconds / 60;
            Seconds = Seconds % 60;
            MilliSeconds = (int) (UpdateTime % 1000);
            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + ":"
                    + String.format("%03d", MilliSeconds));

            handler.postDelayed(this, 0);
        }

    };

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPI, mFilter, null);

    }

    TextWatcher watch = new TextWatcher(){

        @Override
        public void afterTextChanged(Editable arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                int arg3) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onTextChanged(CharSequence s, int a, int b, int c) {
            // TODO Auto-generated method stub

        }
    };
}

I'm sorry I upload the whole code, I just want to make it easy fpr anyone that would like to help me.

Body:
Finally I can make it. Thanks for everyone that helped me. Here is the full code I share it with you.

package com.nfcreadfull;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.util.List;

import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    NfcAdapter mAdapter;
    Tag mTag;
    PendingIntent mPI;
    IntentFilter mFilter[];
    String userData,yo;

    boolean writeMode;
    Context context;
    TextView tvNFCContent, Timer,Low, Uid;

    Button start, pause, reset, lap ;
    long MillisecondTime, StartTime, TimeBuff, UpdateTime = 0L ;
    int Seconds, Minutes, MilliSeconds ;
    ListView listView ;
    String[] ListElements = new String[] {  };
    List<String> ListElementsArrayList ;
    ArrayAdapter<String> adapter ;

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

        tvNFCContent = (TextView) findViewById(R.id.data);
        Timer = (TextView)findViewById(R.id.timer);
        Uid = (TextView)findViewById(R.id.uid);

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPI = PendingIntent.getActivity(getApplicationContext(), 0,
                new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0 );

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);

        IntentFilter filter2 = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        mFilter = new IntentFilter[]{tagDetected,filter2};

    mAdapter = NfcAdapter.getDefaultAdapter(this);
    if (mAdapter == null) {
        // Stop here, we definitely need NFC
        Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
        finish();
    }

    readFromIntent(getIntent());

    }

    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action))

        {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];

                }
            }
            buildTagViews(msgs);
        }

}

    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {

            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);

        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

     tvNFCContent.setText("NFC Content: " + text);

    }

    NdefMessage[] getNdefMessage(Intent intent)
    {
        NdefMessage[] msgs = null;

        Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        if(rawMsgs != null)
        {
            msgs = new NdefMessage[rawMsgs.length];
            for(int i=0; i<rawMsgs.length; i++)
            {
                msgs[i] = (NdefMessage)rawMsgs[i];
            }
        }

        return msgs;
    }

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

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        Uid.setText(ByteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));

        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())){
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

        }

        super.onNewIntent(intent);

        if(intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED))
        {
            Toast.makeText(getApplicationContext(),"Smartcard detected",Toast.LENGTH_SHORT).show();

        }else if(intent.getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED))
        {
            mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            NdefMessage[] messages = getNdefMessage(intent);
            if(messages == null)
            {
                Toast.makeText(getApplicationContext(),"There Is No Data",Toast.LENGTH_SHORT).show();
                return;
            }
            byte[] payload = messages[0].getRecords()[0].getPayload();
            userData = new String(payload);

        }else
        {
            Toast.makeText(getApplicationContext(),"Undefined smartcard",Toast.LENGTH_SHORT).show();
        }

        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
            // While with ForegroundDispatch the NDEF message has already been read
            // And passed to us in the intent and thus the time the App spends "read" the NFC card is Zero
            // We want to time time the read, so now we have been notified that a NDEF card is in range
            // Try and read from it

            // Get the Tag from the intent
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            long startTime = 0;
            long endTime = 0;

            try {
                // Create an NDEF tag object
                Ndef ndefTag = Ndef.get(tag);

                // This is the I/O operation to read the card and format the result to an NDEF message
                // Nothing is done with the result to not add any time to it, as we are timing this
                startTime = System.currentTimeMillis();
                ndefTag.connect();
                ndefTag.getNdefMessage();
                endTime = System.currentTimeMillis();
                ndefTag.close();
            } catch (Exception e) {
                Log.e("NFC", e.toString());
            }

            MillisecondTime = endTime - startTime;

            UpdateTime = MillisecondTime;

            Seconds = (int) (UpdateTime / 1000);

            Minutes = Seconds / 60;

            Seconds = Seconds % 60;

            MilliSeconds = (int) (UpdateTime % 1000);

            Timer.setText("" + Minutes + ":"
                    + String.format("%02d", Seconds) + "."
                    + String.format("%03d", MilliSeconds));

            //Log.v("NFC", "Time to read in milliseconds is: " + (endTime - startTime));
          //Timer.setText("00:00:0.0"+(endTime - startTime));

        }

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        mAdapter.disableForegroundDispatch(this);

    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndefDetected.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {}
        IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter[] nfcIntentFilter = new IntentFilter[]{ndefDetected,techDetected,tagDetected};

        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        if(mAdapter!= null)
            mAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);

    }

     private String getHex(byte[] bytes) {
         if (bytes == null) {
                return null;
            }
            char[] hexChars = new char[bytes.length * 2];
            final char[] hexArray = "0123456789abcdef".toCharArray();
            for (int j = 0; j < bytes.length; j++) {
                int v = bytes[j] & 0xFF;
                hexChars[j * 2] = hexArray[v >>> 4];
                hexChars[j * 2 + 1] = hexArray[v & 0x0F];
            }
            return new String(hexChars);
        }

    private long getDec(byte[] bytes) {
        long result = 0;
        long factor = 1;
        for (int i = 0; i < bytes.length; ++i) {
            long value = bytes[i] & 0xffl;
            result += value * factor;
            factor *= 256l;
        }
        return result;
    }

    private String ByteArrayToHexString(byte [] inarray) {

        Log.d("ByteArrayToHexString", inarray.toString());

        int i, j, in;
        String [] hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
        String out= "";

        for(j = 0 ; j < inarray.length ; ++j)
        {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }

        Log.d("ByteArrayToHexString", String.format("%0" + (inarray.length * 2) + "X", new BigInteger(1,inarray)));

        return out;
    }

}


问:
Recursion sum numbers *with rule* - Recursion only
So the exercise is:

Using recursion only (no loops)

Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.

Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)

```<code>int[] a = {5,4,2,1,3};
</code>```

So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)

My attempt is:

```<code>public static boolean sumRule(int[] a , int num){
        if (num == 0){
            return true;
        } else {

    return sumRule(a,num,0,a.length);
        }
}

private static boolean sumRule(int[] a, int num, int low,int high){
    if(low >= high || low < 0){
        return false;
    }

    if (a[low] == -1){
        return false;
    }

    if(a[low] == num || num-a[low] == 0 ){
        return true;
    }

    int temp = a[low];
    a[low] = -1;

    return  sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;

}
</code>```

But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?

Thanks,

答:
Here is my implementation. It contains comments explaining what the different parts do.

public class RecurSum {
    /**
     * Determines whether 'sum' equals 'target'.
     *
     * @param arr         - its elements are summed
     * @param sum         - sum of some elements in 'arr'
     * @param target      - required value of 'sum'
     * @param index       - index in 'arr'
     * @param consecutive - number of consecutive indexes summed to ensure don't exceed 3
     * @param start       - starting element in 'arr' which is used for back-tracking
     *
     * @return "true" if 'sum' equals 'target'
     */
    private static boolean sumRule(int[] arr, int sum, int target, int index, int consecutive, int start) {
        if (sum == target) {
            return true;
        }
        else {
            if (index >= arr.length) {
                // if we have reached last element in 'arr' then back-track and start again
                if (start < arr.length) {
                    return sumRule(arr, 0, target, start + 1, 0, start + 1);
                }
                // we have reached last element in 'arr' and cannot back-track
                return false;
            }
            else {
                consecutive++;
                if (consecutive == 3) {
                    // skip 3rd consecutive element (because of the rule)
                    consecutive = 0;
                    return sumRule(arr, sum, target, index + 2, consecutive, start);
                }
                else {
                    if (sum + arr[index] > target) {
                        // recursive call but don't add current element of 'arr'
                        return sumRule(arr, sum, target, index + 1, 0, start);
                    }
                    // recursive call: add current element of 'arr' to 'sum' and proceed to next element
                    return sumRule(arr, sum + arr[index], target, index + 1, consecutive, start);
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{5, 4, 2, 1, 3};

        // initial call to recursive method with target = 11 (eleven)
        System.out.println(sumRule(arr, 0, 11, 0, 0, 0));

        // initial call to recursive method with target = 8
        System.out.println(sumRule(arr, 0, 8, 0, 0, 0));
    }
}
```

Body:
So the exercise is:

Using recursion only (no loops)

Find if there is sub ground of numbers that are equal to the given number in an array and follow the rule.

Let's say I have this array, I give the function a number for sum and it must adhere to this rule:
you cannot repeat the same number, and you can't sum 3 numbers in a row (can't do i+1 and i+2)

int[] a = {5,4,2,1,3};

So in this case:
num 8 = true (4+3+1) ( 5+3)
num 11 = false (4+5+2 are 3 but are three in a row) (5+2+1+3 also three in a row)

My attempt is:

public static boolean sumRule(int[] a , int num){
        if (num == 0){
            return true;
        } else {

    return sumRule(a,num,0,a.length);
        }
}

private static boolean sumRule(int[] a, int num, int low,int high){
    if(low >= high || low < 0){
        return false;
    }

    if (a[low] == -1){
        return false;
    }

    if(a[low] == num || num-a[low] == 0 ){
        return true;
    }

    int temp = a[low];
    a[low] = -1;

    return  sumRule(a,num,low,high) || sumRule(a,num-temp,low+3,high) || sumRule(a,num-temp,low+1,high) ;

}

But when I send 11 to this, it still returns true, anyone has an idea what am i missing here?

Thanks,


问:
Could not find method testImplementation() for arguments [junit:junit:4.12]
```<code>dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha06'
    implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha06'
    implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha06'
    implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha06'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
</code>```

This is my build.gradle file and I tried many ways but I can't fix this, when I start Android Studio and gradle starts build the project Android Studio throw this error
how can I fix it?( I am new in Android)

Could not find method testImplementation() for arguments [junit:junit:4.12] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

答:
100% working.

Replace testİmplementation with testImplementation.(İ with I or i)

in your dependencies

```<code>dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha06'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha06'
implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha06'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha06'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testimplementation 'junit:junit:4.12'
androidTestimplementation 'com.android.support.test:runner:1.0.2'
androidTestimplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
</code>```

}

Body:
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha06'
    implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha06'
    implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha06'
    implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha06'
    implementation 'com.android.support:design:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

This is my build.gradle file and I tried many ways but I can't fix this, when I start Android Studio and gradle starts build the project Android Studio throw this error
how can I fix it?( I am new in Android)

Could not find method testImplementation() for arguments [junit:junit:4.12] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Body:
100% working.

Replace testİmplementation with testImplementation.(İ with I or i)

in your dependencies

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'android.arch.navigation:navigation-fragment:1.0.0-alpha06'
implementation 'android.arch.navigation:navigation-ui:1.0.0-alpha06'
implementation 'android.arch.navigation:navigation-fragment-ktx:1.0.0-alpha06'
implementation 'android.arch.navigation:navigation-ui-ktx:1.0.0-alpha06'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testimplementation 'junit:junit:4.12'
androidTestimplementation 'com.android.support.test:runner:1.0.2'
androidTestimplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

}


问:
Using string stream as split result in lambda
I need to split line based on comma and add it to a Map simultaneously in one go. I know that I can collect the splitted stream to list and then iterate over list for same effect. But I need to know if that can be done.

Input : List<String> - (A, B) (A,C)

Output : Map<String, List<String>> -  (A, (B,C))

Example Code : (Contains Error)

```<code>public void edgeListRepresentation(ArrayList<String> edges){
        Map<String, List<String>> edgeList = new HashMap<>();
        edges.forEach(connection -> {

            Stream.of(connection.split(","))
                    .map((arr) -> {
                        edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1]);
                    });
        });

    }

     public static void main(String[] args) throws IOException {
        EdgeList edgeList = new EdgeList();
        edgeList.edgeListRepresentation(new ArrayList<String>(){
            {
                add("A, B");
                add("A, C");
                add("A, E");
                add("B, C");
                add("C, E");
                add("C, D");
                add("D, E");
            }
        });
    }
</code>```

答:
You may solve your problem by using map + groupBy + mapping. Split all your lines by comma and put the result into common List of tuples. In the end, just apply groupBy collector and mapping to pick up only value from tuple. For example:

```<code>new ArrayList<String>() {
    {
        add("A, B");
        add("A, C");
        add("A, E");
        add("B, C");
        add("C, E");
        add("C, D");
        add("D, E");
    }
}.stream()
    .map(line -> line.split(","))
    .collect(Collectors.groupingBy(
        tuple -> tuple[0],
        Collectors.mapping(
            tuple -> tuple[1].trim(),
            Collectors.toList())
    ))
</code>```

Output: {A=[B, C, E], B=[C], C=[E, D], D=[E]}

Body:
I need to split line based on comma and add it to a Map simultaneously in one go. I know that I can collect the splitted stream to list and then iterate over list for same effect. But I need to know if that can be done.

Input : List<String> - (A, B) (A,C)

Output : Map<String, List<String>> -  (A, (B,C))

Example Code : (Contains Error)

public void edgeListRepresentation(ArrayList<String> edges){
        Map<String, List<String>> edgeList = new HashMap<>();
        edges.forEach(connection -> {

            Stream.of(connection.split(","))
                    .map((arr) -> {
                        edgeList.computeIfAbsent(arr[0], val -> new ArrayList<String>()).add(arr[1]);
                    });
        });

    }

     public static void main(String[] args) throws IOException {
        EdgeList edgeList = new EdgeList();
        edgeList.edgeListRepresentation(new ArrayList<String>(){
            {
                add("A, B");
                add("A, C");
                add("A, E");
                add("B, C");
                add("C, E");
                add("C, D");
                add("D, E");
            }
        });
    }

Body:
You may solve your problem by using map + groupBy + mapping. Split all your lines by comma and put the result into common List of tuples. In the end, just apply groupBy collector and mapping to pick up only value from tuple. For example:

new ArrayList<String>() {
    {
        add("A, B");
        add("A, C");
        add("A, E");
        add("B, C");
        add("C, E");
        add("C, D");
        add("D, E");
    }
}.stream()
    .map(line -> line.split(","))
    .collect(Collectors.groupingBy(
        tuple -> tuple[0],
        Collectors.mapping(
            tuple -> tuple[1].trim(),
            Collectors.toList())
    ))

Output: {A=[B, C, E], B=[C], C=[E, D], D=[E]}


问:
Disabling ieretrofit.js on Blogger
this script is giving me trouble in IE 9. From what I heard it was used to get rounded corners working on old IE versions. Now I don't need it anymore... And worse, it is forcing me to keep a <META content=IE=EmulateIE7 http-equiv=X-UA-Compatible> tag or the scripts messes my opaque windows. It seems to be included automatically with the  tag. Anyone knows how to prevent it from being loaded?

答:
I've finally figured this one out.

By replacing

```<code><b:include data='blog' name='all-head-content'/>
</code>```

With

```<code><meta expr:content='"text/html; charset=" + data:blog.encoding' http-equiv='Content-Type'/>
<meta content='true' name='MSSmartTagsPreventParsing'/>
<meta content='blogger' name='generator'/>
<link expr:href='data:blog.homepageUrl + "favicon.ico"' rel='icon' type='image/x-icon'/>
<link expr:href='data:blog.url' rel='canonical'/>
<data:blog.feedLinks/>
<b:if cond='data:blog.url == data:blog.homepageUrl'>
   <link href='http://www.blogger.com/openid-server.g' rel='openid.server'/>
</b:if>
</code>```

Everything works as expected.

At least for my blog this produces the same header output than before (minus the two IE specific scripts and a third global script which I'm not sure about). I've run diff to be sure.

Update 1

If you want the non IE specific script, just add this after the Content-Type tag:

```<code><script type='text/javascript'>(function() { var a=window;function c(b){this.t={};this.tick=function(b,i,d){d=d!=void 0?d:(new Date).getTime();this.t[b]=[d,i]};this.tick("start",null,b)}var e=new c;a.jstiming={Timer:c,load:e};try{var g=null;a.chrome&&a.chrome.csi&&(g=Math.floor(a.chrome.csi().pageT));g==null&&a.gtbExternal&&(g=a.gtbExternal.pageT());g==null&&a.external&&(g=a.external.pageT);g&&(a.jstiming.pt=g)}catch(h){};a.tickAboveFold=function(b){var f=0;if(b.offsetParent){do f+=b.offsetTop;while(b=b.offsetParent)}b=f;b<=750&&a.jstiming.load.tick("aft")};var j=!1;function k(){j||(j=!0,a.jstiming.load.tick("firstScrollTime"))}a.addEventListener?a.addEventListener("scroll",k,!1):a.attachEvent("onscroll",k);
 })();</script>
</code>```

Update 2

This also removes the generated <link rel="image_src">. I just hardcoded an image.

ContentLicense: CC BY-SA 3.0

Title: Disabling ieretrofit.js on Blogger

Body:
I've finally figured this one out.

By replacing

<b:include data='blog' name='all-head-content'/>

With

<meta expr:content='&quot;text/html; charset=&quot; + data:blog.encoding' http-equiv='Content-Type'/>
<meta content='true' name='MSSmartTagsPreventParsing'/>
<meta content='blogger' name='generator'/>
<link expr:href='data:blog.homepageUrl + &quot;favicon.ico&quot;' rel='icon' type='image/x-icon'/>
<link expr:href='data:blog.url' rel='canonical'/>
<data:blog.feedLinks/>
<b:if cond='data:blog.url == data:blog.homepageUrl'>
   <link href='http://www.blogger.com/openid-server.g' rel='openid.server'/>
</b:if>

Everything works as expected.

At least for my blog this produces the same header output than before (minus the two IE specific scripts and a third global script which I'm not sure about). I've run diff to be sure.

Update 1

If you want the non IE specific script, just add this after the Content-Type tag:

<script type='text/javascript'>(function() { var a=window;function c(b){this.t={};this.tick=function(b,i,d){d=d!=void 0?d:(new Date).getTime();this.t[b]=[d,i]};this.tick(&quot;start&quot;,null,b)}var e=new c;a.jstiming={Timer:c,load:e};try{var g=null;a.chrome&amp;&amp;a.chrome.csi&amp;&amp;(g=Math.floor(a.chrome.csi().pageT));g==null&amp;&amp;a.gtbExternal&amp;&amp;(g=a.gtbExternal.pageT());g==null&amp;&amp;a.external&amp;&amp;(g=a.external.pageT);g&amp;&amp;(a.jstiming.pt=g)}catch(h){};a.tickAboveFold=function(b){var f=0;if(b.offsetParent){do f+=b.offsetTop;while(b=b.offsetParent)}b=f;b&lt;=750&amp;&amp;a.jstiming.load.tick(&quot;aft&quot;)};var j=!1;function k(){j||(j=!0,a.jstiming.load.tick(&quot;firstScrollTime&quot;))}a.addEventListener?a.addEventListener(&quot;scroll&quot;,k,!1):a.attachEvent(&quot;onscroll&quot;,k);
 })();</script>

Update 2

This also removes the generated <link rel="image_src">. I just hardcoded an image.


问:
How to replace array element with respect to Index on another array
I have one array which contains values array1 = [a,b,c,d,e,f,g] and another array contains index of array1 and the value to be replaced array2 = [[2,u],[3,x],[6,z]].

Now I want to replace value of array1 with respect to array2 please not array2 consist of [array1_position, value_to_be_replaced]

Now my new arra1 should look like this array1 = [a,b,u,x,e,f,z].

I can do this with for loop but its again time consuming. what trick can i use to replace the value quickly. I am just learning about arrays and have a little knowledge on it.

答:
With an ordered array2 by indices, you could take a closure over an index of this array and map the values from eithe the first array or the replacements array.

var array1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'],
    array2 = [[2, 'u'], [3, 'x'], [6, 'z']],
    result = array1.map(
        (j => (v, i) => i === array2[j][0] ? array2[j++][1] : v)
        (0)
    );

console.log(result);```


问:
How do I print statements inside a function that has been applied to a Spark RDD?
I'm applying a function to a Spark RDD, like so:

```<code>data_2 = sqlContext.createDataFrame(pandas_df,data_schema)

data_3 = data_2.rdd.map(lambda x: parallelized_func(x, **args*)).collect()
</code>```

Now, the function parallelized_func looks something like this:

```<code>def parallelized_func(a,b,c):
    ####FUNCTION BODY#####
    print("unique identifier for each row in pandas_df")
    return {'df1':df1,'df2':df2}
</code>```

The issue I'm facing is this: When I run the "data_3 = ..." statement above in a Databricks notebook, I want the to get the unique identifier that I'm printing inside parallelized_func to show up somewhere, on some console, because that would make it easier to debug when there's an issue with any row in the pandas_df dataframe.

I tried checking the std_out and std_err consoles for every executor that's running the jobs, but there's always a whole load of other statements that occupy most of the console (all Spark statements related to various tasks being executed, I assume). I can sometimes find my print statement in this vast sea of other statements, but it's a really inefficient and ineffective way of debugging.

Is there a better way I can go about printing a statement like this? Or a better way of finding it? Can I for instance suppress all other execution-related statements that Spark keeps throwing up on the console?

Attaching a snapshot of the other statements that get printed on the console.

答:
Print it's not really good solution, because as you said there is tons of logs that spark's write (and print for debugging it's not good also).

You can make logger that write your logs to somewhere else (thats way only your logs will be write over there) such as NFS / whereever u can write it.(even locally on the executors and then check for it)

If you try to find the "corrupted" rows maybe, only for deubgging, filter only the corrupted rows and collect it to the driver, and then u'll can check the rows locally on the notebook.

Body:
I'm applying a function to a Spark RDD, like so:

data_2 = sqlContext.createDataFrame(pandas_df,data_schema)

data_3 = data_2.rdd.map(lambda x: parallelized_func(x, **args*)).collect()

Now, the function parallelized_func looks something like this:

def parallelized_func(a,b,c):
    ####FUNCTION BODY#####
    print("unique identifier for each row in pandas_df")
    return {'df1':df1,'df2':df2}

The issue I'm facing is this: When I run the "data_3 = ..." statement above in a Databricks notebook, I want the to get the unique identifier that I'm printing inside parallelized_func to show up somewhere, on some console, because that would make it easier to debug when there's an issue with any row in the pandas_df dataframe.

I tried checking the std_out and std_err consoles for every executor that's running the jobs, but there's always a whole load of other statements that occupy most of the console (all Spark statements related to various tasks being executed, I assume). I can sometimes find my print statement in this vast sea of other statements, but it's a really inefficient and ineffective way of debugging.

Is there a better way I can go about printing a statement like this? Or a better way of finding it? Can I for instance suppress all other execution-related statements that Spark keeps throwing up on the console?

Attaching a snapshot of the other statements that get printed on the console.


问:
Figuring out RegEx search term
I'm very new to this whole thing. I am using regex to extract data from an HTML which contains:

```<code><p class="bold"> Last Statement:</p>
<p>Yes sir. I  would like to thank God, my dad, my Lord Jesus savior for saving me and changing  my life. I want to apologize to my in-laws for causing all this emotional pain.  I love y’all and consider y’all my sisters I never had. I want to thank you for  forgiving me. Thank you warden. </p>
</code>```

I am trying to extract the text using

```<code>word = re.findall('Last Statement:</p>.*<p>(.+)</p>', x)
</code>```

But it's giving me an empty list. How can I debug that?

答:
you were almost here. replacing .* by \s* should make it work.

```<code>word = re.findall('Last Statement:</p>\s*<p>(.+)</p>', x)
</code>```

e.g.

```<code>import re

if __name__ == "__main__":
    s = """
<p class="bold"> Last Statement:</p>
<p>Yes sir. I  would like to thank God, my dad, my Lord Jesus savior for saving me and changing  my life. I want to apologize to my in-laws for causing all this emotional pain.  I love y’all and consider y’all my sisters I never had. I want to thank you for  forgiving me. Thank you warden. </p>
        """
    word = re.findall('Last Statement:</p>\s*<p>(.+)</p>', s)
    print(word)
</code>```

since you are processing html, it might be better tough to use an xml parser + xpath to find the text you are interested in...

Title: Figuring out RegEx search term

Body:
I'm very new to this whole thing. I am using regex to extract data from an HTML which contains:

 Last Statement:

Yes sir. I  would like to thank God, my dad, my Lord Jesus savior for saving me and changing  my life. I want to apologize to my in-laws for causing all this emotional pain.  I love y’all and consider y’all my sisters I never had. I want to thank you for  forgiving me. Thank you warden.

I am trying to extract the text using

word = re.findall('Last Statement:
.*
(.+)
', x)

But it's giving me an empty list. How can I debug that?

Body:
you were almost here. replacing .* by \s* should make it work.

word = re.findall('Last Statement:</p>\s*<p>(.+)</p>', x)

e.g.

import re

if __name__ == "__main__":
    s = """
<p class="bold"> Last Statement:</p>
<p>Yes sir. I  would like to thank God, my dad, my Lord Jesus savior for saving me and changing  my life. I want to apologize to my in-laws for causing all this emotional pain.  I love y&rsquo;all and consider y&rsquo;all my sisters I never had. I want to thank you for  forgiving me. Thank you warden. </p>
        """
    word = re.findall('Last Statement:</p>\s*<p>(.+)</p>', s)
    print(word)

since you are processing html, it might be better tough to use an xml parser + xpath to find the text you are interested in...


问:
How can I make the corners of my bottom sheet dialog rounded?
I'm trying to make the top corners of my BottomSheetDialog rounded, but I haven't had any luck with anything online. This is what I would like for it to look like:

No matter what I've tried, I keep getting this:

I've tried the method here and using shapeAppearanceLargeComponent (what I'm using now).

Here is my code:

styles.xml

```<code> <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ...
    <item name="shapeAppearanceLargeComponent">@style/CustomShapeAppearanceBottomSheetDialog</item>
</style>

<style name="CustomShapeAppearanceBottomSheetDialog" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSizeTopRight">16dp</item>
    <item name="cornerSizeTopLeft">16dp</item>
</style>
</code>```

BottomNavMenuFragment:

```<code>public class BottomNavMenuFragment extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bottom_nav_drawer, container, false);
    }
}
</code>```

And this is how I'm showing the fragment:

```<code>BottomNavMenuFragment navFragment = new BottomNavMenuFragment();
navFragment.show(getSupportFragmentManager(), navFragment.getTag());
</code>```

Nothing I seem to do works. Could someone point me in the right direction?

答:
You can create following shape in your drawable:

drawable/rounded_corners.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:shape="rectangle">
    <solid android:color="#fff"/>
    <corners
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp"/>
</shape>```
</div>
</div>
</p>

<p>Then for the layout for your bottom sheet you can add this drawable as a background property.</p>

```android:background="@drawable/rounded_corners"
```

Body:
I'm trying to make the top corners of my BottomSheetDialog rounded, but I haven't had any luck with anything online. This is what I would like for it to look like:

No matter what I've tried, I keep getting this:

I've tried the method here and using shapeAppearanceLargeComponent (what I'm using now).

Here is my code:

styles.xml

BottomNavMenuFragment:

public class BottomNavMenuFragment extends BottomSheetDialogFragment {
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_bottom_nav_drawer, container, false);
    }
}

And this is how I'm showing the fragment:

BottomNavMenuFragment navFragment = new BottomNavMenuFragment();
navFragment.show(getSupportFragmentManager(), navFragment.getTag());

Nothing I seem to do works. Could someone point me in the right direction?

Body:
You can create following shape in your drawable:

drawable/rounded_corners.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:shape="rectangle">
    <solid android:color="#fff"/>
    <corners
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp"/>
</shape>

Then for the layout for your bottom sheet you can add this drawable as a background property.

android:background="@drawable/rounded_corners"


问:
My c++ function is not running and I am not able to decode it
Hey guys I am new with c++. I have the following function in c++ but it always gives me an error by the "double overlap" function and I do not know why. Can somebody tell me, what I am doing wrong?</p>

```<code>double overlap(vector<double> &R1, vector<double> &R2) {
    // overlap in the x dimension
    double xmin = max(R1[0], R2[0]);
    double xmax = min(R1[2], R2[2]);
    if (xmin >= xmax) return 0;

    // overlap in the y dimension
    double ymin = max(R1[1], R2[1]);
    double ymax = min(R1[3], R2[3]);
    if (ymin >= ymax) return 0;

    double overlap_area = (xmax-xmin)*(ymax-ymin)

    return overlap_area;
}

int main() {
    vector<int> R1;
    vector<int> R2;

    // Coordinates of the rectangles
    // with the .push_back() function we are adding the rectangles to our vector to give it to the algorithm.
    // x: x-coordinate, y: y-coordinate, w: weidth, h: height - (w,h: distance from left/botton to right/top side of the rectangle)
    int x1 = 0, y1 = 0, w1 = 6, h1 = 9;
    R1.push_back(x1);
    R1.push_back(y1);
    R1.push_back(w1);
    R1.push_back(h1);

    int x2 = 3, y2 = 4, w2 = 3, h2 = 3;
    R2.push_back(x2);
    R2.push_back(y2);
    R2.push_back(w2);
    R2.push_back(h2);

    cout << "Overlap = " << overlap(R1, R2) << endl;
}
</code>```

答:
You declare (along with the definition) as receiving two references to vectors of doubles.

```<code>double overlap(vector<double> &R1, vector<double> &R2)
{ /* ... */ }
</code>```

You call with two vectors of int

```<code>vector<int> R1;
vector<int> R2;
/* ... */ overlap(R1, R2) /* ... */
</code>```

If you read the error message closely, I bet it will tell you this.

Body:
Hey guys I am new with c++. I have the following function in c++ but it always gives me an error by the "double overlap" function and I do not know why. Can somebody tell me, what I am doing wrong?

double overlap(vector<double> &R1, vector<double> &R2) {
    // overlap in the x dimension
    double xmin = max(R1[0], R2[0]);
    double xmax = min(R1[2], R2[2]);
    if (xmin >= xmax) return 0;

    // overlap in the y dimension
    double ymin = max(R1[1], R2[1]);
    double ymax = min(R1[3], R2[3]);
    if (ymin >= ymax) return 0;

    double overlap_area = (xmax-xmin)*(ymax-ymin)

    return overlap_area;
}

int main() {
    vector<int> R1;
    vector<int> R2;

    // Coordinates of the rectangles
    // with the .push_back() function we are adding the rectangles to our vector to give it to the algorithm.
    // x: x-coordinate, y: y-coordinate, w: weidth, h: height - (w,h: distance from left/botton to right/top side of the rectangle)
    int x1 = 0, y1 = 0, w1 = 6, h1 = 9;
    R1.push_back(x1);
    R1.push_back(y1);
    R1.push_back(w1);
    R1.push_back(h1);

    int x2 = 3, y2 = 4, w2 = 3, h2 = 3;
    R2.push_back(x2);
    R2.push_back(y2);
    R2.push_back(w2);
    R2.push_back(h2);

    cout << "Overlap = " << overlap(R1, R2) << endl;
}

Body:
You declare (along with the definition) as receiving two references to vectors of doubles.

double overlap(vector<double> &R1, vector<double> &R2)
{ /* ... */ }

You call with two vectors of int

vector<int> R1;
vector<int> R2;
/* ... */ overlap(R1, R2) /* ... */

If you read the error message closely, I bet it will tell you this.


问:
How do I use C++20 in vscode?
I want to use C++20 in vscode as I'd like to use .contains on an unordered_set, but when I try it I get
error C2039: 'contains': is not a member of 'std::unordered_set
and I don't understand why as I 've already went on to c_cpp_properties.json and specified the use of c++20 but it still doesn't seem to work, and I can't find anything anywhere about changing the C++ version on vscode.

Compiler version: 19.25.28614 for x86

答:
As of my knowledge, settings about c++ version in c_cpp_properties.json are just used for services that help you write the code (intellisense, code browsing, etc.).
Vscode has no c++ compiler of its own. It uses whatever compiler you configured it to.

You might want to check the latest standard your compiler supports. I found this post very helpful. How to determine the version of the C++ standard used by the compiler?

Make sure to evaluate the constant using the compiler (compile-time or run-time). You might see a different value when you hover the cursor on it.

Title: How do I use C++20 in vscode?


问:
Load entire html page in python
I need to store in a str variable an entire html page.
I'm doing this:

```<code>import requests
from bs4 import BeautifulSoup

url = my_url
response = requests.get(url)
page = str(BeautifulSoup(response.content))
</code>```

This works but the page in my_url is not "complete". It is a website in which going to the end, new things will load, and i need all the page, not only the main visible part.

Is there a way to load the entire page and then store it?

I also tried to load the page manually and then looking at the source code, but the final part of the page is still not visible.

Alternatively, all I want from my_url page are all the links inside it, and all of them are like:

```<code>my_url/something/first-post
my_url/something/second-post
</code>```

Is there a way to find all the links in another way? So, all the possible url that starts with "my_url/something/"

Thanks in advance

答:
For the alternative option, you can find the  tags via find_all

```<code>links = soup.find_all('a')
</code>```

to get all starting with you can use the following

```<code>result = [link for link  in links if link.startswith('my_url/something/')]
</code>```

Title: Load entire html page in python

Body:
I need to store in a str variable an entire html page.
I'm doing this:

import requests
from bs4 import BeautifulSoup

url = my_url
response = requests.get(url)
page = str(BeautifulSoup(response.content))

This works but the page in my_url is not "complete". It is a website in which going to the end, new things will load, and i need all the page, not only the main visible part.

Is there a way to load the entire page and then store it?

I also tried to load the page manually and then looking at the source code, but the final part of the page is still not visible.

Alternatively, all I want from my_url page are all the links inside it, and all of them are like:

my_url/something/first-post
my_url/something/second-post

Is there a way to find all the links in another way? So, all the possible url that starts with "my_url/something/"

Thanks in advance

Body:
For the alternative option, you can find the <a> tags via find_all

links = soup.find_all('a')

to get all starting with you can use the following

result = [link for link  in links if link.startswith('my_url/something/')]


问:
How to turn a table vertical using PHP
I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script

Name
Age
Height

<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
" . $row["Name"]. "	" . $row["Age"] . "	"
. $row["Height"]. "
";
}
echo "
";
} else //{ echo "0 results"; }//
$conn->close();
?>

```

but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .

答:
It's not a good idea ! if you have a lot of ROW you will generate a long table not visible for user in screen.

if you want to do it after all you can change table structure but you will not respect html table structure.

I will give you a

Dirty code

```<code><table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"];  ?></td>
<?php } ?>
</tr>

<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
    <td><?php echo $value["Age"];  ?></td>
<?php } ?>
</tr>

<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
    <td><?php echo $value["Height"];  ?></td>
<?php } ?>
</tr>
</table>
</code>```

I recommand to USE CSS instead a table

Title: How to turn a table vertical using PHP

Body:
I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script

Name
Age
Height

<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "
" . $row["Name"]. "	" . $row["Age"] . "	"
. $row["Height"]. "
";
}
echo "
";
} else //{ echo "0 results"; }//
$conn->close();
?>

but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can't get the result at all and the shape of the table is far away from what I want and this is the full script of my page .

Body:
It's not a good idea ! if you have a lot of ROW you will generate a long table not visible for user in screen.

if you want to do it after all you can change table structure but you will not respect html table structure.

I will give you a

Dirty code

<table>
<tr>
<th>Name</th>
<?php foreach ($row as $value) { ?><td><?php echo$value["Name"];  ?></td>
<?php } ?>
</tr>

<tr>
<th>Age</th>
<?php foreach ($row as $value) { ?>
    <td><?php echo $value["Age"];  ?></td>
<?php } ?>
</tr>

<tr>
<th>Height</th>
<?php foreach ($row as $value) { ?>
    <td><?php echo $value["Height"];  ?></td>
<?php } ?>
</tr>
</table>

I recommand to USE CSS instead a table


问:
try/except issue in Python
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

```<code>sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

答:
I think the easiest way is this:

```<code>while True:  #open a while loop
        try:  #ask your questions here
            sh = input("Enter hours:")
            fh = float(sh)
            sr = input("Enter Rate:")
            fr = float(sr)
        except ValueError:  #if a string is in input instead of a float do this
            print("input is not numeric")
        else:  # if user did all right do this and end the while loop
            print(fh, fr)
            if fh > 40:
                reg = fr  * fh
                otp = (fh - 40.0) * (fr * 0.5)
                xp = reg + otp
            else:
                xp = fh * fr
            print("Pay:",xp)
            break
</code>```

edit:

```<code>def check_for_float(question):
    #define a function to check if it's float
    while True:
        #open a while loop
            try:
                #ask your questions here
                value = float(input(question))
                #return value
                return value
            except ValueError:
                #if a string is in input instead of a float give second chance
                print("input is not numeric, try again:")

#execute function and give argument question
#returned value will be your variable
fr = check_for_float("Enter Rate:")
fh = check_for_float("Enter hours:")

#do your stuff with the returned variables
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)
</code>```

all in one:

```<code>def calculate_userinput ():
    ## function in function
    #this means the function check_for_float isn't available outside of calculate
    def check_for_float(question):
        #define a function to check if it's float
        while True:
            #open a while loop
                try:
                    #ask your questions here
                    value = float(input(question))
                    #return value
                    return value
                except ValueError:
                    #if a string is in input instead of a float give second chance
                    print("input is not numeric, try again:")
    #execute function and give argument question
    #returned value will be your variable
    fr = check_for_float("Enter Rate:")
    fh = check_for_float("Enter hours:")
    #do your stuff with the returned values
    print(fh, fr)
    if fh > 40:
        reg = fr  * fh
        otp = (fh - 40.0) * (fr * 0.5)
        xp = reg + otp
    else:
        xp = fh * fr
    print("Pay:",xp)

calculate_userinput()
</code>```

functions for diffrent stuff to use

```<code>def check_for_float(question):
    #define a function to check if it's float
    while True:
        #open a while loop
            try:
                #ask your questions here
                value = float(input(question))
                #return value
                return value
            except ValueError:
                #if a string is in input instead of a float give second chance
                print("input is not numeric, try again:")

def calculate():
    fr = check_for_float("Enter Rate:")
    fh = check_for_float("Enter hours:")
    print(fh, fr)
    if fh > 40:
        reg = fr  * fh
        otp = (fh - 40.0) * (fr * 0.5)
        xp = reg + otp
    else:
        xp = fh * fr
    print("Pay:",xp)
calculate()
</code>```

programming is like engineering, first you need to know what you want to create then how you get there in the best way. Wich structure you want, are there subsystems what they need to do or to watch et cetera.

Title: try/except issue in Python

Body:
I ran the following code as a practice purpose from one of the Python book and I want the output as shown in the URL provided below. So, when I am running the first activity in the question (from book - shown in the photo) to verify if he has done it correctly, it's working but when he ran the second activity, it's not working properly. Ideally, I should get except statement printed if I am entering any string in the first user prompted input but I am being asked for the second user prompted input i.e., rate. Why is that so? And also please tell if it is advisable to put complete code in try portion or ideally we should only put the portion in a try statement for which we are sure that it wouldn't work out and it would jump to except block?

When I enter forty, I am not given the error message which is in the book which means that there can be some changes made in the code. However, it is working fine when I am including all lines of codes under try instead of just 2 lines which are currently there i.e., (fh = float(sh) and fr = float(sr)). How can I correct my existing written code by just writing two statements in a try portion?

Your help would be appreciated.

Issue: Enter Hours: fortyError, please enter numeric input

Image of the required output is below:

Following is the code:

sh = input("Enter hours:")
sr = input("Enter Rate:")
try:
    fh = float(sh)
    fr = float(sr)
except:
    print('Error, please enter numeric input')
    quit()
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

Body:
I think the easiest way is this:

while True:  #open a while loop
        try:  #ask your questions here
            sh = input("Enter hours:")
            fh = float(sh)
            sr = input("Enter Rate:")
            fr = float(sr)
        except ValueError:  #if a string is in input instead of a float do this
            print("input is not numeric")
        else:  # if user did all right do this and end the while loop
            print(fh, fr)
            if fh > 40:
                reg = fr  * fh
                otp = (fh - 40.0) * (fr * 0.5)
                xp = reg + otp
            else:
                xp = fh * fr
            print("Pay:",xp)
            break

edit:

def check_for_float(question):
    #define a function to check if it's float
    while True:
        #open a while loop
            try:
                #ask your questions here
                value = float(input(question))
                #return value
                return value
            except ValueError:
                #if a string is in input instead of a float give second chance
                print("input is not numeric, try again:")

#execute function and give argument question
#returned value will be your variable
fr = check_for_float("Enter Rate:")
fh = check_for_float("Enter hours:")

#do your stuff with the returned variables
print(fh, fr)
if fh > 40:
    reg = fr  * fh
    otp = (fh - 40.0) * (fr * 0.5)
    xp = reg + otp
else:
    xp = fh * fr
print("Pay:",xp)

all in one:

def calculate_userinput ():
    ## function in function
    #this means the function check_for_float isn't available outside of calculate
    def check_for_float(question):
        #define a function to check if it's float
        while True:
            #open a while loop
                try:
                    #ask your questions here
                    value = float(input(question))
                    #return value
                    return value
                except ValueError:
                    #if a string is in input instead of a float give second chance
                    print("input is not numeric, try again:")
    #execute function and give argument question
    #returned value will be your variable
    fr = check_for_float("Enter Rate:")
    fh = check_for_float("Enter hours:")
    #do your stuff with the returned values
    print(fh, fr)
    if fh > 40:
        reg = fr  * fh
        otp = (fh - 40.0) * (fr * 0.5)
        xp = reg + otp
    else:
        xp = fh * fr
    print("Pay:",xp)

calculate_userinput()

functions for diffrent stuff to use

def check_for_float(question):
    #define a function to check if it's float
    while True:
        #open a while loop
            try:
                #ask your questions here
                value = float(input(question))
                #return value
                return value
            except ValueError:
                #if a string is in input instead of a float give second chance
                print("input is not numeric, try again:")

def calculate():
    fr = check_for_float("Enter Rate:")
    fh = check_for_float("Enter hours:")
    print(fh, fr)
    if fh > 40:
        reg = fr  * fh
        otp = (fh - 40.0) * (fr * 0.5)
        xp = reg + otp
    else:
        xp = fh * fr
    print("Pay:",xp)
calculate()

programming is like engineering, first you need to know what you want to create then how you get there in the best way. Wich structure you want, are there subsystems what they need to do or to watch et cetera.


答:
You are using vector<double> as parameters for your function overlap. But in your main(), you have declared two vectors of type int and passing them to the function which is giving you error.

Just declare your vectors as :

```<code>vector<double> R1;
vector<double> R2;
</code>```

And add double values to them and your program would run fine.

Note : your program has an minor sytax error as well because you haven't specified semicolon after :

```<code>double overlap_area = (xmax-xmin)*(ymax-ymin)
</code>```

Title: My c++ function is not running and I am not able to decode it

Body:
You are using vector<double> as parameters for your function overlap. But in your main(), you have declared two vectors of type int and passing them to the function which is giving you error.

Just declare your vectors as :

vector<double> R1;
vector<double> R2;

And add double values to them and your program would run fine.

Note : your program has an minor sytax error as well because you haven't specified semicolon after :

double overlap_area = (xmax-xmin)*(ymax-ymin)


问:
Using Pandas Rank on strings in DataFrameGroupBy
I'm working on an organisational matrix, and am trying to reproduce a task in Python that is very inefficiently done using MS Access usually. There probably is a simple answer to this issue but i've not been able to find it anywhere, apologies if this has already been answered.

Let's posit a matrix in a dict and put it in a DF:

```<code>matrix ={'Flow':['Flow1','Flow2','Flow3','Flow4','Flow6']*6,
     'User':['Jill','Jacky','Joanie','Peter','Paul','Paddy']*5,
     'Role':['Requestor','Manager','Approver']*10}
mydf=pd.DataFrame(matrix)
</code>```

This gives me a table of flows for which there are three roles, each of which can be fulfilled by several possible individuals (only two here, many more in reality).

For each flow/role pair, i would like to get a ranking by name, so that my data looks like this:

```<code>   Flow    User       Role      Rank
0   Flow1  Jill       Requestor 1
5   Flow1  Paddy      Approver  1
10  Flow1  Paul       Manager   1
15  Flow1  Peter      Requestor 2
20  Flow1  Joanie     Approver  2
25  Flow1  Jacky      Manager   2
</code>```

and so on for each flows. This can be a first come first serve basis, alphabetical order does not matter really.

Supposedly, this should be done by using groupby.rank()

```<code>mydf['Rank']=mydf.groupby(['Flow','Role'])['User'].rank(method='dense')
</code>```

but this returns a 'NoneType' object is not callable error.
My end goal is to pivot the matrix to have each role represented in a column, but i really need this ranking to be able to represent the data for all users.

Please tell me what i'm doing wrong, perhaps i need to use .apply() instead, not sure how though.

答:
You can use .groupby, along with .cumcount:

```<code>mydf['Rank'] = mydf.groupby(['Flow','Role'])['User'].cumcount().add(1)
</code>```

Result:

```<code># print(mydf[mydf['Flow'].eq('Flow1')])

    Flow    User       Role  Rank
0   Flow1    Jill  Requestor     1
5   Flow1   Paddy   Approver     1
10  Flow1    Paul    Manager     1
15  Flow1   Peter  Requestor     2
20  Flow1  Joanie   Approver     2
25  Flow1   Jacky    Manager     2
</code>```

Body:
I'm working on an organisational matrix, and am trying to reproduce a task in Python that is very inefficiently done using MS Access usually. There probably is a simple answer to this issue but i've not been able to find it anywhere, apologies if this has already been answered.

Let's posit a matrix in a dict and put it in a DF:

matrix ={'Flow':['Flow1','Flow2','Flow3','Flow4','Flow6']*6,
     'User':['Jill','Jacky','Joanie','Peter','Paul','Paddy']*5,
     'Role':['Requestor','Manager','Approver']*10}
mydf=pd.DataFrame(matrix)

This gives me a table of flows for which there are three roles, each of which can be fulfilled by several possible individuals (only two here, many more in reality).

For each flow/role pair, i would like to get a ranking by name, so that my data looks like this:

   Flow    User       Role      Rank
0   Flow1  Jill       Requestor 1
5   Flow1  Paddy      Approver  1
10  Flow1  Paul       Manager   1
15  Flow1  Peter      Requestor 2
20  Flow1  Joanie     Approver  2
25  Flow1  Jacky      Manager   2

and so on for each flows. This can be a first come first serve basis, alphabetical order does not matter really.

Supposedly, this should be done by using groupby.rank()

mydf['Rank']=mydf.groupby(['Flow','Role'])['User'].rank(method='dense')

but this returns a 'NoneType' object is not callable error.
My end goal is to pivot the matrix to have each role represented in a column, but i really need this ranking to be able to represent the data for all users.

Please tell me what i'm doing wrong, perhaps i need to use .apply() instead, not sure how though.

Body:
You can use .groupby, along with .cumcount:

mydf['Rank'] = mydf.groupby(['Flow','Role'])['User'].cumcount().add(1)

Result:

# print(mydf[mydf['Flow'].eq('Flow1')])

    Flow    User       Role  Rank
0   Flow1    Jill  Requestor     1
5   Flow1   Paddy   Approver     1
10  Flow1    Paul    Manager     1
15  Flow1   Peter  Requestor     2
20  Flow1  Joanie   Approver     2
25  Flow1   Jacky    Manager     2


问:
How to store several pieces of info in a defaultdict
I have a list I'm iterating over to tally up some combinations, and I'd like to store some more info beyond the tallies. A Counter or defaultdict is good for tallies but I'm not sure how to add the aux info. For instance if I'm toting up all length-2 lists in my 'list_to_count' column I can do this:

import pandas as pd
from itertools import combinations
from collections import defaultdict

mydf = pd.DataFrame({'auxinfo': ['first', 'second', 'third'], 'list_to_count': [['apple', 'banana'], ['apple', 'banana', 'chicken'], ['apple']]})
print(mydf)
d=defaultdict(int)
for r in mydf.itertuples():
    combos = combinations(r.list_to_count, 2)
    for combo in combos:
        combo_name = ','.join(sorted(combo))
        d[combo_name] += 1
print(d)
```

<p>This is what I get:</p>

```auxinfo              list_to_count
0        first       [apple, banana]
1        second      [apple, banana, chicken]
2        third       [apple]
```

<pre class="lang-py prettyprint-override"><code>In [13]: d
Out[13]: defaultdict(int, {'apple,banana': 2, 'apple,chicken': 1, 'banana,chicken': 1})
</code>```

But I'd also like to store the auxinfo e.g. in a list, where the desired output would look like

{'apple,banana': (2, ['first', 'second']), 'apple,chicken': (1, ['second']), 'banana,chicken': (1, ['second'])}
```

The defaultdict can be intialized like defaultdict(tuple) in which I could store a tuple of (count, auxinfo_list) but the auxinfo_list itself isn't a defaultdict.

答:
You could use dict.get() and set the default value to (0, []).

d = {}
for r in mydf.itertuples():
    combos = combinations(r.list_to_count, 2)
    for combo in combos:
        combo_name = ','.join(sorted(combo))
        count, auxinfo_list = d.get(combo_name, (0, []))
        d[combo_name] = (count + 1, auxinfo_list + [r.auxinfo])

for key, value in d.items():
    print(f'{key}:\t{value}')
```

<p>Output:</p>

```apple,banana:   (2, ['first', 'second'])
apple,chicken:  (1, ['second'])
banana,chicken: (1, ['second'])
```

Body:
I have a list I'm iterating over to tally up some combinations, and I'd like to store some more info beyond the tallies. A Counter or defaultdict is good for tallies but I'm not sure how to add the aux info. For instance if I'm toting up all length-2 lists in my 'list_to_count' column I can do this:

import pandas as pd
from itertools import combinations
from collections import defaultdict

mydf = pd.DataFrame({'auxinfo': ['first', 'second', 'third'], 'list_to_count': [['apple', 'banana'], ['apple', 'banana', 'chicken'], ['apple']]})
print(mydf)
d=defaultdict(int)
for r in mydf.itertuples():
    combos = combinations(r.list_to_count, 2)
    for combo in combos:
        combo_name = ','.join(sorted(combo))
        d[combo_name] += 1
print(d)

This is what I get:

auxinfo              list_to_count
0        first       [apple, banana]
1        second      [apple, banana, chicken]
2        third       [apple]

In [13]: d
Out[13]: defaultdict(int, {'apple,banana': 2, 'apple,chicken': 1, 'banana,chicken': 1})

But I'd also like to store the auxinfo e.g. in a list, where the desired output would look like

{'apple,banana': (2, ['first', 'second']), 'apple,chicken': (1, ['second']), 'banana,chicken': (1, ['second'])}

The defaultdict can be intialized like defaultdict(tuple) in which I could store a tuple of (count, auxinfo_list) but the auxinfo_list itself isn't a defaultdict.

Body:
You could use dict.get() and set the default value to (0, []).

d = {}
for r in mydf.itertuples():
    combos = combinations(r.list_to_count, 2)
    for combo in combos:
        combo_name = ','.join(sorted(combo))
        count, auxinfo_list = d.get(combo_name, (0, []))
        d[combo_name] = (count + 1, auxinfo_list + [r.auxinfo])

for key, value in d.items():
    print(f'{key}:\t{value}')

Output:

apple,banana:   (2, ['first', 'second'])
apple,chicken:  (1, ['second'])
banana,chicken: (1, ['second'])


问:
Age as a time dependant covariate in Cox regression
I have a question regarding time-dependant variables in survival analysis. Do you usually count age as a time varying variable?
I am looking at a population of cancer patients who received certain treatment and were cured initially. They were then followed up for certain period of time. The total follow up time is up to 15 years, so it is relatively long, but some have of course a much shorter follow up time. The event of interest is whether they developed recurrence of their cancer or not.
So in SAS, here is how I am doing this

```<code>proc phreg data=have ;
Title 'Cox for cancer recurrence';
class sex tumor_differentiation;
model Time*Recurrence(0)=   age sex tumor_size tumor_differentiation/rl;
run;
</code>```

And in R

```<code>surv_object <- Surv(time = df$Time, event = df$Recurrence)
fit.coxph <- coxph(surv_object ~ Age +Sex + TumorSize + TumorDifferentiation,
                   data = have)
</code>```

The question here is, would you put in Age as a time dependant co-variate or would you just put in age at baseline in your model?
Thank you for your insights and appreciate your help

答: In the cancer research, the age at diagnosis has clinical importance, so in the usual setting, we use age at diagnosis as a variable, and it is fixed!</p>

Body:
I have a question regarding time-dependant variables in survival analysis. Do you usually count age as a time varying variable?
I am looking at a population of cancer patients who received certain treatment and were cured initially. They were then followed up for certain period of time. The total follow up time is up to 15 years, so it is relatively long, but some have of course a much shorter follow up time. The event of interest is whether they developed recurrence of their cancer or not.
So in SAS, here is how I am doing this

proc phreg data=have ;
Title 'Cox for cancer recurrence';
class sex tumor_differentiation;
model Time*Recurrence(0)=   age sex tumor_size tumor_differentiation/rl;
run;

And in R

surv_object <- Surv(time = df$Time, event = df$Recurrence)
fit.coxph <- coxph(surv_object ~ Age +Sex + TumorSize + TumorDifferentiation,
                   data = have)

The question here is, would you put in Age as a time dependant co-variate or would you just put in age at baseline in your model?
Thank you for your insights and appreciate your help