问:
Parse XML to Pandas DataFrame to CSV
I have tried multiple iterations of code to get this done but cant seem to find a good solution. Been at it for days.

Here is the XML data I am returning from an API:

```<code> <response status="success"><result>
  <job>
    <tenq>14:00:42</tenq>
    <tdeq>14:00:42</tdeq>
    <tlast>16:00:00</tlast>
    <status>FIN</status>
    <id>123</id>
    <cached-logs>123</cached-logs>
  </job>
  <log>
    <logs count="20" progress="100">
      <entry logid="123">
        <domain>1</domain>
        <receive_time>2017/11/25 12:12:02</receive_time>
        <serial>123</serial>
        <seqno>123</seqno>
        <actionflags>123</actionflags>
        <type>Example</type>
        <subtype>Example</subtype>
        <config_ver>0</config_ver>
        <time_generated>2017/11/25 12:12:00</time_generated>
        <src>192.168.1.1</src>
        <dst>192.168.1.1</dst>
        <natsrc>192.168.1.1</natsrc>
        <natdst>192.168.1.1</natdst>
        <rule>Example</rule>
        <srcloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</srcloc>
        <dstloc code="United States" cc="US">United States</dstloc>
        <app>Example</app>
        <vsys>Example</vsys>
        <from>Example</from>
        <to>Example</to>
        <inbound_if>Example</inbound_if>
        <outbound_if>Example</outbound_if>
        <logset>Example</logset>
        <time_received>Example</time_received>
        <sessionid>Example</sessionid>
        <repeatcnt>1</repeatcnt>
        <sport>123</sport>
        <dport>80</dport>
        <natsport>123</natsport>
        <natdport>80</natdport>
        <flags>123</flags>
        <flag-pcap>no</flag-pcap>
        <flag-flagged>no</flag-flagged>
        <flag-proxy>no</flag-proxy>
        <flag-url-denied>no</flag-url-denied>
        <flag-nat>yes</flag-nat>
        <captive-portal>no</captive-portal>
        <non-std-dport>no</non-std-dport>
        <transaction>no</transaction>
        <pbf-c2s>no</pbf-c2s>
        <pbf-s2c>no</pbf-s2c>
        <temporary-match>no</temporary-match>
        <sym-return>no</sym-return>
        <decrypt-mirror>no</decrypt-mirror>
        <proto>tcp</proto>
        <action>Example</action>
        <cpadding>0</cpadding>
        <dg_hier_level_1>0</dg_hier_level_1>
        <dg_hier_level_2>0</dg_hier_level_2>
        <dg_hier_level_3>0</dg_hier_level_3>
        <dg_hier_level_4>0</dg_hier_level_4>
        <vsys_name>Legacy</vsys_name>
        <device_name>Example</device_name>
        <vsys_id>123</vsys_id>
        <bytes>463</bytes>
        <bytes_sent>393</bytes_sent>
        <bytes_received>70</bytes_received>
        <packets>4</packets>
        <start>Example</start>
        <elapsed>0</elapsed>
        <category>Example</category>
        <padding>0</padding>
        <pkts_sent>3</pkts_sent>
        <pkts_received>1</pkts_received>
        <session_end_reason>Example</session_end_reason>
        <action_source>Example</action_source>
      </entry>
      <entry logid="456">
        <domain>1</domain>
        <receive_time>2017/11/25 12:12:02</receive_time>
        <serial>Example</serial>
        <seqno>Example</seqno>
        <actionflags>Example</actionflags>
        <type>Example</type>
        <subtype>Example</subtype>
        <config_ver>0</config_ver>
        <time_generated>2017/11/25 12:12:00</time_generated>
        <src>192.168.1.1</src>
        <dst>192.168.1.2</dst>
        <rule>Example</rule>
        <dstuser>Example</dstuser>
        <srcloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</srcloc>
        <dstloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</dstloc>
        <app>Example</app>
        <vsys>Example</vsys>
        <from>Example</from>
        <to>Example</to>
        <inbound_if>Example</inbound_if>
        <logset>Example</logset>
        <time_received>Example</time_received>
        <sessionid>0</sessionid>
        <repeatcnt>1</repeatcnt>
        <sport>123</sport>
        <dport>123</dport>
        <natsport>0</natsport>
        <natdport>0</natdport>
        <flags>123</flags>
        <flag-pcap>no</flag-pcap>
        <flag-flagged>no</flag-flagged>
        <flag-proxy>no</flag-proxy>
        <flag-url-denied>no</flag-url-denied>
        <flag-nat>no</flag-nat>
        <captive-portal>no</captive-portal>
        <non-std-dport>no</non-std-dport>
        <transaction>no</transaction>
        <pbf-c2s>no</pbf-c2s>
        <pbf-s2c>no</pbf-s2c>
        <temporary-match>no</temporary-match>
        <sym-return>no</sym-return>
        <decrypt-mirror>no</decrypt-mirror>
        <proto>tcp</proto>
        <action>Example</action>
        <cpadding>0</cpadding>
        <dg_hier_level_1>0</dg_hier_level_1>
        <dg_hier_level_2>0</dg_hier_level_2>
        <dg_hier_level_3>0</dg_hier_level_3>
        <dg_hier_level_4>0</dg_hier_level_4>
        <vsys_name>Example</vsys_name>
        <device_name>Example</device_name>
        <vsys_id>0</vsys_id>
        <bytes>70</bytes>
        <bytes_sent>70</bytes_sent>
        <bytes_received>0</bytes_received>
        <packets>1</packets>
        <start>Example</start>
        <elapsed>0</elapsed>
        <category>Example</category>
        <padding>0</padding>
        <pkts_sent>1</pkts_sent>
        <pkts_received>0</pkts_received>
        <session_end_reason>Example</session_end_reason>
        <action_source>Example</action_source>
      </entry>
      <entry logid="789">
        <domain>1</domain>
        <receive_time>2017/11/25 12:12:02</receive_time>
        <serial>Example</serial>
        <seqno>Example</seqno>
        <actionflags>Example</actionflags>
        <type>Example</type>
        <subtype>Example</subtype>
        <config_ver>0</config_ver>
        <time_generated>2017/11/25 12:12:00</time_generated>
        <src>192.168.1.1</src>
        <dst>192.168.1.2</dst>
        <rule>Example</rule>
        <srcuser>Example</srcuser>
        <dstuser>Example</dstuser>
        <srcloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</srcloc>
        <dstloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</dstloc>
        <app>Example</app>
        <vsys>Example</vsys>
        <from>Example</from>
        <to>Example</to>
        <inbound_if>Example</inbound_if>
        <outbound_if>Example</outbound_if>
        <logset>Example</logset>
        <time_received>Example</time_received>
        <sessionid>Example</sessionid>
        <repeatcnt>1</repeatcnt>
        <sport>123</sport>
        <dport>123</dport>
        <natsport>0</natsport>
        <natdport>0</natdport>
        <flags>Example</flags>
        <flag-pcap>no</flag-pcap>
        <flag-flagged>no</flag-flagged>
        <flag-proxy>no</flag-proxy>
        <flag-url-denied>no</flag-url-denied>
        <flag-nat>no</flag-nat>
        <captive-portal>no</captive-portal>
        <non-std-dport>no</non-std-dport>
        <transaction>no</transaction>
        <pbf-c2s>no</pbf-c2s>
        <pbf-s2c>no</pbf-s2c>
        <temporary-match>no</temporary-match>
        <sym-return>no</sym-return>
        <decrypt-mirror>no</decrypt-mirror>
        <proto>no</proto>
        <action>no</action>
        <cpadding>0</cpadding>
        <dg_hier_level_1>0</dg_hier_level_1>
        <dg_hier_level_2>0</dg_hier_level_2>
        <dg_hier_level_3>0</dg_hier_level_3>
        <dg_hier_level_4>0</dg_hier_level_4>
        <vsys_name>Example</vsys_name>
        <device_name>Example</device_name>
        <vsys_id>0</vsys_id>
        <bytes>299</bytes>
        <bytes_sent>104</bytes_sent>
        <bytes_received>195</bytes_received>
        <packets>2</packets>
        <start>Example</start>
        <elapsed>0</elapsed>
        <category>Example</category>
        <padding>0</padding>
        <pkts_sent>1</pkts_sent>
        <pkts_received>1</pkts_received>
        <session_end_reason>Example</session_end_reason>
        <action_source>Example</action_source>
      </entry>
    </logs>
  </log>
</result></response>
</code>```

I would like the data to fit into a dataframe so I can write it to a csv with the following headers:

```<code>logid
receive_time
type
src dst rule
srcuser
srcloc code
src_cc  *NEW HEADER*
dstloc code
dst_cc  *NEW HEADER*
app
from
to
repeatcnt
sport
dport
proto
action
bytes
bytes_sent
bytes_received
packets start
elapsed category
pkts_sent
pkts_received
session_end_reason
action_source
</code>```

Here is an image of the way the table should look (Obviously needs all the data inserted):

Table

I was able to get this partially working with a for loop,  but then i'd need an additional 29 loops and 29 df conversions to concat the remaining headers/data:

```<code>import xml.etree.ElementTree as ET
import pandas as pd

tree = ET.parse("My_Data.xml")

a = []
b = []

for src in tree.findall('.//src'):
    a.append({'Source': src.text})

for domain in tree.findall('.//domain'):
    b.append({'Domain': domain.text})

df = pd.DataFrame(a)

df1 = pd.DataFrame(b)

result = pd.concat([df,df1], axis=1)
</code>```

This is my very first post. I have looked through this site for years and it has helped me a ton. Thank you all for your help and hard work. Please let me know if you need additional information.

UPDATE

I am also having an issue with tags that do not exist in every response. For example, if 'type' didn't exist in the very first response, it would not be added to the header. If the second xml response contains this tag, it will throw an error: ValueError: dict contains fields not in fieldnames: 'type'

UPDATED CODE

This code posted in one of the responses works great, just need to modify it to work with the update above.

FINAL UPDATE

The code below works 100% for my use-case. You can see the full explanation in the selected answer within the comments section.

```<code>import csv
import xml.etree.ElementTree as et
from collections import OrderedDict

doc = et.parse('LogEntryCSV.xml')

csv_data = []

fields =  ['logid', 'receive_time', 'type', 'src', 'dst', 'rule',
           'srcuser', 'srcloc', 'dstloc', 'app', 'from', 'to', 'repeatcnt',
           'sport', 'dport', 'proto', 'action', 'bytes', 'bytes_sent',
           'bytes_received', 'packets', 'start', 'elapsed', 'category',
           'pkts_sent', 'pkts_received', 'session_end_reason', 'action_source']

for elem in doc.findall('.//entry'):
    inner_dict = OrderedDict({k:None for k in fields})   # PRE-POPULATES TEMP DICT

    inner_dict['logid'] = elem.attrib['logid']

    for item in elem.findall('.//*'):
        if item.tag in fields:
            if item.tag=='srcloc':
                inner_dict['scrloc code'] = item.attrib['code']
                inner_dict['scr_cc'] = item.attrib['cc']

            elif item.tag=='dstloc':
                inner_dict['dstloc code'] = item.attrib['code']
                inner_dict['dst_cc'] = item.attrib['cc']

            else:
                inner_dict[item.tag] = item.text

    csv_data.append(inner_dict)

with open('Output.csv', 'w', newline='') as f:
    w = csv.DictWriter(f, csv_data[0].keys())
    w.writeheader()
    w.writerows(csv_data)
</code>```

答:
Consider using containers like list of dictionaries that are assigned within a for loop iteration through each child of entry. For attributes, if conditionals are used to parse the attribute instead of text value. OrderedDict is used to keep keys intact as they are filled in. No need for pandas as you should leave the library for actual data analysis not data wrangling.

```<code>import csv
import xml.etree.ElementTree as et
from collections import OrderedDict

doc = et.parse('LogEntryCSV.xml')

csv_data = []

fields =  ['logid', 'receive_time', 'type', 'src', 'dst', 'rule',
           'srcuser', 'srcloc', 'dstloc', 'app', 'from', 'to', 'repeatcnt',
           'sport', 'dport', 'proto', 'action', 'bytes', 'bytes_sent',
           'bytes_received', 'packets', 'start', 'elapsed', 'category',
           'pkts_sent', 'pkts_received', 'session_end_reason', 'action_source']

for elem in doc.findall('.//entry'):
    inner_dict = OrderedDict({k:None for k in fields})   # PRE-POPULATES TEMP DICT

    inner_dict['logid'] = elem.attrib['logid']

    for item in elem.findall('.//*'):
        if item.tag in fields:
            if item.tag=='srcloc':
                inner_dict['scrloc code'] = item.attrib['code']
                inner_dict['scr_cc'] = item.attrib['cc']

            elif item.tag=='dstloc':
                inner_dict['dstloc code'] = item.attrib['code']
                inner_dict['dst_cc'] = item.attrib['cc']

            else:
                inner_dict[item.tag] = item.text

    csv_data.append(inner_dict)

with open('Output.csv', 'w', newline='') as f:
    w = csv.DictWriter(f, csv_data[0].keys())
    w.writeheader()
    w.writerows(csv_data)
</code>```

Title: Parse XML to Pandas DataFrame to CSV

Body:
I have tried multiple iterations of code to get this done but cant seem to find a good solution. Been at it for days.

Here is the XML data I am returning from an API:

 <response status="success"><result>
  <job>
    <tenq>14:00:42</tenq>
    <tdeq>14:00:42</tdeq>
    <tlast>16:00:00</tlast>
    <status>FIN</status>
    <id>123</id>
    <cached-logs>123</cached-logs>
  </job>
  <log>
    <logs count="20" progress="100">
      <entry logid="123">
        <domain>1</domain>
        <receive_time>2017/11/25 12:12:02</receive_time>
        <serial>123</serial>
        <seqno>123</seqno>
        <actionflags>123</actionflags>
        <type>Example</type>
        <subtype>Example</subtype>
        <config_ver>0</config_ver>
        <time_generated>2017/11/25 12:12:00</time_generated>
        <src>192.168.1.1</src>
        <dst>192.168.1.1</dst>
        <natsrc>192.168.1.1</natsrc>
        <natdst>192.168.1.1</natdst>
        <rule>Example</rule>
        <srcloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</srcloc>
        <dstloc code="United States" cc="US">United States</dstloc>
        <app>Example</app>
        <vsys>Example</vsys>
        <from>Example</from>
        <to>Example</to>
        <inbound_if>Example</inbound_if>
        <outbound_if>Example</outbound_if>
        <logset>Example</logset>
        <time_received>Example</time_received>
        <sessionid>Example</sessionid>
        <repeatcnt>1</repeatcnt>
        <sport>123</sport>
        <dport>80</dport>
        <natsport>123</natsport>
        <natdport>80</natdport>
        <flags>123</flags>
        <flag-pcap>no</flag-pcap>
        <flag-flagged>no</flag-flagged>
        <flag-proxy>no</flag-proxy>
        <flag-url-denied>no</flag-url-denied>
        <flag-nat>yes</flag-nat>
        <captive-portal>no</captive-portal>
        <non-std-dport>no</non-std-dport>
        <transaction>no</transaction>
        <pbf-c2s>no</pbf-c2s>
        <pbf-s2c>no</pbf-s2c>
        <temporary-match>no</temporary-match>
        <sym-return>no</sym-return>
        <decrypt-mirror>no</decrypt-mirror>
        <proto>tcp</proto>
        <action>Example</action>
        <cpadding>0</cpadding>
        <dg_hier_level_1>0</dg_hier_level_1>
        <dg_hier_level_2>0</dg_hier_level_2>
        <dg_hier_level_3>0</dg_hier_level_3>
        <dg_hier_level_4>0</dg_hier_level_4>
        <vsys_name>Legacy</vsys_name>
        <device_name>Example</device_name>
        <vsys_id>123</vsys_id>
        <bytes>463</bytes>
        <bytes_sent>393</bytes_sent>
        <bytes_received>70</bytes_received>
        <packets>4</packets>
        <start>Example</start>
        <elapsed>0</elapsed>
        <category>Example</category>
        <padding>0</padding>
        <pkts_sent>3</pkts_sent>
        <pkts_received>1</pkts_received>
        <session_end_reason>Example</session_end_reason>
        <action_source>Example</action_source>
      </entry>
      <entry logid="456">
        <domain>1</domain>
        <receive_time>2017/11/25 12:12:02</receive_time>
        <serial>Example</serial>
        <seqno>Example</seqno>
        <actionflags>Example</actionflags>
        <type>Example</type>
        <subtype>Example</subtype>
        <config_ver>0</config_ver>
        <time_generated>2017/11/25 12:12:00</time_generated>
        <src>192.168.1.1</src>
        <dst>192.168.1.2</dst>
        <rule>Example</rule>
        <dstuser>Example</dstuser>
        <srcloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</srcloc>
        <dstloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</dstloc>
        <app>Example</app>
        <vsys>Example</vsys>
        <from>Example</from>
        <to>Example</to>
        <inbound_if>Example</inbound_if>
        <logset>Example</logset>
        <time_received>Example</time_received>
        <sessionid>0</sessionid>
        <repeatcnt>1</repeatcnt>
        <sport>123</sport>
        <dport>123</dport>
        <natsport>0</natsport>
        <natdport>0</natdport>
        <flags>123</flags>
        <flag-pcap>no</flag-pcap>
        <flag-flagged>no</flag-flagged>
        <flag-proxy>no</flag-proxy>
        <flag-url-denied>no</flag-url-denied>
        <flag-nat>no</flag-nat>
        <captive-portal>no</captive-portal>
        <non-std-dport>no</non-std-dport>
        <transaction>no</transaction>
        <pbf-c2s>no</pbf-c2s>
        <pbf-s2c>no</pbf-s2c>
        <temporary-match>no</temporary-match>
        <sym-return>no</sym-return>
        <decrypt-mirror>no</decrypt-mirror>
        <proto>tcp</proto>
        <action>Example</action>
        <cpadding>0</cpadding>
        <dg_hier_level_1>0</dg_hier_level_1>
        <dg_hier_level_2>0</dg_hier_level_2>
        <dg_hier_level_3>0</dg_hier_level_3>
        <dg_hier_level_4>0</dg_hier_level_4>
        <vsys_name>Example</vsys_name>
        <device_name>Example</device_name>
        <vsys_id>0</vsys_id>
        <bytes>70</bytes>
        <bytes_sent>70</bytes_sent>
        <bytes_received>0</bytes_received>
        <packets>1</packets>
        <start>Example</start>
        <elapsed>0</elapsed>
        <category>Example</category>
        <padding>0</padding>
        <pkts_sent>1</pkts_sent>
        <pkts_received>0</pkts_received>
        <session_end_reason>Example</session_end_reason>
        <action_source>Example</action_source>
      </entry>
      <entry logid="789">
        <domain>1</domain>
        <receive_time>2017/11/25 12:12:02</receive_time>
        <serial>Example</serial>
        <seqno>Example</seqno>
        <actionflags>Example</actionflags>
        <type>Example</type>
        <subtype>Example</subtype>
        <config_ver>0</config_ver>
        <time_generated>2017/11/25 12:12:00</time_generated>
        <src>192.168.1.1</src>
        <dst>192.168.1.2</dst>
        <rule>Example</rule>
        <srcuser>Example</srcuser>
        <dstuser>Example</dstuser>
        <srcloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</srcloc>
        <dstloc code="10.0.0.0-10.255.255.255" cc="10.0.0.0-10.255.255.255">10.0.0.0-10.255.255.255</dstloc>
        <app>Example</app>
        <vsys>Example</vsys>
        <from>Example</from>
        <to>Example</to>
        <inbound_if>Example</inbound_if>
        <outbound_if>Example</outbound_if>
        <logset>Example</logset>
        <time_received>Example</time_received>
        <sessionid>Example</sessionid>
        <repeatcnt>1</repeatcnt>
        <sport>123</sport>
        <dport>123</dport>
        <natsport>0</natsport>
        <natdport>0</natdport>
        <flags>Example</flags>
        <flag-pcap>no</flag-pcap>
        <flag-flagged>no</flag-flagged>
        <flag-proxy>no</flag-proxy>
        <flag-url-denied>no</flag-url-denied>
        <flag-nat>no</flag-nat>
        <captive-portal>no</captive-portal>
        <non-std-dport>no</non-std-dport>
        <transaction>no</transaction>
        <pbf-c2s>no</pbf-c2s>
        <pbf-s2c>no</pbf-s2c>
        <temporary-match>no</temporary-match>
        <sym-return>no</sym-return>
        <decrypt-mirror>no</decrypt-mirror>
        <proto>no</proto>
        <action>no</action>
        <cpadding>0</cpadding>
        <dg_hier_level_1>0</dg_hier_level_1>
        <dg_hier_level_2>0</dg_hier_level_2>
        <dg_hier_level_3>0</dg_hier_level_3>
        <dg_hier_level_4>0</dg_hier_level_4>
        <vsys_name>Example</vsys_name>
        <device_name>Example</device_name>
        <vsys_id>0</vsys_id>
        <bytes>299</bytes>
        <bytes_sent>104</bytes_sent>
        <bytes_received>195</bytes_received>
        <packets>2</packets>
        <start>Example</start>
        <elapsed>0</elapsed>
        <category>Example</category>
        <padding>0</padding>
        <pkts_sent>1</pkts_sent>
        <pkts_received>1</pkts_received>
        <session_end_reason>Example</session_end_reason>
        <action_source>Example</action_source>
      </entry>
    </logs>
  </log>
</result></response>

I would like the data to fit into a dataframe so I can write it to a csv with the following headers:

logid
receive_time
type
src dst rule
srcuser
srcloc code
src_cc  *NEW HEADER*
dstloc code
dst_cc  *NEW HEADER*
app
from
to
repeatcnt
sport
dport
proto
action
bytes
bytes_sent
bytes_received
packets start
elapsed category
pkts_sent
pkts_received
session_end_reason
action_source

Here is an image of the way the table should look (Obviously needs all the data inserted):

Table

I was able to get this partially working with a for loop,  but then i'd need an additional 29 loops and 29 df conversions to concat the remaining headers/data:

import xml.etree.ElementTree as ET
import pandas as pd

tree = ET.parse("My_Data.xml")

a = []
b = []

for src in tree.findall('.//src'):
    a.append({'Source': src.text})

for domain in tree.findall('.//domain'):
    b.append({'Domain': domain.text})

df = pd.DataFrame(a)

df1 = pd.DataFrame(b)

result = pd.concat([df,df1], axis=1)

This is my very first post. I have looked through this site for years and it has helped me a ton. Thank you all for your help and hard work. Please let me know if you need additional information.

UPDATE

I am also having an issue with tags that do not exist in every response. For example, if 'type' didn't exist in the very first response, it would not be added to the header. If the second xml response contains this tag, it will throw an error: ValueError: dict contains fields not in fieldnames: 'type'

UPDATED CODE

This code posted in one of the responses works great, just need to modify it to work with the update above.

FINAL UPDATE

The code below works 100% for my use-case. You can see the full explanation in the selected answer within the comments section.

import csv
import xml.etree.ElementTree as et
from collections import OrderedDict

doc = et.parse('LogEntryCSV.xml')

csv_data = []

fields =  ['logid', 'receive_time', 'type', 'src', 'dst', 'rule',
           'srcuser', 'srcloc', 'dstloc', 'app', 'from', 'to', 'repeatcnt',
           'sport', 'dport', 'proto', 'action', 'bytes', 'bytes_sent',
           'bytes_received', 'packets', 'start', 'elapsed', 'category',
           'pkts_sent', 'pkts_received', 'session_end_reason', 'action_source']

for elem in doc.findall('.//entry'):
    inner_dict = OrderedDict({k:None for k in fields})   # PRE-POPULATES TEMP DICT

    inner_dict['logid'] = elem.attrib['logid']

    for item in elem.findall('.//*'):
        if item.tag in fields:
            if item.tag=='srcloc':
                inner_dict['scrloc code'] = item.attrib['code']
                inner_dict['scr_cc'] = item.attrib['cc']

            elif item.tag=='dstloc':
                inner_dict['dstloc code'] = item.attrib['code']
                inner_dict['dst_cc'] = item.attrib['cc']

            else:
                inner_dict[item.tag] = item.text

    csv_data.append(inner_dict)

with open('Output.csv', 'w', newline='') as f:
    w = csv.DictWriter(f, csv_data[0].keys())
    w.writeheader()
    w.writerows(csv_data)

Body:
Consider using containers like list of dictionaries that are assigned within a for loop iteration through each child of entry. For attributes, if conditionals are used to parse the attribute instead of text value. OrderedDict is used to keep keys intact as they are filled in. No need for pandas as you should leave the library for actual data analysis not data wrangling.

import csv
import xml.etree.ElementTree as et
from collections import OrderedDict

doc = et.parse('LogEntryCSV.xml')

csv_data = []

fields =  ['logid', 'receive_time', 'type', 'src', 'dst', 'rule',
           'srcuser', 'srcloc', 'dstloc', 'app', 'from', 'to', 'repeatcnt',
           'sport', 'dport', 'proto', 'action', 'bytes', 'bytes_sent',
           'bytes_received', 'packets', 'start', 'elapsed', 'category',
           'pkts_sent', 'pkts_received', 'session_end_reason', 'action_source']

for elem in doc.findall('.//entry'):
    inner_dict = OrderedDict({k:None for k in fields})   # PRE-POPULATES TEMP DICT

    inner_dict['logid'] = elem.attrib['logid']

    for item in elem.findall('.//*'):
        if item.tag in fields:
            if item.tag=='srcloc':
                inner_dict['scrloc code'] = item.attrib['code']
                inner_dict['scr_cc'] = item.attrib['cc']

            elif item.tag=='dstloc':
                inner_dict['dstloc code'] = item.attrib['code']
                inner_dict['dst_cc'] = item.attrib['cc']

            else:
                inner_dict[item.tag] = item.text

    csv_data.append(inner_dict)

with open('Output.csv', 'w', newline='') as f:
    w = csv.DictWriter(f, csv_data[0].keys())
    w.writeheader()
    w.writerows(csv_data)


来源: stackexchange

问:
Efficiently return words that match, or whose synonym(s), match a keyword
I have a database of industry-specific terms, each of which may have zero or more synonyms.  Users of the system can search for terms by keyword and the results should include any term that contains the keyword or that has at least one synonym that contains the keyword.  The result should then include the term and ONLY ONE of the matching synonyms.

Here's the setup... I have a term table with 2 fields: id and term.  I also have a synonym table with 3 fields: id, termId, and synonym.  So there would data like:

```<code>term Table
id | term
-- | -----
1  | dog
2  | cat
3  | bird

synonym Table
id | termId | synonym
-- | ------ | --------
1  | 1      | canine
2  | 1      | man's best friend
3  | 2      | feline
</code>```

A keyword search for (the letter) "i" should return the following as a result:

```<code>id | term   | synonym
-- | ------ | --------
1  | dog    | canine     <- because of the "i" in "canine"
2  | cat    | feline     <- because of the "i" in "feline"
3  | bird   |            <- because of the "i" in "bird"
</code>```

Notice how, even though both "dog" synonyms contain the letter "i", only one was returned in the result (doesn't matter which one).

Because I need to return all matches from the term table regardless of whether or not there's a synonym and I need no more than 1 matching synonym, I'm using an OUTER APPLY as follows:

```<code><!-- language: sql -->

SELECT
    term.id,
    term.term,
    synonyms.synonym
FROM
    term
    OUTER APPLY (
            SELECT
                TOP 1
                term.id,
                synonym.synonym
            FROM
                synonym
            WHERE
                term.id = synonym.termId
                AND synonym.synonym LIKE @keyword
        ) AS synonyms
WHERE
    term.term LIKE @keyword
    OR synonyms.synonym LIKE @keyword
</code>```

There are indexes on term.term, synonym.termId and synonym.synonym.  @Keyword is always something like '%foo%'.  The problem is that, with close to 50,000 terms (not that much for databases, I know, but...), the performance is horrible.  Any thoughts on how this can be done more efficiently?

Just a note, one thing I had thought to try was flattening the synonyms into a comma-delimited list in the term table so that I could get around the OUTER APPLY.  Unfortunately though, that list can easily exceed 900 characters which would then prevent SQL Server from adding an index to that column.  So that's a no-go.

Thanks very much in advance.

答:
You've got a lot of unnecessary logic in there. There's no telling how SQL server is creating an execution path. It's simpler and more efficient to split this up into two separate db calls and then merge them in your code:

Get matches based on synonyms:

```<code>SELECT
 term.id
,term.term
,synonyms.synonym
FROM
 term
 INNER JOIN synonyms ON term.termId = synonyms.termId
WHERE
 synonyms.synonym LIKE @keyword
</code>```

Get matches based on terms:

```<code>SELECT
 term.id
,term.term
FROM
 term
WHERE
 term.term LIKE @keyword
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a database of industry-specific terms, each of which may have zero or more synonyms.  Users of the system can search for terms by keyword and the results should include any term that contains the keyword or that has at least one synonym that contains the keyword.  The result should then include the term and ONLY ONE of the matching synonyms.

Here's the setup... I have a term table with 2 fields: id and term.  I also have a synonym table with 3 fields: id, termId, and synonym.  So there would data like:

term Table
id | term
-- | -----
1  | dog
2  | cat
3  | bird

synonym Table
id | termId | synonym
-- | ------ | --------
1  | 1      | canine
2  | 1      | man's best friend
3  | 2      | feline

A keyword search for (the letter) "i" should return the following as a result:

id | term   | synonym
-- | ------ | --------
1  | dog    | canine     <- because of the "i" in "canine"
2  | cat    | feline     <- because of the "i" in "feline"
3  | bird   |            <- because of the "i" in "bird"

Notice how, even though both "dog" synonyms contain the letter "i", only one was returned in the result (doesn't matter which one).

Because I need to return all matches from the term table regardless of whether or not there's a synonym and I need no more than 1 matching synonym, I'm using an OUTER APPLY as follows:

SELECT
    term.id,
    term.term,
    synonyms.synonym
FROM
    term
    OUTER APPLY (
            SELECT
                TOP 1
                term.id,
                synonym.synonym
            FROM
                synonym
            WHERE
                term.id = synonym.termId
                AND synonym.synonym LIKE @keyword
        ) AS synonyms
WHERE
    term.term LIKE @keyword
    OR synonyms.synonym LIKE @keyword

There are indexes on term.term, synonym.termId and synonym.synonym.  @Keyword is always something like '%foo%'.  The problem is that, with close to 50,000 terms (not that much for databases, I know, but...), the performance is horrible.  Any thoughts on how this can be done more efficiently?

Just a note, one thing I had thought to try was flattening the synonyms into a comma-delimited list in the term table so that I could get around the OUTER APPLY.  Unfortunately though, that list can easily exceed 900 characters which would then prevent SQL Server from adding an index to that column.  So that's a no-go.

Thanks very much in advance.

Body:
You've got a lot of unnecessary logic in there. There's no telling how SQL server is creating an execution path. It's simpler and more efficient to split this up into two separate db calls and then merge them in your code:

Get matches based on synonyms:

SELECT
 term.id
,term.term
,synonyms.synonym
FROM
 term
 INNER JOIN synonyms ON term.termId = synonyms.termId
WHERE
 synonyms.synonym LIKE @keyword

Get matches based on terms:

SELECT
 term.id
,term.term
FROM
 term
WHERE
 term.term LIKE @keyword


问:
How to position image to be directly vertically centered between two elements
I am trying to get the Texas icon directly centered between the span and h1 element.

Here is the Screen Capture

I tried googling but I think I might be phrasing what I need poorly. Is it that I have to adjust the padding and margin in css? I just want to move the icon down the y-axis.

Thank you

```<code> <header id="top" class="main-header">
      <span class="title">Keep it Weird in</span>
   <div>
    <img class="texas-icon" src="https://image.ibb.co/cGRVFG/texasicon_1.png" alt="texasicon_1" border="0"></a>
      </div>
      <h1>Austin</h1>

    .main-header {
  padding-top: 170px;
  height: 850px;
  background: linear-gradient(lightblue, transparent 90%),
              linear-gradient(0deg, #fff, transparent),
              #ffa949 url('https://media.giphy.com/media/3ohs7I9ho0H4dfeP7y/giphy.gif') no-repeat center;

  background-size: cover;

}

.title {
  color: white;
  font-size: 1.625rem; /* 26px/16px */
  letter-spacing: .065em;
  font-weight: 200px;
  padding-bottom: 10px;
}
h1 {
  font-size: 12.5rem; /* 90px/16px  */
  color: rgba(255, 255, 255, 1);
  text-transform: capitalize;
  font-weight: normal;
  text-align: center;
  line-height: 1.3;
  margin: 12px 0px 0px;
     }
</code>```

答:
I think text-align:center is enough in your case, then simply play with margin of elements to create the spaces :

header {
  background: blue;
  text-align: center;
  color: #fff;
  max-height: 380px;
  padding: 50px 25px 0px;
}

.title {
  margin: 5px 0;
  font-size: 1.3rem;
  border: none;
  display: inline-block;
}

h1 {
  margin: 10px 0;
  font-size: 5rem;
  line-height: 1.1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header id="top" class="main-header">
  <span class="title">Keep it Weird in</span>
  <div>
    <img class="texas-icon" src="https://image.ibb.co/cGRVFG/texasicon_1.png" alt="texasicon_1" border="0">
  </div>
  <h1>Austin</h1>
</header></code>```

Body:
I am trying to get the Texas icon directly centered between the span and h1 element.

Here is the Screen Capture

I tried googling but I think I might be phrasing what I need poorly. Is it that I have to adjust the padding and margin in css? I just want to move the icon down the y-axis.

Thank you

      Keep it Weird in

Austin

    .main-header {
  padding-top: 170px;
  height: 850px;
  background: linear-gradient(lightblue, transparent 90%),
              linear-gradient(0deg, #fff, transparent),
              #ffa949 url('https://media.giphy.com/media/3ohs7I9ho0H4dfeP7y/giphy.gif') no-repeat center;

  background-size: cover;

}

.title {
  color: white;
  font-size: 1.625rem; /* 26px/16px */
  letter-spacing: .065em;
  font-weight: 200px;
  padding-bottom: 10px;
}
h1 {
  font-size: 12.5rem; /* 90px/16px  */
  color: rgba(255, 255, 255, 1);
  text-transform: capitalize;
  font-weight: normal;
  text-align: center;
  line-height: 1.3;
  margin: 12px 0px 0px;
     }

Body:
I think text-align:center is enough in your case, then simply play with margin of elements to create the spaces :

header {
  background: blue;
  text-align: center;
  color: #fff;
  max-height: 380px;
  padding: 50px 25px 0px;
}

.title {
  margin: 5px 0;
  font-size: 1.3rem;
  border: none;
  display: inline-block;
}

h1 {
  margin: 10px 0;
  font-size: 5rem;
  line-height: 1.1;
}

<header id="top" class="main-header">
  <span class="title">Keep it Weird in</span>
  <div>
    <a href=""><img class="texas-icon" src="https://image.ibb.co/cGRVFG/texasicon_1.png" alt="texasicon_1" border="0"></a>
  </div>
  <h1>Austin</h1>
</header>


问:
How to print a file from VsCode?
I want to send the file I'm currently editing to a printer, like I did in Notepad++ for example.
I havn't found any hint on a print command. Is it not possible ?</p>

答:
Now you can install addon for VS Code - search "PrintCode".

Note that the repository for this extension was last updated in February 2018 with numerous issues outstanding.

Title: How to print a file from VsCode?

ContentLicense: CC BY-SA 4.0


问:
SWIG - Java Proxy Class Array Parameter
I thought that this would be a simple problem but I have had some difficulty finding an answer.

I have a struct defined in C++, let's say:

```<code>struct MyStruct
{
  int a;
  int b;
};
</code>```

This gets wrapped into Java proxy class MyStruct by SWIG.  I have a function in C++ which takes an array of struct MyStructs:

```<code>void myFunction(struct MyStruct arg[], int amount);
</code>```

SWIG sees a pointer parameter and therefore generates the Java wrapper of the function to use a single MyStruct object as its parameter:

```<code>void myFunction(MyStruct arg, int amount) { /**/ }
</code>```

How do I get SWIG to generate the Java function to take an array of MyStruct Java objects?  I have been able to figure it out for arrays of primitive types but have not found a way to get it working for custom wrapped types.

So my desired Java function signature would be this:

```<code>void myFunction(MyStruct[] arg, int amount);
</code>```

Edit: Updated wording to use proper SWIG nomenclature of proxy classes.

答:
I was able to create a working solution using an intermediary array class generated using %array_class from carrays.i along with in and javain typemaps.  A complete working example with the solution can be found in my gist.

If anyone can come up with a better solution or improvements then I would be much appreciated.  A drawback of my solution is that you would need to create an additional Java array proxy class for each different proxy class that you wanted to use in this way, which could clutter up the Java API.  This could be improved slightly by making the array proxy classes package-private using the javaclassmodifiers typemap.

Title: SWIG - Java Proxy Class Array Parameter

Body:
I thought that this would be a simple problem but I have had some difficulty finding an answer.

I have a struct defined in C++, let's say:

struct MyStruct
{
  int a;
  int b;
};

This gets wrapped into Java proxy class MyStruct by SWIG.  I have a function in C++ which takes an array of struct MyStructs:

void myFunction(struct MyStruct arg[], int amount);

SWIG sees a pointer parameter and therefore generates the Java wrapper of the function to use a single MyStruct object as its parameter:

void myFunction(MyStruct arg, int amount) { /**/ }

How do I get SWIG to generate the Java function to take an array of MyStruct Java objects?  I have been able to figure it out for arrays of primitive types but have not found a way to get it working for custom wrapped types.

So my desired Java function signature would be this:

void myFunction(MyStruct[] arg, int amount);

Edit: Updated wording to use proper SWIG nomenclature of proxy classes.


问:
Mongoose schema not working with nested object arrays (Node.js)
I have created a simple Mongo database on mLab, and I want to print the content on my console using Node.js and Mongoose, but I'm not able to figure out what is wrong with my schema (or something else maybe?). It is not able to print nested object data.

Here is my database structure:

```<code>{
    "_id": {
        "$oid": "5a26d0a8f36d280fefe443ed"
    },
    "housename": "my sweet home",
    "rooms": [
        {
            "roomname": "kitchen",
            "appliance": "fridge"
        },
        {
            "roomname": "bedroom",
            "appliance": "lamp"
        }
    ]
}
</code>```

I am trying to print this content like this:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userDataSchema = new Schema({housename: String, rooms: [{roomname: String, appliance: String}] }, {collection: 'testcollection'});
var userData = mongoose.model('userData', userDataSchema);

var mongoDB = 'mongodb://homeuser:homeuser@ds129776.mlab.com:29776/homedb';
mongoose.connect(mongoDB, {
  useMongoClient: true
});
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

userData.find({}, function(err, data) {
    console.log(data);
});
</code>```

The problem is, the console is not printing the nested rooms objects:

```<code>VSHANDIL-M-60PS:mongoclient vshandil$ node mongoclient.js
[ { _id: 5a26d0a8f36d280fefe443ed,
    housename: 'my sweet home',
    rooms: [ [Object], [Object] ] } ]
</code>```

Can anyone please help me figure out what might be going wrong? I am trying to follow the following doc:

http://mongoosejs.com/docs/guide.html

Thanks for any help!

答:
It is just console.log behavior.
Try console.log(JSON.stringify(data)); it will give you full object.

Body:
I have created a simple Mongo database on mLab, and I want to print the content on my console using Node.js and Mongoose, but I'm not able to figure out what is wrong with my schema (or something else maybe?). It is not able to print nested object data.

Here is my database structure:

{
    "_id": {
        "$oid": "5a26d0a8f36d280fefe443ed"
    },
    "housename": "my sweet home",
    "rooms": [
        {
            "roomname": "kitchen",
            "appliance": "fridge"
        },
        {
            "roomname": "bedroom",
            "appliance": "lamp"
        }
    ]
}

I am trying to print this content like this:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userDataSchema = new Schema({housename: String, rooms: [{roomname: String, appliance: String}] }, {collection: 'testcollection'});
var userData = mongoose.model('userData', userDataSchema);

var mongoDB = 'mongodb://homeuser:homeuser@ds129776.mlab.com:29776/homedb';
mongoose.connect(mongoDB, {
  useMongoClient: true
});
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

userData.find({}, function(err, data) {
    console.log(data);
});

The problem is, the console is not printing the nested rooms objects:

VSHANDIL-M-60PS:mongoclient vshandil$ node mongoclient.js
[ { _id: 5a26d0a8f36d280fefe443ed,
    housename: 'my sweet home',
    rooms: [ [Object], [Object] ] } ]

Can anyone please help me figure out what might be going wrong? I am trying to follow the following doc:

http://mongoosejs.com/docs/guide.html

Thanks for any help!


问:
Confusion over C++ pointer and reference topic
What is the difference between the following parameter passing mechanisms in C++?

```<code>void foo(int &x)
void foo(int *x)
void foo(int **x)
void foo(int *&x)
</code>```

I'd like to know in which case the parameter is being passed by value or passed by reference.

答:
Just adding: I think your spacing is misleading. Maybe things get a bit clearer if you change it.

The , &, * and so on is part of the type, so keep it with the type:

```<code>void foo(int& x)
void foo(int* x)
void foo(int** x)
void foo(int*& x)
</code>```

int& is an reference to an int, int* is a pointer to an int, int** is a pointer to an pointer to an int, and so on.
You still need to read the types from right to left - int*& being a reference to an pointer to an int. But that's consistent.

I think this is easier to read and represents better what is meant.

ContentLicense: CC BY-SA 2.5

Body:
What is the difference between the following parameter passing mechanisms in C++?

void foo(int &x)
void foo(int *x)
void foo(int **x)
void foo(int *&x)

I'd like to know in which case the parameter is being passed by value or passed by reference.

Body:
Just adding: I think your spacing is misleading. Maybe things get a bit clearer if you change it.

The , &, * and so on is part of the type, so keep it with the type:

void foo(int& x)
void foo(int* x)
void foo(int** x)
void foo(int*& x)

int& is an reference to an int, int* is a pointer to an int, int** is a pointer to an pointer to an int, and so on.
You still need to read the types from right to left - int*& being a reference to an pointer to an int. But that's consistent.

I think this is easier to read and represents better what is meant.


问:
Does Firebase Cloud Messaging provide a Graphical User Interface to see, manage and monitor device topic subscriptions?
I am already obtaining successfully the Firebase Cloud Messaging (FCM) device token by using FirebaseInstanceId.getInstance().getToken(). I used the following code to subscribe the client app to a topic:

```<code>String topic = "toronto";
FirebaseMessaging.getInstance().subscribeToTopic(topic);
</code>```

I assume everything is correct but in order to confirm, I would like to have a Graphical User Interface (GUI) provided by FCM to manage, monitor and see all of the devices that are subscribed to specific topics. With the code I used, I would expect to see the topic "toronto", and at least one device subscribed to that topic, for example by showing the FCM device token.

I was reading at https://developers.google.com/instance-id/reference/server#get_information_about_app_instances how it is possible to get information about app instances to find out details about a client app instance's subscriptions, including each topic name and subscribe date, but does FCM provide a GUI to see that?

UPDATE 1:

I was able to subscribe devices to topics and unsubscribe devices from topics. But when I want to confirm/monitor that a device was subscribed successfully, I am using this for example (for privacy I changed values of keys and tokens):

```<code>C:\curl>curl -X GET -k --header "Authorization: key=[My key]" "https://iid.googleapis.com/iid/info/[My device token]?details=true"
{"applicationVersion":"22","connectDate":"2017-12-05","attestStatus":"NOT_ROOTED","application":"com.[My app]","scope":"*","authorizedEntity":"[My app ID]","rel":{"topics":{"San-salvador":{"addDate":"2017-12-05"}}},"connectionType":"WIFI","appSigner":"[My signature]","platform":"ANDROID"}
C:\curl>
</code>```

I was expecting Firebase Cloud Messaging to provide a Graphical User Interface with a dashboard, charts and reports to see the topics that have been created and the list and number of devices subscribed to each of the topics, something similar to the Google Analytics reports, maybe even with maps to see where devices are subscribing from or anything visual that can help to visualize and monitor topic subscriptions. Instead, I am having to do everything with cURL with code similar to what I am showing in this UPDATE 1. I am surprised Firebase Cloud Messaging does not provide a GUI, since the tool comes from Google and they could easily provide a dashboard or something similar to Google Analytics.

答:
FCM currently doesn't have a GUI that displays the list/count of topics you have or the subscribers (count/registration tokens) the topic has.

At most, you could use the Instance ID API (the one from your post) to check a single registration token to which topics it is subscribed to. However, do note that the Instance ID API was meant to be used on your Server side.

Other than that, you will have to implement your own mapping with the topics (which tokens are subscribed to it).

Kinda similar/possibly helpful posts:

Firebase Cloud Messaging - Check existing or available Topics

Count subscribers of a topic in Firebase Cloud Messaging

Android/Firebase - Check to see if you are subscribed to topic

Firebase Cloud Messaging - Managing Registration Tokens

Body:
I am already obtaining successfully the Firebase Cloud Messaging (FCM) device token by using FirebaseInstanceId.getInstance().getToken(). I used the following code to subscribe the client app to a topic:

String topic = "toronto";
FirebaseMessaging.getInstance().subscribeToTopic(topic);

I assume everything is correct but in order to confirm, I would like to have a Graphical User Interface (GUI) provided by FCM to manage, monitor and see all of the devices that are subscribed to specific topics. With the code I used, I would expect to see the topic "toronto", and at least one device subscribed to that topic, for example by showing the FCM device token.

I was reading at https://developers.google.com/instance-id/reference/server#get_information_about_app_instances how it is possible to get information about app instances to find out details about a client app instance's subscriptions, including each topic name and subscribe date, but does FCM provide a GUI to see that?

UPDATE 1:

I was able to subscribe devices to topics and unsubscribe devices from topics. But when I want to confirm/monitor that a device was subscribed successfully, I am using this for example (for privacy I changed values of keys and tokens):

C:\curl>curl -X GET -k --header "Authorization: key=[My key]" "https://iid.googleapis.com/iid/info/[My device token]?details=true"
{"applicationVersion":"22","connectDate":"2017-12-05","attestStatus":"NOT_ROOTED","application":"com.[My app]","scope":"*","authorizedEntity":"[My app ID]","rel":{"topics":{"San-salvador":{"addDate":"2017-12-05"}}},"connectionType":"WIFI","appSigner":"[My signature]","platform":"ANDROID"}
C:\curl>

I was expecting Firebase Cloud Messaging to provide a Graphical User Interface with a dashboard, charts and reports to see the topics that have been created and the list and number of devices subscribed to each of the topics, something similar to the Google Analytics reports, maybe even with maps to see where devices are subscribing from or anything visual that can help to visualize and monitor topic subscriptions. Instead, I am having to do everything with cURL with code similar to what I am showing in this UPDATE 1. I am surprised Firebase Cloud Messaging does not provide a GUI, since the tool comes from Google and they could easily provide a dashboard or something similar to Google Analytics.


问:
Navigation with toolbar up arrow restarts the app but android built-in arrow button works
Please assist.

Edited to ask a more simple straight forward questions

I have three activities (A, B and C) that each host a fragment.
Navigation with up arrow on toolbar is not working when navigating from fragment C to fragment B. However, navigation with the built-in android back arrow, works fine.

Comparing the logging of the lifecycle methods below with the two different back navigations, why does it get destroyed, detached and recreated (where it crashes and restarts the app because the arguments bundle is empty) with the toolbar back navigation, but goes straight from stop to start on the built-in android back navigation?

Order of activity and fragment lifecycle on toolbar up arrow

```<code>11-30 19:41:15.491 2070-2086/? I/PgedBinderListener: kstate callback type:16 value1=1433 value2=CALLED
11-30 19:41:15.537 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreate Called
11-30 19:41:15.541 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreateView Called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroyView Called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStart Called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onStart() called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onResume() called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onResume Called
11-30 19:41:17.321 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onPause() called
11-30 19:41:17.878 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStopCalled
11-30 19:41:17.878 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onStop() called
11-30 19:41:18.838 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroyView Called
11-30 19:41:18.839 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroy Called
11-30 19:41:18.839 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDetached Called
11-30 19:41:18.839 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onDestroy() called
11-30 19:41:18.874 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreate Called
</code>```

Order of activity and fragment lifecycle with android built-in back arrow

```<code>12-02 22:31:10.355 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreate Called
12-02 22:31:10.357 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreateView Called
12-02 22:31:10.420 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroyView Called
12-02 22:31:10.420 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStart Called
12-02 22:31:10.420 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onStart() called
12-02 22:31:10.421 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onResume() called
12-02 22:31:10.421 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onResume Called
12-02 22:31:13.499 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onPause() called
12-02 22:31:14.122 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStopCalled
12-02 22:31:14.122 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onStop() called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStart Called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onStart() called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onResume() called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onResume Called
</code>```

Abstract class for hosting activities

```<code>public abstract class SingleFragmentActivity extends AppCompatActivity {

    protected abstract Fragment createFragment();

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

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_container);

        if (fragment == null) {
            fragment = createFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_container, fragment)
                    .commit();
        }
    }

}
</code>```

Activity B

```<code>public class ChildDetailsActivity extends SingleFragmentActivity {

    public static final String EXTRA_CHILD_ID =
            "com.navsaria.keeran.clinicbook.child_id";
    public static final String TAG = "child_details_activity";

    public static Intent newIntent(Context packagedContext, UUID childId) {
        Intent intent = new Intent(packagedContext, ChildDetailsActivity.class);
        intent.putExtra(EXTRA_CHILD_ID, childId);
        return intent;
    }

    @Override
    protected Fragment createFragment() {
        UUID childId = (UUID) getIntent().getSerializableExtra(EXTRA_CHILD_ID);
        return ChildDetailsFragment.newInstance(childId);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        Log.i(TAG, "onCreate() called");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "onStart() called");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume() called");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause() called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        String  uuid = getIntent().getSerializableExtra(EXTRA_CHILD_ID).toString();
        Log.i(TAG, "onStop() called" + uuid);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy() called");
    }
}
</code>```

Fragment B

```<code>public class ChildDetailsFragment extends Fragment{

    private RecyclerView mRecyclerView;
    private Child mChild;

    private static final String ARGS_ID = "child_id";
    private static final String SAVED_INSTANCE_STATE_UUID = "clinicbook.childdetailsfragment.mchildid";

    public static ChildDetailsFragment newInstance(UUID childId) {
        ChildDetailsFragment childDetailsFragment = new ChildDetailsFragment();

        Bundle args = new Bundle();
        args.putSerializable(ARGS_ID, childId);

        childDetailsFragment.setArguments(args);
        return childDetailsFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("ChildDetailsFragment", "onCreate Called");
        ChildList childList = ChildList.getChildList(getActivity());
        UUID childId = (UUID) getArguments().getSerializable(ARGS_ID);
        mChild = childList.getChild(childId);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_child_details, container, false);

        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(mChild.getFirstName() + " " + mChild.getLastName());

        mRecyclerView = (RecyclerView) v.findViewById(R.id.child_recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(new CategoryAdapter());

        return  v;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("ChildDetailsFragment", "onDestroy Called");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("ChildDetailsFragment", "fragment onStopCalled");
    }

    ///////////////////////////////////////////////////////////////
    //RecyclerView ViewHolder

    private class CategoryHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public CategoryHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.category_list_item, parent, false));
            ((LinearLayout) itemView).setOnClickListener(this);
        }

        public void bind(String category) {
            TextView categoryTitle = itemView.findViewById(R.id.category_title);
            categoryTitle.setText(category);
        }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), PersonalDataActivity.class);
            startActivity(intent);
        }
    }

    //RecyclerView ViewHolder
    ///////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////
    //RecyclerView Adapter

    private class CategoryAdapter extends RecyclerView.Adapter<CategoryHolder> {

        private final String[] mCategoryList = {
                "Personal Data",
                "Growth Measurements",
                "Growth Stages",
                "Immunisations",
                "Medications",
                "Allergies"
        };

        @Override
        public CategoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            return new CategoryHolder(inflater, parent);
        }

        @Override
        public void onBindViewHolder(CategoryHolder holder, int position) {
            String category = mCategoryList[position];
            holder.bind(category);
        }

        @Override
        public int getItemCount() {
            return mCategoryList.length;
        }
    }
    //RecyclerView Adapter
    ///////////////////////////////////////////////////////////////

}// End of Class ChildDetailsFragment
</code>```

Activity C

```<code>public class PersonalDataActivity extends SingleFragmentActivity {
    @Override
    protected Fragment createFragment() {
        return new PersonalDataFragment();
    }
}
</code>```

Fragment C
    public class PersonalDataFragment extends Fragment {

```<code>    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_personal_data, container, false);
        return v;
    }
}
</code>```

AndroidManifest.xml

```<code><activity android:name=".ChildrenActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name=".ChildDetailsActivity"
    android:parentActivityName=".ChildrenActivity">
</activity>
<activity android:name=".PersonalDataActivity"
    android:parentActivityName=".ChildDetailsActivity">
</activity>
</code>```

Stack Trace fatal error is as follows:

```<code>12-02 22:42:18.330 16037-16037/com.navsaria.keeran.clinicbook E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.navsaria.keeran.clinicbook, PID: 16037
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.navsaria.keeran.clinicbook/com.navsaria.keeran.clinicbook.ChildDetailsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.UUID.toString()' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2479)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:168)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:150)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5659)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.UUID.toString()' on a null object reference
                                                                                at com.navsaria.keeran.clinicbook.ChildList.getChild(ChildList.java:67)
                                                                                at com.navsaria.keeran.clinicbook.ChildDetailsFragment.onCreate(ChildDetailsFragment.java:50)
                                                                                at android.support.v4.app.Fragment.performCreate(Fragment.java:2339)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
                                                                                at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1109)
                                                                                at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:996)
                                                                                at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:99)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2364)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
                                                                                at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
                                                                                at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
                                                                                at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                                                                                at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
                                                                                at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                                                                                at com.navsaria.keeran.clinicbook.ChildDetailsActivity.onStart(ChildDetailsActivity.java:56)
                                                                                at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1241)
                                                                                at android.app.Activity.performStart(Activity.java:6392)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2442)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:168)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:150)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5659)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
</code>```

Test Device is Huawei P9 lite

答:
Found the solution:

Change the launchMode of ChildDetailsActivity in the AndroidManifest to "singleTop" so that the activity in the back stack receives the intent instead of a new activity being created.

```<code><activity android:name=".ChildDetailsActivity"
    android:parentActivityName=".ChildrenActivity"
    android:launchMode="singleTop">
</activity>
</code>```

Body:
Please assist.

Edited to ask a more simple straight forward questions

I have three activities (A, B and C) that each host a fragment.
Navigation with up arrow on toolbar is not working when navigating from fragment C to fragment B. However, navigation with the built-in android back arrow, works fine.

Comparing the logging of the lifecycle methods below with the two different back navigations, why does it get destroyed, detached and recreated (where it crashes and restarts the app because the arguments bundle is empty) with the toolbar back navigation, but goes straight from stop to start on the built-in android back navigation?

Order of activity and fragment lifecycle on toolbar up arrow

11-30 19:41:15.491 2070-2086/? I/PgedBinderListener: kstate callback type:16 value1=1433 value2=CALLED
11-30 19:41:15.537 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreate Called
11-30 19:41:15.541 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreateView Called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroyView Called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStart Called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onStart() called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onResume() called
11-30 19:41:15.607 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onResume Called
11-30 19:41:17.321 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onPause() called
11-30 19:41:17.878 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStopCalled
11-30 19:41:17.878 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onStop() called
11-30 19:41:18.838 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroyView Called
11-30 19:41:18.839 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroy Called
11-30 19:41:18.839 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDetached Called
11-30 19:41:18.839 13374-13374/com.navsaria.keeran.clinicbook I/child_details_activity: onDestroy() called
11-30 19:41:18.874 13374-13374/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreate Called

Order of activity and fragment lifecycle with android built-in back arrow

12-02 22:31:10.355 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreate Called
12-02 22:31:10.357 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onCreateView Called
12-02 22:31:10.420 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onDestroyView Called
12-02 22:31:10.420 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStart Called
12-02 22:31:10.420 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onStart() called
12-02 22:31:10.421 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onResume() called
12-02 22:31:10.421 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onResume Called
12-02 22:31:13.499 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onPause() called
12-02 22:31:14.122 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStopCalled
12-02 22:31:14.122 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onStop() called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onStart Called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onStart() called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/child_details_activity: onResume() called
12-02 22:31:27.380 16037-16037/com.navsaria.keeran.clinicbook I/ChildDetailsFragment: onResume Called

Abstract class for hosting activities

public abstract class SingleFragmentActivity extends AppCompatActivity {

    protected abstract Fragment createFragment();

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

        FragmentManager fm = getSupportFragmentManager();
        Fragment fragment = fm.findFragmentById(R.id.fragment_container);

        if (fragment == null) {
            fragment = createFragment();
            fm.beginTransaction()
                    .add(R.id.fragment_container, fragment)
                    .commit();
        }
    }

}

Activity B

public class ChildDetailsActivity extends SingleFragmentActivity {

    public static final String EXTRA_CHILD_ID =
            "com.navsaria.keeran.clinicbook.child_id";
    public static final String TAG = "child_details_activity";

    public static Intent newIntent(Context packagedContext, UUID childId) {
        Intent intent = new Intent(packagedContext, ChildDetailsActivity.class);
        intent.putExtra(EXTRA_CHILD_ID, childId);
        return intent;
    }

    @Override
    protected Fragment createFragment() {
        UUID childId = (UUID) getIntent().getSerializableExtra(EXTRA_CHILD_ID);
        return ChildDetailsFragment.newInstance(childId);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
        Log.i(TAG, "onCreate() called");
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "onStart() called");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume() called");

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause() called");
    }

    @Override
    protected void onStop() {
        super.onStop();
        String  uuid = getIntent().getSerializableExtra(EXTRA_CHILD_ID).toString();
        Log.i(TAG, "onStop() called" + uuid);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy() called");
    }
}

Fragment B

public class ChildDetailsFragment extends Fragment{

    private RecyclerView mRecyclerView;
    private Child mChild;

    private static final String ARGS_ID = "child_id";
    private static final String SAVED_INSTANCE_STATE_UUID = "clinicbook.childdetailsfragment.mchildid";

    public static ChildDetailsFragment newInstance(UUID childId) {
        ChildDetailsFragment childDetailsFragment = new ChildDetailsFragment();

        Bundle args = new Bundle();
        args.putSerializable(ARGS_ID, childId);

        childDetailsFragment.setArguments(args);
        return childDetailsFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i("ChildDetailsFragment", "onCreate Called");
        ChildList childList = ChildList.getChildList(getActivity());
        UUID childId = (UUID) getArguments().getSerializable(ARGS_ID);
        mChild = childList.getChild(childId);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_child_details, container, false);

        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(mChild.getFirstName() + " " + mChild.getLastName());

        mRecyclerView = (RecyclerView) v.findViewById(R.id.child_recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(new CategoryAdapter());

        return  v;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("ChildDetailsFragment", "onDestroy Called");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i("ChildDetailsFragment", "fragment onStopCalled");
    }

    ///////////////////////////////////////////////////////////////
    //RecyclerView ViewHolder

    private class CategoryHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        public CategoryHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.category_list_item, parent, false));
            ((LinearLayout) itemView).setOnClickListener(this);
        }

        public void bind(String category) {
            TextView categoryTitle = itemView.findViewById(R.id.category_title);
            categoryTitle.setText(category);
        }

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getActivity(), PersonalDataActivity.class);
            startActivity(intent);
        }
    }

    //RecyclerView ViewHolder
    ///////////////////////////////////////////////////////////////

    ///////////////////////////////////////////////////////////////
    //RecyclerView Adapter

    private class CategoryAdapter extends RecyclerView.Adapter<CategoryHolder> {

        private final String[] mCategoryList = {
                "Personal Data",
                "Growth Measurements",
                "Growth Stages",
                "Immunisations",
                "Medications",
                "Allergies"
        };

        @Override
        public CategoryHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            return new CategoryHolder(inflater, parent);
        }

        @Override
        public void onBindViewHolder(CategoryHolder holder, int position) {
            String category = mCategoryList[position];
            holder.bind(category);
        }

        @Override
        public int getItemCount() {
            return mCategoryList.length;
        }
    }
    //RecyclerView Adapter
    ///////////////////////////////////////////////////////////////

}// End of Class ChildDetailsFragment

Activity C

public class PersonalDataActivity extends SingleFragmentActivity {
    @Override
    protected Fragment createFragment() {
        return new PersonalDataFragment();
    }
}

Fragment C
    public class PersonalDataFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_personal_data, container, false);
        return v;
    }
}

AndroidManifest.xml

<activity android:name=".ChildrenActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name=".ChildDetailsActivity"
    android:parentActivityName=".ChildrenActivity">
</activity>
<activity android:name=".PersonalDataActivity"
    android:parentActivityName=".ChildDetailsActivity">
</activity>

Stack Trace fatal error is as follows:

12-02 22:42:18.330 16037-16037/com.navsaria.keeran.clinicbook E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.navsaria.keeran.clinicbook, PID: 16037
                                                                                java.lang.RuntimeException: Unable to start activity ComponentInfo{com.navsaria.keeran.clinicbook/com.navsaria.keeran.clinicbook.ChildDetailsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.UUID.toString()' on a null object reference
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2479)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:168)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:150)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5659)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)
                                                                                Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.util.UUID.toString()' on a null object reference
                                                                                at com.navsaria.keeran.clinicbook.ChildList.getChild(ChildList.java:67)
                                                                                at com.navsaria.keeran.clinicbook.ChildDetailsFragment.onCreate(ChildDetailsFragment.java:50)
                                                                                at android.support.v4.app.Fragment.performCreate(Fragment.java:2339)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1377)
                                                                                at android.support.v4.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1109)
                                                                                at android.support.v4.app.FragmentTransition.calculateFragments(FragmentTransition.java:996)
                                                                                at android.support.v4.app.FragmentTransition.startTransitions(FragmentTransition.java:99)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2364)
                                                                                at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2322)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2229)
                                                                                at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3221)
                                                                                at android.support.v4.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManager.java:3171)
                                                                                at android.support.v4.app.FragmentController.dispatchActivityCreated(FragmentController.java:192)
                                                                                at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:560)
                                                                                at android.support.v7.app.AppCompatActivity.onStart(AppCompatActivity.java:177)
                                                                                at com.navsaria.keeran.clinicbook.ChildDetailsActivity.onStart(ChildDetailsActivity.java:56)
                                                                                at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1241)
                                                                                at android.app.Activity.performStart(Activity.java:6392)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2442)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2539)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:168)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1378)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:150)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5659)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:822)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:712)

Test Device is Huawei P9 lite

Body:
Found the solution:

Change the launchMode of ChildDetailsActivity in the AndroidManifest to "singleTop" so that the activity in the back stack receives the intent instead of a new activity being created.

<activity android:name=".ChildDetailsActivity"
    android:parentActivityName=".ChildrenActivity"
    android:launchMode="singleTop">
</activity>


问:
how to get a subprocess to not get stuck if application crashes?
I am launching a series of subprocess one after the other, something like

```<code>for variables in my_list:
    proc = subprocess.Popen(**variables)
    proc.wait()
</code>```

however if one of them crashes Windows pops up a window saying that the program has stopped working; since the process hasn't been killed yet, the program waits until I click the "close program" button

I'm wondering if there is a way to tell Python to open this process without UI or make it so that if it crashes it doesn't pop up error reports. The documentation doesn't seem to address any of this.

I'm using python 2.7, so I can't make use of the timeout flag that is present in python 3.

答:
The error mode is inherited by child processes. Set it via ctypes. For example: </p>

```<code>import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

SEM_FAILCRITICALERRORS = 1
SEM_NOGPFAULTERRORBOX = 2

prev_error_mode = kernel32.SetErrorMode(SEM_FAILCRITICALERRORS |
                    SEM_NOGPFAULTERRORBOX)
</code>```

Body:
I am launching a series of subprocess one after the other, something like

for variables in my_list:
    proc = subprocess.Popen(**variables)
    proc.wait()

however if one of them crashes Windows pops up a window saying that the program has stopped working; since the process hasn't been killed yet, the program waits until I click the "close program" button

I'm wondering if there is a way to tell Python to open this process without UI or make it so that if it crashes it doesn't pop up error reports. The documentation doesn't seem to address any of this.

I'm using python 2.7, so I can't make use of the timeout flag that is present in python 3.

Body:
The error mode is inherited by child processes. Set it via ctypes. For example:

import ctypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

SEM_FAILCRITICALERRORS = 1
SEM_NOGPFAULTERRORBOX = 2

prev_error_mode = kernel32.SetErrorMode(SEM_FAILCRITICALERRORS |
                    SEM_NOGPFAULTERRORBOX)


问:
Selenium Python - Finding Elements by Class Name With Spaces
I'm writing a Python program that uses Selenium to navigate to and enter information into search boxes on an advanced search page. This website uses Javascript, and the IDs and Names for each search box change slightly each time the website is loaded, but the Class Names remain consistent. Class names are frequently reused though, so my goal is to use find_elements_by_class_name(classname) and then index through that list.

One box, for example, has the class name x-form-text x-form-field x-form-num-field x-form-empty-field, but I can't use this because selenium considers it a compound class name and throws an error. If I use just a portion of it, such as x-form-text, it can't find the element. My hope is to either find a way to allow the spaces or, if that can't be done, find a way to search for all elements whose class name contains a section of text without spaces, such as x-form-text.

Any help or thoughts would be greatly appreciated!

Edit:

I tried this code:

    quantminclass = 'x-form-text.x-form-field.x-form-num-field.x-form-empty-field'
    quantmin = '25'
    browser.find_elements_by_css_selector(quantminclass)[0].send_keys(quantmin)

But got an error that the list index was out of range, implying that it can't find anything. I inspected the element and that is definitely its class name, so I'm not sure how to proceed.

答:
Those are multiple classes, not a single class with spaces, just use all the classes together.

```<code>driver.find_element(By.CSS_SELECTOR, '.class1.class2.class3')
</code>```

In CSS selector a dot . is a class, you can concatenate any number class names

Body:
Those are multiple classes, not a single class with spaces, just use all the classes together.

driver.find_element(By.CSS_SELECTOR, '.class1.class2.class3')

In CSS selector a dot . is a class, you can concatenate any number class names


问:
Multiple instances of playing a video on one page using jQuery
I have some code that shows a cover image over a video, upon clicking said image it auto plays the video. Currently this code works for one video on one page (because it uses ID's).

The code is leaning on Froogaloop to control and play Vimeo.

Using jQuery how can I convert the following code so that it will work with  more than 1 video on a page (currently it breaks):

```<code>// Control Vimeo videos
var iframe = document.getElementById('video');

// $f == Froogaloop
var player = $f(iframe);

var playButton = document.getElementById("play-me");

playButton.addEventListener("click", function() {
  player.api("play");
    $('.bg-image').addClass('hide-me');

    setTimeout(function(){
        $('.bg-image').css('z-index','-1');
    }, 1000);
});
</code>```

This is my HTML:

```<code><div class="video-wrapper">
    <div class="bg-image" id="play-me">
       <span class="play">
         <i class="i-play"></i>
       </span>
    </div>
    <iframe src="" id="video"></iframe>
</div>
</code>```

答: How is the video set on place? Is hardcoded through html? I cant comment, this should be a comment... Btw, why the mix with jquery and plain javascript?</p>

Body:
I have some code that shows a cover image over a video, upon clicking said image it auto plays the video. Currently this code works for one video on one page (because it uses ID's).

The code is leaning on Froogaloop to control and play Vimeo.

Using jQuery how can I convert the following code so that it will work with  more than 1 video on a page (currently it breaks):

// Control Vimeo videos
var iframe = document.getElementById('video');

// $f == Froogaloop
var player = $f(iframe);

var playButton = document.getElementById("play-me");

playButton.addEventListener("click", function() {
  player.api("play");
    $('.bg-image').addClass('hide-me');

    setTimeout(function(){
        $('.bg-image').css('z-index','-1');
    }, 1000);
});

This is my HTML:


答:
Conver ids to classes:

```<code><div class="video-wrapper">
    <div class="bg-image" class="play-me">
       <span class="play">
         <i class="i-play"></i>
       </span>
    </div>
    <iframe src="" class="video"></iframe>
</div>
</code>```

and modify your js/jquery to this:

```<code>var playButton = $(".play-me");

playButton.get(0).addEventListener("click", function() {
    var iframe = $(this).next('.video').get(0),// or use closest() based on your condition
    player = $f(iframe);
    player.api("play");
    $(this).addClass('hide-me');

    setTimeout(function(){
        $(this).css('z-index','-1');
    }, 1000);
});
</code>```

IF
you had to add more videos inside the same .video-wrapper, use .closest() as i commented in top otherwise .next() will works fine.

Explanation:
With using $(this) make us confident that code will do changes just on that element we clicked not all.

Title: Multiple instances of playing a video on one page using jQuery

Body:
Conver ids to classes:

<div class="video-wrapper">
    <div class="bg-image" class="play-me">
       <span class="play">
         <i class="i-play"></i>
       </span>
    </div>
    <iframe src="" class="video"></iframe>
</div>

and modify your js/jquery to this:

var playButton = $(".play-me");

playButton.get(0).addEventListener("click", function() {
    var iframe = $(this).next('.video').get(0),// or use closest() based on your condition
    player = $f(iframe);
    player.api("play");
    $(this).addClass('hide-me');

    setTimeout(function(){
        $(this).css('z-index','-1');
    }, 1000);
});

IF
you had to add more videos inside the same .video-wrapper, use .closest() as i commented in top otherwise .next() will works fine.

Explanation:
With using $(this) make us confident that code will do changes just on that element we clicked not all.


问:
Trouble doing a bitwise xor + bit_count in mysql
I am trying to perform a comparison on hash values (hexadecimal strings of 16 characters). I have a MYSQL table that stores those values with a phash VARCHAR(16) column.
This is what I am trying to do:

```<code>SELECT phash, bit_count(phash ^ x'dda15873a3de013d') FROM mytable;
</code>```

But the bit_count + xor is not done correctly. Even for phash='dda15873a3de013d' I get 33 as a result whereas I should get 0 (the two hex are the same, so the xor should yield only zeros, hence a bit_count of 0.

What is wrong?
Thank you

Edit:
example here => http://sqlfiddle.com/#!9/d7f5c2/1/0

```<code>mysql> SELECT phash,BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de012d) from mytable limit 1;

+------------------+-----------------------------------------------------+
| phash            | BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de012d) |
+------------------+-----------------------------------------------------+
| dda15873a3de012d |                                                  33 |
+------------------+-----------------------------------------------------+
</code>```

答: CONV returns a string. You need to cast the result of CONV to UNSIGNED.

Body:
I am trying to perform a comparison on hash values (hexadecimal strings of 16 characters). I have a MYSQL table that stores those values with a phash VARCHAR(16) column.
This is what I am trying to do:

SELECT phash, bit_count(phash ^ x'dda15873a3de013d') FROM mytable;

But the bit_count + xor is not done correctly. Even for phash='dda15873a3de013d' I get 33 as a result whereas I should get 0 (the two hex are the same, so the xor should yield only zeros, hence a bit_count of 0.

What is wrong?
Thank you

Edit:
example here => http://sqlfiddle.com/#!9/d7f5c2/1/0

mysql> SELECT phash,BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de012d) from mytable limit 1;

+------------------+-----------------------------------------------------+
| phash            | BIT_COUNT(CONV(phash, 16, 10) ^ 0xdda15873a3de012d) |
+------------------+-----------------------------------------------------+
| dda15873a3de012d |                                                  33 |
+------------------+-----------------------------------------------------+


问:
How to replace variable name and variable value from string?
I have a Google Forms Prefilled URL

```<code>$input = "https://docs.google.com/forms/d/e/1FAIpQLSe8aZbfXa2IRRzK6hPTDKvAf_Oa8chTMrX8wkkYcuVHGs-vuA/viewform?usp=pp_url&entry.1064398956=NAME&entry.1318807391=TELEPHONE";
$pars = parse_url($input);
$values = $pars["query"];
$values = str_replace("entry.", "", $values);
$values = str_replace("usp=pp_url&", "", $values);
</code>```

With this code I get values as

```<code>1064398956=NAME&1318807391=TELEPHONE
</code>```

Because the numbers (entry id) are always different, I use default values (like NAME, TELEPHONE), and these would be storaged to mySQL database like this:

```<code>Id  ||  NAME       || VALUE
================================
1   || 1064398956  || 1318807391
</code>```

To upload a row to that mysql database I have the query:

```<code>    INSERT INTO TABLE (ID, NAME, VALUE) VALUES (1, $NAME, $VALUE)
</code>```

Based on the following string, how i can find values $NAME and $VALUE?

```<code>1064398956=NAME&1318807391=TELEPHONE
</code>```

答:
The @mario and @chris85 solution that worked:</p>

```<code>$string = '1064398956=NAME&1318807391=TELEPHONE';
parse_str($string, $output);
print_r(array_flip($output));
</code>```

Body:
I have a Google Forms Prefilled URL

$input = "https://docs.google.com/forms/d/e/1FAIpQLSe8aZbfXa2IRRzK6hPTDKvAf_Oa8chTMrX8wkkYcuVHGs-vuA/viewform?usp=pp_url&entry.1064398956=NAME&entry.1318807391=TELEPHONE";
$pars = parse_url($input);
$values = $pars["query"];
$values = str_replace("entry.", "", $values);
$values = str_replace("usp=pp_url&", "", $values);

With this code I get values as

1064398956=NAME&1318807391=TELEPHONE

Because the numbers (entry id) are always different, I use default values (like NAME, TELEPHONE), and these would be storaged to mySQL database like this:

Id  ||  NAME       || VALUE
================================
1   || 1064398956  || 1318807391

To upload a row to that mysql database I have the query:

    INSERT INTO TABLE (ID, NAME, VALUE) VALUES (1, $NAME, $VALUE)

Based on the following string, how i can find values $NAME and $VALUE?

1064398956=NAME&1318807391=TELEPHONE

Body:
The @mario and @chris85 solution that worked:

$string = '1064398956=NAME&1318807391=TELEPHONE';
parse_str($string, $output);
print_r(array_flip($output));