问:
How to derive sql columns from a XMLcolumn
I have a table named dbo.XMLData and one column in the table named XMLValue, a sample row in the table is below( basically its a XML value)

<GENERIC_ROUGHDRAFT xmlns="http://xactware.com/generic_roughdraft.xsd" majorVersion="28" minorVersion="300" transactionId="001SPL8">

  <COVERSHEET>
    <ESTIMATE_INFO estimateName="OSCAR_MURPHY" insuredName="Oscar Murphy" priceList="KYLO8X_JAN15" laborEff="Restoration/Service/Remodel" claimNumber="KBR-182015-13:18:46 MST" policyNumber="KBR1467216" typeOfLoss="Collapse" causeOfLoss="collapse" deprMat="1" deprNonMat="1" deprTaxes="1" recipientsXNAddress="XA.ONLINE.TEST" rotationTrade="Re Key\Lock Change" carrierId="2210000" estimateType="Structural" />
    <ADDRESSES>
      <ADDRESS type="Property" street="6467 N 7506 W" city="Louisville" state="KY" zip="40219" primary="1" />
      <ADDRESS type="Home" street="6467 N 7506 W" city="Louisville" state="KY" zip="40219" />
    </ADDRESSES>
    <PHONES>
      <PHONE type="Home" primary="1" phone="(800) 555-5765" />
      <PHONE type="Business" phone="(801) 555-2021" />
      <PHONE type="Cellular" phone="(808) 555-0202" />
    </PHONES>
    <CONTACTS>
      <CONTACT type="ClaimRep" name="John Deeter">
        <ADDRESSES>
          <ADDRESS type="Business" street="100 N 100 E" city="Orem" state="UT" zip="84062" primary="1" />
        </ADDRESSES>
        <PHONES>
          <PHONE primary="1" type="Business" phone="555-555-5554" />
        </PHONES>
      </CONTACT>
      <CONTACT type="Estimator" name="John Deeter">
        <ADDRESSES>
          <ADDRESS type="Business" street="100 N 100 E" city="Orem" state="UT" zip="84062" primary="1" />
        </ADDRESSES>
        <PHONES>
          <PHONE primary="1" type="Business" phone="555-555-5554" />
        </PHONES>
      </CONTACT>
    </CONTACTS>
    <DATES loss="2015-01-07" inspected="2015-01-08T05:00:00Z" completed="2015-01-08T20:26:26Z" received="2015-01-08T20:18:00Z" entered="2015-01-08T20:22:00Z" contacted="2015-01-08T05:00:00Z" />
  </COVERSHEET>
  <COVERAGES>
    <COVERAGE deductible="500" coverageName="Building" coverageType="0" id="1">

        <TOTALS lineItemTotal="7919.16" subtotal="8060.24" rcv="8060.24" acv="8060.24" deductible="500" fullDeduct="500" netClaim="7560.24">
          <SALES_TAXES>
            <SALES_TAX desc="Material Sales Tax" amount="141.08" taxOP="OPonTax" />
          </SALES_TAXES>
          <SIGNATURE estimator="John Deeter" />
        </TOTALS>

    </COVERAGE>
  </COVERAGES>
  <RECAP_TAX_OP>
    <TAXES>
      <TAX_DETAIL taxNum="1" rate="6" desc="Material Sales Tax" amount="141.08" />
      <TAX_DETAIL taxNum="2" rate="6" desc="Storage Tax" />
    </TAXES>
    <LINE_ITEMS>
      <TAXES>
        <TAX_AMOUNT taxNum="1" amount="141.08" />
      </TAXES>
    </LINE_ITEMS>
  </RECAP_TAX_OP>
  <LINE_ITEM_DETAIL total="7919.16">
    <GROUP desc="OSCAR_MURPHY" total="7919.16" acvTotal="8060.24" rcvTotal="8060.24" tax="141.08">
      <GROUPS>
        <GROUP desc="Main Level" total="7888.97" acvTotal="8030.05" rcvTotal="8030.05" tax="141.08">
          <ITEMS total="6394.83">
            <ITEM type="I" lineNum="1" cat="FRM" sel="IJ9" act="&" desc="I-joist - 9 1/2" deep - 1 3/4" flange" calc="164.67" qty="164.67" unit="LF" coverageName="Building" remove="0.76" replace="3.19" total="650.45" acv="650.45" recoverable="1" tax="19.27" acvTotal="669.72" rcvTotal="669.72" isPartOfInitSettle="1" laborTotal="329.34" laborBase="144.91" laborBurden="85.63" laborMarkup="98.8" laborHours="8.42" material="321.11" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.76" acvTotal="0.76" rcvTotal="0.76" trade="DMO" />
                <ITEM_ACT act="+" labUnit="1.24" matUnit="1.95" tax="0.12" acvTotal="3.31" rcvTotal="3.31" trade="CARP-FRM" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="3" cat="FRM" sel="SHW3/4T" act="&" desc="Sheathing - OSB - 3/4" - tongue and groove" calc="192" qty="192" unit="SF" coverageName="Building" remove="0.91" replace="1.47" total="456.96" acv="456.96" recoverable="1" tax="8.29" acvTotal="465.25" rcvTotal="465.25" isPartOfInitSettle="1" laborTotal="318.72" laborBase="140.16" laborBurden="80.64" laborMarkup="97.92" laborHours="8.46" material="138.24" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.91" acvTotal="0.91" rcvTotal="0.91" trade="DMO" />
                <ITEM_ACT act="+" labUnit="0.75" matUnit="0.72" tax="0.04" acvTotal="1.51" rcvTotal="1.51" trade="CARP-FRM" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="4" cat="FRM" sel="DBP6" act="&" desc="Drilled bottom plate - 2" x 6" treated lumber" calc="50.67" qty="50.67" unit="LF" coverageName="Building" remove="3.57" replace="2.36" total="300.47" acv="300.47" recoverable="1" tax="3.1" acvTotal="303.57" rcvTotal="303.57" isPartOfInitSettle="1" laborTotal="248.79" laborBase="107.42" laborBurden="62.32" laborMarkup="79.05" laborHours="6.88" material="51.68" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="3.57" acvTotal="3.57" rcvTotal="3.57" trade="DMO" />
                <ITEM_ACT act="+" labUnit="1.34" matUnit="1.02" tax="0.06" acvTotal="2.42" rcvTotal="2.42" trade="CARP-FRM" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="5" cat="CNC" sel="FTG-" act="&" desc="Footings - labor and materials" calc="2.54" qty="2.54" unit="CY" coverageName="Building" remove="106.07" replace="270.31" total="956.01" acv="956.01" recoverable="1" tax="15.76" acvTotal="971.77" rcvTotal="971.77" isPartOfInitSettle="1" laborTotal="626.82" laborBase="209.96" laborBurden="113.79" laborMarkup="303.07" laborHours="13.14" material="262.74" equipment="66.45" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="88.87" equUnit="17.2" acvTotal="106.07" rcvTotal="106.07" trade="DMO" />
                <ITEM_ACT act="+" labUnit="157.91" matUnit="103.44" equUnit="8.96" tax="6.21" acvTotal="276.52" rcvTotal="276.52" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="7" cat="CNC" sel="RBJ42" act="+" desc="Steel rebar - j-bar - #4, 2' 6"" calc="48" qty="48" unit="EA" coverageName="Building" replace="2.48" total="119.04" acv="119.04" recoverable="1" tax="2.48" acvTotal="121.52" rcvTotal="121.52" isPartOfInitSettle="1" laborTotal="77.76" laborBase="22.08" laborBurden="11.52" laborMarkup="44.16" laborHours="1.25" material="41.28" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="+" labUnit="1.62" matUnit="0.86" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="8" cat="CNC" sel="RB4" act="&" desc="Steel rebar - #4 (1/2")" calc="106.17" qty="106.17" unit="LF" coverageName="Building" remove="0.99" replace="0.92" total="202.79" acv="202.79" recoverable="1" tax="2.87" acvTotal="205.66" rcvTotal="205.66" isPartOfInitSettle="1" laborTotal="155.01" laborBase="58.39" laborBurden="32.91" laborMarkup="63.71" laborHours="3.88" material="47.78" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.99" acvTotal="0.99" rcvTotal="0.99" trade="DMO" />
                <ITEM_ACT act="+" labUnit="0.47" matUnit="0.45" tax="0.03" acvTotal="0.95" rcvTotal="0.95" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="9" cat="CNC" sel="FW-" act="&" desc="Concrete wall - labor & materials" calc="4.87" qty="4.87" unit="CY" coverageName="Building" remove="184.02" replace="235.54" total="2043.26" acv="2043.26" recoverable="1" tax="29.73" acvTotal="2072.99" rcvTotal="2072.99" isPartOfInitSettle="1" laborTotal="1361.8" laborBase="493.33" laborBurden="272.38" laborMarkup="596.09" laborHours="32.04" material="495.57" equipment="185.89" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="154.23" equUnit="29.79" acvTotal="184.02" rcvTotal="184.02" trade="DMO" />
                <ITEM_ACT act="+" labUnit="125.4" matUnit="101.76" equUnit="8.38" tax="6.11" acvTotal="241.65" rcvTotal="241.65" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="10" cat="CNC" sel="RB4" act="&" desc="Steel rebar - #4 (1/2")" calc="872.17" qty="872.17" unit="LF" coverageName="Building" remove="0.99" replace="0.92" total="1665.85" acv="1665.85" recoverable="1" tax="23.55" acvTotal="1689.4" rcvTotal="1689.4" isPartOfInitSettle="1" laborTotal="1273.37" laborBase="479.69" laborBurden="270.37" laborMarkup="523.31" laborHours="31.91" material="392.48" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.99" acvTotal="0.99" rcvTotal="0.99" trade="DMO" />
                <ITEM_ACT act="+" labUnit="0.47" matUnit="0.45" tax="0.03" acvTotal="0.95" rcvTotal="0.95" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
          </ITEMS>
          <GROUPS>
            <GROUP desc="Room1" total="1494.14" acvTotal="1530.17" rcvTotal="1530.17" tax="36.03">
              <ROOM_INFO sketchCeiling="8'" />
              <ROOM_DIM_VARS sfWalls="384" sfCeiling="144" sfWallsCeiling="528" sfFloor="144" syFloor="16" lfFloorPerim="48" lfCeilingPerim="48" />
              <ITEMS total="1494.14">
                <ITEM type="I" lineNum="15" cat="FCC" sel="AV" act="-" desc="Carpet" calc="F" qty="144" unit="SF" coverageName="Building" remove="0.19" total="27.36" acv="27.36" recoverable="1" acvTotal="27.36" rcvTotal="27.36" isPartOfInitSettle="1" laborTotal="27.36" laborBase="11.52" laborBurden="7.2" laborMarkup="8.64" laborHours="0.78" containsBSCDontApply="1">
                  <ITEM_ACTS>
                    <ITEM_ACT act="-" labUnit="0.19" trade="DMO" />
                  </ITEM_ACTS>
                </ITEM>
                <ITEM type="I" lineNum="13" cat="FCC" sel="AV" act="+" desc="Carpet" calc="(F)*1.15" qty="165.6" unit="SF" coverageName="Building" replace="2.64" total="437.18" acv="437.18" recoverable="1" tax="21.46" acvTotal="458.64" rcvTotal="458.64" isPartOfInitSettle="1" laborTotal="69.55" laborBase="29.81" laborBurden="14.9" laborMarkup="24.84" laborHours="1.6" material="357.7" equipment="9.93" containsBSCDontApply="1">
                  <ITEM_ACTS>
                    <ITEM_ACT act="+" labUnit="0.42" matUnit="2.16" equUnit="0.06" trade="FLR" />
                  </ITEM_ACTS>
                </ITEM>
                <ITEM type="N">
                  <NOTE>15 % waste added for Carpet.</NOTE>
                </ITEM>
                <ITEM type="I" lineNum="11" cat="DRY" sel="1/2++" act="&" desc="1/2" drywall - hung, taped, with smooth wall finish" calc="WC" qty="528" unit="SF" coverageName="Building" remove="0.28" replace="1.67" total="1029.6" acv="1029.6" recoverable="1" tax="14.57" acvTotal="1044.17" rcvTotal="1044.17" isPartOfInitSettle="1" laborTotal="786.72" laborBase="343.2" laborBurden="179.52" laborMarkup="264" laborHours="19.26" material="242.88" containsBSCDontApply="1">
                  <ITEM_ACTS>
                    <ITEM_ACT act="-" labUnit="0.28" acvTotal="0.28" rcvTotal="0.28" trade="DMO" />
                    <ITEM_ACT act="+" labUnit="1.21" matUnit="0.46" tax="0.03" acvTotal="1.7" rcvTotal="1.7" trade="DRY" />
                  </ITEM_ACTS>
                </ITEM>
              </ITEMS>
            </GROUP>
          </GROUPS>
        </GROUP>
        <GROUP desc="Labor Minimums Applied" total="30.19" acvTotal="30.19" rcvTotal="30.19">
          <ITEMS total="30.19">
            <ITEM type="I" lineNum="14" cat="FCC" sel="MN-A" act="+" desc="Carpet labor minimum" calc="1" qty="1" unit="EA" coverageName="Building" replace="30.19" total="30.19" acv="30.19" recoverable="1" acvTotal="30.19" rcvTotal="30.19" isPartOfInitSettle="0" laborTotal="30.19" laborBase="30.19">
              <ITEM_ACTS>
                <ITEM_ACT act="+" labUnit="30.19" />
              </ITEM_ACTS>
            </ITEM>
          </ITEMS>
        </GROUP>
      </GROUPS>
      <AREA_DIM_VARS sfWalls="384" sfCeiling="144" sfWallsCeiling="528" sfFloor="144" syFloor="16" lfFloorPerim="48" lfCeilingPerim="48" sfSkFloor="144" sfSkTotalFloor="160.44" sfSkIntWall="384" sfSkExtWall="456" lfSkExtWallPerim="50.67" />
    </GROUP>
  </LINE_ITEM_DETAIL>
  <RECAP_BY_ROOM total="7919.16">
    <RECAP_GROUP desc="OSCAR_MURPHY" subtotal="7919.16" subtotalPercentage="100">
      <RECAP_GROUPS>
        <RECAP_GROUP desc="Main Level" items="6394.83" itemsPercentage="80.75" subtotal="7888.97" subtotalPercentage="99.62">
          <RECAP_GROUPS>
            <RECAP_GROUP desc="Room1" items="1494.14" itemsPercentage="18.87" />
          </RECAP_GROUPS>
        </RECAP_GROUP>
        <RECAP_GROUP desc="Labor Minimums Applied" items="30.19" itemsPercentage="0.38" />
      </RECAP_GROUPS>
    </RECAP_GROUP>
  </RECAP_BY_ROOM>
  <RECAP_BY_CATEGORY subtotalRCV="8060.24">
    <OP_ITEMS subtotalRCV="7919.16" subtotalPercentage="98.25">
      <CATEGORY desc="GENERAL DEMOLITION" rcv="2790.12" percentage="34.62" />
      <CATEGORY desc="CONCRETE & ASPHALT" rcv="2852.79" percentage="35.39" />
      <CATEGORY desc="DRYWALL" rcv="881.76" percentage="10.94" />
      <CATEGORY desc="FLOOR COVERING - CARPET" rcv="467.37" percentage="5.8" />
      <CATEGORY desc="FRAMING & ROUGH CARPENTRY" rcv="927.12" percentage="11.5" />
    </OP_ITEMS>
    <SALES_TAXES>
      <SALES_TAX desc="Material Sales Tax" percentage="1.75" rcv="141.08" />
    </SALES_TAXES>
  </RECAP_BY_CATEGORY>
</GENERIC_ROUGHDRAFT>```

Now i want to get some of the data from this XML , such as i need to have a query which can return me the following data

dateCreated  =  2015-01-08T20:26:28

estimateName =  OSCAR_MURPHY

PHONE type   =  Business
ContactName  =  JohnDeeter

Can someone please help me with a query to get these columns derived from XML ,i need all the columns from this XML but if someone can help me with a few i can use it and derive all.

Thanks in advance to everyone and please let me know if you need anything else.

答:
This XML is by no means strange, just a bit more complex... And there is default namespace... Try this:</p>

```<code>DECLARE @dummyXMLData TABLE(XMLValue XML);
INSERT INTO @dummyXMLData VALUES
(N'<GENERIC_ROUGHDRAFT xmlns="http://xactware.com/generic_roughdraft.xsd" majorVersion="28" minorVersion="300" transactionId="001SPL8">
  <HEADER dateCreated="2015-01-08T20:26:28" />
  <COVERSHEET>
    <ESTIMATE_INFO estimateName="OSCAR_MURPHY" insuredName="Oscar Murphy" priceList="KYLO8X_JAN15" laborEff="Restoration/Service/Remodel" claimNumber="KBR-182015-13:18:46 MST" policyNumber="KBR1467216" typeOfLoss="Collapse" causeOfLoss="collapse" deprMat="1" deprNonMat="1" deprTaxes="1" recipientsXNAddress="XA.ONLINE.TEST" rotationTrade="Re Key\Lock Change" carrierId="2210000" estimateType="Structural" />
<!--Deleted for brevity-->
  <PHONES>
      <PHONE type="Home" primary="1" phone="(800) 555-5765" />
      <PHONE type="Business" phone="(801) 555-2021" />
      <PHONE type="Cellular" phone="(808) 555-0202" />
    </PHONES>
    <CONTACTS>
      <CONTACT type="ClaimRep" name="John Deeter">
<!--Deleted for brevity-->
      </CONTACT>
      <CONTACT type="Estimator" name="John Deeter">
<!--Deleted for brevity-->
      </CONTACT>
    </CONTACTS>
    <DATES loss="2015-01-07" inspected="2015-01-08T05:00:00Z" completed="2015-01-08T20:26:26Z" received="2015-01-08T20:18:00Z" entered="2015-01-08T20:22:00Z" contacted="2015-01-08T05:00:00Z" />
  </COVERSHEET>
<!--Deleted for brevity-->
</GENERIC_ROUGHDRAFT>');

WITH XMLNAMESPACES(DEFAULT 'http://xactware.com/generic_roughdraft.xsd')
SELECT X.XMLValue.value(N'(/GENERIC_ROUGHDRAFT/HEADER/@dateCreated)[1]','datetime') AS DateCreated
      ,X.XMLValue.value(N'(/GENERIC_ROUGHDRAFT/COVERSHEET/ESTIMATE_INFO/@estimateName)[1]','nvarchar(max)') AS EstimateName
      ,X.XMLValue.value(N'(/GENERIC_ROUGHDRAFT/COVERSHEET/PHONES/PHONE[@type="Business"]/@phone)[1]','nvarchar(max)') AS BusinessPhone
      ,X.XMLValue.query(N'/GENERIC_ROUGHDRAFT/COVERSHEET/CONTACTS/CONTACT') AS AllConctacts
FROM @dummyXMLData X
</code>```

Body:
I have a table named dbo.XMLData and one column in the table named XMLValue, a sample row in the table is below( basically its a XML value)

<GENERIC_ROUGHDRAFT xmlns="http://xactware.com/generic_roughdraft.xsd" majorVersion="28" minorVersion="300" transactionId="001SPL8">

  <COVERSHEET>
    <ESTIMATE_INFO estimateName="OSCAR_MURPHY" insuredName="Oscar Murphy" priceList="KYLO8X_JAN15" laborEff="Restoration/Service/Remodel" claimNumber="KBR-182015-13:18:46 MST" policyNumber="KBR1467216" typeOfLoss="Collapse" causeOfLoss="collapse" deprMat="1" deprNonMat="1" deprTaxes="1" recipientsXNAddress="XA.ONLINE.TEST" rotationTrade="Re Key\Lock Change" carrierId="2210000" estimateType="Structural" />
    <ADDRESSES>
      <ADDRESS type="Property" street="6467 N 7506 W" city="Louisville" state="KY" zip="40219" primary="1" />
      <ADDRESS type="Home" street="6467 N 7506 W" city="Louisville" state="KY" zip="40219" />
    </ADDRESSES>
    <PHONES>
      <PHONE type="Home" primary="1" phone="(800) 555-5765" />
      <PHONE type="Business" phone="(801) 555-2021" />
      <PHONE type="Cellular" phone="(808) 555-0202" />
    </PHONES>
    <CONTACTS>
      <CONTACT type="ClaimRep" name="John Deeter">
        <ADDRESSES>
          <ADDRESS type="Business" street="100 N 100 E" city="Orem" state="UT" zip="84062" primary="1" />
        </ADDRESSES>
        <PHONES>
          <PHONE primary="1" type="Business" phone="555-555-5554" />
        </PHONES>
      </CONTACT>
      <CONTACT type="Estimator" name="John Deeter">
        <ADDRESSES>
          <ADDRESS type="Business" street="100 N 100 E" city="Orem" state="UT" zip="84062" primary="1" />
        </ADDRESSES>
        <PHONES>
          <PHONE primary="1" type="Business" phone="555-555-5554" />
        </PHONES>
      </CONTACT>
    </CONTACTS>
    <DATES loss="2015-01-07" inspected="2015-01-08T05:00:00Z" completed="2015-01-08T20:26:26Z" received="2015-01-08T20:18:00Z" entered="2015-01-08T20:22:00Z" contacted="2015-01-08T05:00:00Z" />
  </COVERSHEET>
  <COVERAGES>
    <COVERAGE deductible="500" coverageName="Building" coverageType="0" id="1">

        <TOTALS lineItemTotal="7919.16" subtotal="8060.24" rcv="8060.24" acv="8060.24" deductible="500" fullDeduct="500" netClaim="7560.24">
          <SALES_TAXES>
            <SALES_TAX desc="Material Sales Tax" amount="141.08" taxOP="OPonTax" />
          </SALES_TAXES>
          <SIGNATURE estimator="John Deeter" />
        </TOTALS>

    </COVERAGE>
  </COVERAGES>
  <RECAP_TAX_OP>
    <TAXES>
      <TAX_DETAIL taxNum="1" rate="6" desc="Material Sales Tax" amount="141.08" />
      <TAX_DETAIL taxNum="2" rate="6" desc="Storage Tax" />
    </TAXES>
    <LINE_ITEMS>
      <TAXES>
        <TAX_AMOUNT taxNum="1" amount="141.08" />
      </TAXES>
    </LINE_ITEMS>
  </RECAP_TAX_OP>
  <LINE_ITEM_DETAIL total="7919.16">
    <GROUP desc="OSCAR_MURPHY" total="7919.16" acvTotal="8060.24" rcvTotal="8060.24" tax="141.08">
      <GROUPS>
        <GROUP desc="Main Level" total="7888.97" acvTotal="8030.05" rcvTotal="8030.05" tax="141.08">
          <ITEMS total="6394.83">
            <ITEM type="I" lineNum="1" cat="FRM" sel="IJ9" act="&" desc="I-joist - 9 1/2" deep - 1 3/4" flange" calc="164.67" qty="164.67" unit="LF" coverageName="Building" remove="0.76" replace="3.19" total="650.45" acv="650.45" recoverable="1" tax="19.27" acvTotal="669.72" rcvTotal="669.72" isPartOfInitSettle="1" laborTotal="329.34" laborBase="144.91" laborBurden="85.63" laborMarkup="98.8" laborHours="8.42" material="321.11" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.76" acvTotal="0.76" rcvTotal="0.76" trade="DMO" />
                <ITEM_ACT act="+" labUnit="1.24" matUnit="1.95" tax="0.12" acvTotal="3.31" rcvTotal="3.31" trade="CARP-FRM" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="3" cat="FRM" sel="SHW3/4T" act="&" desc="Sheathing - OSB - 3/4" - tongue and groove" calc="192" qty="192" unit="SF" coverageName="Building" remove="0.91" replace="1.47" total="456.96" acv="456.96" recoverable="1" tax="8.29" acvTotal="465.25" rcvTotal="465.25" isPartOfInitSettle="1" laborTotal="318.72" laborBase="140.16" laborBurden="80.64" laborMarkup="97.92" laborHours="8.46" material="138.24" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.91" acvTotal="0.91" rcvTotal="0.91" trade="DMO" />
                <ITEM_ACT act="+" labUnit="0.75" matUnit="0.72" tax="0.04" acvTotal="1.51" rcvTotal="1.51" trade="CARP-FRM" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="4" cat="FRM" sel="DBP6" act="&" desc="Drilled bottom plate - 2" x 6" treated lumber" calc="50.67" qty="50.67" unit="LF" coverageName="Building" remove="3.57" replace="2.36" total="300.47" acv="300.47" recoverable="1" tax="3.1" acvTotal="303.57" rcvTotal="303.57" isPartOfInitSettle="1" laborTotal="248.79" laborBase="107.42" laborBurden="62.32" laborMarkup="79.05" laborHours="6.88" material="51.68" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="3.57" acvTotal="3.57" rcvTotal="3.57" trade="DMO" />
                <ITEM_ACT act="+" labUnit="1.34" matUnit="1.02" tax="0.06" acvTotal="2.42" rcvTotal="2.42" trade="CARP-FRM" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="5" cat="CNC" sel="FTG-" act="&" desc="Footings - labor and materials" calc="2.54" qty="2.54" unit="CY" coverageName="Building" remove="106.07" replace="270.31" total="956.01" acv="956.01" recoverable="1" tax="15.76" acvTotal="971.77" rcvTotal="971.77" isPartOfInitSettle="1" laborTotal="626.82" laborBase="209.96" laborBurden="113.79" laborMarkup="303.07" laborHours="13.14" material="262.74" equipment="66.45" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="88.87" equUnit="17.2" acvTotal="106.07" rcvTotal="106.07" trade="DMO" />
                <ITEM_ACT act="+" labUnit="157.91" matUnit="103.44" equUnit="8.96" tax="6.21" acvTotal="276.52" rcvTotal="276.52" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="7" cat="CNC" sel="RBJ42" act="+" desc="Steel rebar - j-bar - #4, 2' 6"" calc="48" qty="48" unit="EA" coverageName="Building" replace="2.48" total="119.04" acv="119.04" recoverable="1" tax="2.48" acvTotal="121.52" rcvTotal="121.52" isPartOfInitSettle="1" laborTotal="77.76" laborBase="22.08" laborBurden="11.52" laborMarkup="44.16" laborHours="1.25" material="41.28" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="+" labUnit="1.62" matUnit="0.86" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="8" cat="CNC" sel="RB4" act="&" desc="Steel rebar - #4 (1/2")" calc="106.17" qty="106.17" unit="LF" coverageName="Building" remove="0.99" replace="0.92" total="202.79" acv="202.79" recoverable="1" tax="2.87" acvTotal="205.66" rcvTotal="205.66" isPartOfInitSettle="1" laborTotal="155.01" laborBase="58.39" laborBurden="32.91" laborMarkup="63.71" laborHours="3.88" material="47.78" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.99" acvTotal="0.99" rcvTotal="0.99" trade="DMO" />
                <ITEM_ACT act="+" labUnit="0.47" matUnit="0.45" tax="0.03" acvTotal="0.95" rcvTotal="0.95" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="9" cat="CNC" sel="FW-" act="&" desc="Concrete wall - labor & materials" calc="4.87" qty="4.87" unit="CY" coverageName="Building" remove="184.02" replace="235.54" total="2043.26" acv="2043.26" recoverable="1" tax="29.73" acvTotal="2072.99" rcvTotal="2072.99" isPartOfInitSettle="1" laborTotal="1361.8" laborBase="493.33" laborBurden="272.38" laborMarkup="596.09" laborHours="32.04" material="495.57" equipment="185.89" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="154.23" equUnit="29.79" acvTotal="184.02" rcvTotal="184.02" trade="DMO" />
                <ITEM_ACT act="+" labUnit="125.4" matUnit="101.76" equUnit="8.38" tax="6.11" acvTotal="241.65" rcvTotal="241.65" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
            <ITEM type="I" lineNum="10" cat="CNC" sel="RB4" act="&" desc="Steel rebar - #4 (1/2")" calc="872.17" qty="872.17" unit="LF" coverageName="Building" remove="0.99" replace="0.92" total="1665.85" acv="1665.85" recoverable="1" tax="23.55" acvTotal="1689.4" rcvTotal="1689.4" isPartOfInitSettle="1" laborTotal="1273.37" laborBase="479.69" laborBurden="270.37" laborMarkup="523.31" laborHours="31.91" material="392.48" containsBSCDontApply="1">
              <ITEM_ACTS>
                <ITEM_ACT act="-" labUnit="0.99" acvTotal="0.99" rcvTotal="0.99" trade="DMO" />
                <ITEM_ACT act="+" labUnit="0.47" matUnit="0.45" tax="0.03" acvTotal="0.95" rcvTotal="0.95" trade="CNC" />
              </ITEM_ACTS>
            </ITEM>
          </ITEMS>
          <GROUPS>
            <GROUP desc="Room1" total="1494.14" acvTotal="1530.17" rcvTotal="1530.17" tax="36.03">
              <ROOM_INFO sketchCeiling="8'" />
              <ROOM_DIM_VARS sfWalls="384" sfCeiling="144" sfWallsCeiling="528" sfFloor="144" syFloor="16" lfFloorPerim="48" lfCeilingPerim="48" />
              <ITEMS total="1494.14">
                <ITEM type="I" lineNum="15" cat="FCC" sel="AV" act="-" desc="Carpet" calc="F" qty="144" unit="SF" coverageName="Building" remove="0.19" total="27.36" acv="27.36" recoverable="1" acvTotal="27.36" rcvTotal="27.36" isPartOfInitSettle="1" laborTotal="27.36" laborBase="11.52" laborBurden="7.2" laborMarkup="8.64" laborHours="0.78" containsBSCDontApply="1">
                  <ITEM_ACTS>
                    <ITEM_ACT act="-" labUnit="0.19" trade="DMO" />
                  </ITEM_ACTS>
                </ITEM>
                <ITEM type="I" lineNum="13" cat="FCC" sel="AV" act="+" desc="Carpet" calc="(F)*1.15" qty="165.6" unit="SF" coverageName="Building" replace="2.64" total="437.18" acv="437.18" recoverable="1" tax="21.46" acvTotal="458.64" rcvTotal="458.64" isPartOfInitSettle="1" laborTotal="69.55" laborBase="29.81" laborBurden="14.9" laborMarkup="24.84" laborHours="1.6" material="357.7" equipment="9.93" containsBSCDontApply="1">
                  <ITEM_ACTS>
                    <ITEM_ACT act="+" labUnit="0.42" matUnit="2.16" equUnit="0.06" trade="FLR" />
                  </ITEM_ACTS>
                </ITEM>
                <ITEM type="N">
                  <NOTE>15 % waste added for Carpet.</NOTE>
                </ITEM>
                <ITEM type="I" lineNum="11" cat="DRY" sel="1/2++" act="&" desc="1/2" drywall - hung, taped, with smooth wall finish" calc="WC" qty="528" unit="SF" coverageName="Building" remove="0.28" replace="1.67" total="1029.6" acv="1029.6" recoverable="1" tax="14.57" acvTotal="1044.17" rcvTotal="1044.17" isPartOfInitSettle="1" laborTotal="786.72" laborBase="343.2" laborBurden="179.52" laborMarkup="264" laborHours="19.26" material="242.88" containsBSCDontApply="1">
                  <ITEM_ACTS>
                    <ITEM_ACT act="-" labUnit="0.28" acvTotal="0.28" rcvTotal="0.28" trade="DMO" />
                    <ITEM_ACT act="+" labUnit="1.21" matUnit="0.46" tax="0.03" acvTotal="1.7" rcvTotal="1.7" trade="DRY" />
                  </ITEM_ACTS>
                </ITEM>
              </ITEMS>
            </GROUP>
          </GROUPS>
        </GROUP>
        <GROUP desc="Labor Minimums Applied" total="30.19" acvTotal="30.19" rcvTotal="30.19">
          <ITEMS total="30.19">
            <ITEM type="I" lineNum="14" cat="FCC" sel="MN-A" act="+" desc="Carpet labor minimum" calc="1" qty="1" unit="EA" coverageName="Building" replace="30.19" total="30.19" acv="30.19" recoverable="1" acvTotal="30.19" rcvTotal="30.19" isPartOfInitSettle="0" laborTotal="30.19" laborBase="30.19">
              <ITEM_ACTS>
                <ITEM_ACT act="+" labUnit="30.19" />
              </ITEM_ACTS>
            </ITEM>
          </ITEMS>
        </GROUP>
      </GROUPS>
      <AREA_DIM_VARS sfWalls="384" sfCeiling="144" sfWallsCeiling="528" sfFloor="144" syFloor="16" lfFloorPerim="48" lfCeilingPerim="48" sfSkFloor="144" sfSkTotalFloor="160.44" sfSkIntWall="384" sfSkExtWall="456" lfSkExtWallPerim="50.67" />
    </GROUP>
  </LINE_ITEM_DETAIL>
  <RECAP_BY_ROOM total="7919.16">
    <RECAP_GROUP desc="OSCAR_MURPHY" subtotal="7919.16" subtotalPercentage="100">
      <RECAP_GROUPS>
        <RECAP_GROUP desc="Main Level" items="6394.83" itemsPercentage="80.75" subtotal="7888.97" subtotalPercentage="99.62">
          <RECAP_GROUPS>
            <RECAP_GROUP desc="Room1" items="1494.14" itemsPercentage="18.87" />
          </RECAP_GROUPS>
        </RECAP_GROUP>
        <RECAP_GROUP desc="Labor Minimums Applied" items="30.19" itemsPercentage="0.38" />
      </RECAP_GROUPS>
    </RECAP_GROUP>
  </RECAP_BY_ROOM>
  <RECAP_BY_CATEGORY subtotalRCV="8060.24">
    <OP_ITEMS subtotalRCV="7919.16" subtotalPercentage="98.25">
      <CATEGORY desc="GENERAL DEMOLITION" rcv="2790.12" percentage="34.62" />
      <CATEGORY desc="CONCRETE & ASPHALT" rcv="2852.79" percentage="35.39" />
      <CATEGORY desc="DRYWALL" rcv="881.76" percentage="10.94" />
      <CATEGORY desc="FLOOR COVERING - CARPET" rcv="467.37" percentage="5.8" />
      <CATEGORY desc="FRAMING & ROUGH CARPENTRY" rcv="927.12" percentage="11.5" />
    </OP_ITEMS>
    <SALES_TAXES>
      <SALES_TAX desc="Material Sales Tax" percentage="1.75" rcv="141.08" />
    </SALES_TAXES>
  </RECAP_BY_CATEGORY>
</GENERIC_ROUGHDRAFT>

Now i want to get some of the data from this XML , such as i need to have a query which can return me the following data

dateCreated  =  2015-01-08T20:26:28

estimateName =  OSCAR_MURPHY

PHONE type   =  Business
ContactName  =  JohnDeeter

Can someone please help me with a query to get these columns derived from XML ,i need all the columns from this XML but if someone can help me with a few i can use it and derive all.

Thanks in advance to everyone and please let me know if you need anything else.

Body:
This XML is by no means strange, just a bit more complex... And there is default namespace... Try this:

DECLARE @dummyXMLData TABLE(XMLValue XML);
INSERT INTO @dummyXMLData VALUES
(N'<GENERIC_ROUGHDRAFT xmlns="http://xactware.com/generic_roughdraft.xsd" majorVersion="28" minorVersion="300" transactionId="001SPL8">
  <HEADER dateCreated="2015-01-08T20:26:28" />
  <COVERSHEET>
    <ESTIMATE_INFO estimateName="OSCAR_MURPHY" insuredName="Oscar Murphy" priceList="KYLO8X_JAN15" laborEff="Restoration/Service/Remodel" claimNumber="KBR-182015-13:18:46 MST" policyNumber="KBR1467216" typeOfLoss="Collapse" causeOfLoss="collapse" deprMat="1" deprNonMat="1" deprTaxes="1" recipientsXNAddress="XA.ONLINE.TEST" rotationTrade="Re Key\Lock Change" carrierId="2210000" estimateType="Structural" />
<!--Deleted for brevity-->
  <PHONES>
      <PHONE type="Home" primary="1" phone="(800) 555-5765" />
      <PHONE type="Business" phone="(801) 555-2021" />
      <PHONE type="Cellular" phone="(808) 555-0202" />
    </PHONES>
    <CONTACTS>
      <CONTACT type="ClaimRep" name="John Deeter">
<!--Deleted for brevity-->
      </CONTACT>
      <CONTACT type="Estimator" name="John Deeter">
<!--Deleted for brevity-->
      </CONTACT>
    </CONTACTS>
    <DATES loss="2015-01-07" inspected="2015-01-08T05:00:00Z" completed="2015-01-08T20:26:26Z" received="2015-01-08T20:18:00Z" entered="2015-01-08T20:22:00Z" contacted="2015-01-08T05:00:00Z" />
  </COVERSHEET>
<!--Deleted for brevity-->
</GENERIC_ROUGHDRAFT>');

WITH XMLNAMESPACES(DEFAULT 'http://xactware.com/generic_roughdraft.xsd')
SELECT X.XMLValue.value(N'(/GENERIC_ROUGHDRAFT/HEADER/@dateCreated)[1]','datetime') AS DateCreated
      ,X.XMLValue.value(N'(/GENERIC_ROUGHDRAFT/COVERSHEET/ESTIMATE_INFO/@estimateName)[1]','nvarchar(max)') AS EstimateName
      ,X.XMLValue.value(N'(/GENERIC_ROUGHDRAFT/COVERSHEET/PHONES/PHONE[@type="Business"]/@phone)[1]','nvarchar(max)') AS BusinessPhone
      ,X.XMLValue.query(N'/GENERIC_ROUGHDRAFT/COVERSHEET/CONTACTS/CONTACT') AS AllConctacts
FROM @dummyXMLData X


来源: stackexchange

问:
Faster to consolidate regexes in a hash of regexes in Ruby?
I have a string that I want to map to an integer. Many strings can map to the same integer, so I'm using regexes to match strings that should map to the same integer.

Example:

```<code>str = "hello"

REGEXES.each do |key, val|
  if str =~ key
    print val
  end
end
</code>```

where REGEXES is a hash that maps regex to integer.

Which is better:

```<code>REGEXES = [/hello/ => 2, /foo/ => 2, /bar/ => 3]
</code>```

or

```<code>REGEXES = [/(hello|foo)/ => 2, /bar/ => 3]
</code>```

答:
Benchmark is your friend:

```<code>require 'benchmark'

str = 'hello'
num = 1000000

Benchmark.bmbm do |x|
  x.report('individual keys:') do
    regexes = [/hello/ => 2, /foo/ => 2, /bar/ => 3]

    num.times do
      regexes.each {|key, val| str =~ key}
    end
  end

  x.report('combined keys:  ') do
    regexes = [/(hello|foo)/ => 2, /bar/ => 3]

    num.times do
      regexes.each {|key, val| str =~ key}
    end
  end
end
</code>```

Result:

```<code>Rehearsal ----------------------------------------------------
individual keys:   1.600000   0.010000   1.610000 (  1.780246)
combined keys:     1.610000   0.010000   1.620000 (  1.761067)
------------------------------------------- total: 3.230000sec

                       user     system      total        real
individual keys:   1.570000   0.000000   1.570000 (  1.589879)
combined keys:     1.590000   0.010000   1.600000 (  1.678724)
</code>```

As you can see, in this case there's not much difference.

I'd suggest that you try it with your full hash of regexes/integers, and see if the difference is more significant. If there is, well, there's your answer. If there's not, you can probably feel free to use whichever makes more sense.

ContentLicense: CC BY-SA 2.5

Body:
I have a string that I want to map to an integer. Many strings can map to the same integer, so I'm using regexes to match strings that should map to the same integer.

Example:

str = "hello"

REGEXES.each do |key, val|
  if str =~ key
    print val
  end
end

where REGEXES is a hash that maps regex to integer.

Which is better:

REGEXES = [/hello/ => 2, /foo/ => 2, /bar/ => 3]

or

REGEXES = [/(hello|foo)/ => 2, /bar/ => 3]

Body:
Benchmark is your friend:

require 'benchmark'

str = 'hello'
num = 1000000

Benchmark.bmbm do |x|
  x.report('individual keys:') do
    regexes = [/hello/ => 2, /foo/ => 2, /bar/ => 3]

    num.times do
      regexes.each {|key, val| str =~ key}
    end
  end

  x.report('combined keys:  ') do
    regexes = [/(hello|foo)/ => 2, /bar/ => 3]

    num.times do
      regexes.each {|key, val| str =~ key}
    end
  end
end

Result:

Rehearsal ----------------------------------------------------
individual keys:   1.600000   0.010000   1.610000 (  1.780246)
combined keys:     1.610000   0.010000   1.620000 (  1.761067)
------------------------------------------- total: 3.230000sec

                       user     system      total        real
individual keys:   1.570000   0.000000   1.570000 (  1.589879)
combined keys:     1.590000   0.010000   1.600000 (  1.678724)

As you can see, in this case there's not much difference.

I'd suggest that you try it with your full hash of regexes/integers, and see if the difference is more significant. If there is, well, there's your answer. If there's not, you can probably feel free to use whichever makes more sense.


问:
group and filter and array of objects using VanillaJS
I have the following table which contains some objects :

```<code>var data = [
    {
        "userRoleId": 1,
        "userId": 1,
        "roleId": 1,
        "organizationId": "ORG_01",
        "roleTitle": "Admin",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": false,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 2,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_01",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 4,
        "userId": 1,
        "roleId": 4,
        "organizationId": "ORG_02",
        "roleTitle": "Referent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 5,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_02",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    }
];
</code>```

What I want to do is to group these objects using the object property "organizationId" and "organizationTitle", so what I tried is I grouped them using "organizationId" as following :

```<code>var filtered = data.reduce(function(accumulator, currentValue) {
    (accumulator[currentValue['organizationId']] = accumulator[currentValue['organizationId']] || []).push(currentValue);
    return accumulator;
  }, {});
</code>```

This will generate an object with a key which has the value of each "organizationId" used for grouping, and the grouped data as it's value.

Then I want to create an object for each "organizationId" used for grouping which will have three properties: id which will have the value for "organizationId", title which will have the value for "organizationTitle" and roles which is an array.

This array will contain objects for each grouped objects, this object will have two properties: id which will have the value for "roleId" and title which will have the value for "roleTitle".

So the result should look like this:

```<code>[
    {
        id: 'ORG_01',
        lib: 'Organization 01',
        roles: [
            {
                id: 1,
                title: 'Admin'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    },
      {
        id: 'ORG_02',
        lib: 'Organization 02',
        roles: [
            {
                id: 4,
                title: 'Referent'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    }
]
</code>```

So I did the following, which works and I get the expected result :

```<code>var organizations = [];

for(var i in filtered){
    var obj = {};
    obj.id = i;

    var roles = [];
    filtered[i].forEach(function(el){
        roles.push({'id' : el.roleId, 'lib': el.roleTitle})
        obj.lib = el.organizationTitle;
    });
    obj.roles = roles;
    organizations.push(obj);
}

console.log(organizations);
</code>```

As you can see I used too much code for this, first I used the reduce function then a forEeach and inisde it another forEach.

Isn't there a simple way doing that using vanillaJS (ES5) with the minimun code possible ?

Thanks in advance.

答:
You could do this with one loop:</p>

```<code> const result = [], hash = {};

 for(const {roleTitle : role, organizationId : id, organizationTitle : title, userId} of data){
   const key = id+"#"+title;
   if(hash[key]){
     hash[key].roles.push({ id: userId, role });
   } else {
     result.push(hash[key] = {
        id, title, roles : [{ id : userId, role}]
     });
  }
 }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following table which contains some objects :

var data = [
    {
        "userRoleId": 1,
        "userId": 1,
        "roleId": 1,
        "organizationId": "ORG_01",
        "roleTitle": "Admin",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": false,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 2,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_01",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 01",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 4,
        "userId": 1,
        "roleId": 4,
        "organizationId": "ORG_02",
        "roleTitle": "Referent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    },
    {
        "userRoleId": 5,
        "userId": 1,
        "roleId": 2,
        "organizationId": "ORG_02",
        "roleTitle": "Agent",
        "organizationTitle": "Organization 02",
        "startDate": "2017-11-15",
        "endDate": "2017-11-15",
        "automatic": true,
        "useDate": "2017-11-15"
    }
];

What I want to do is to group these objects using the object property "organizationId" and "organizationTitle", so what I tried is I grouped them using "organizationId" as following :

var filtered = data.reduce(function(accumulator, currentValue) {
    (accumulator[currentValue['organizationId']] = accumulator[currentValue['organizationId']] || []).push(currentValue);
    return accumulator;
  }, {});

This will generate an object with a key which has the value of each "organizationId" used for grouping, and the grouped data as it's value.

Then I want to create an object for each "organizationId" used for grouping which will have three properties: id which will have the value for "organizationId", title which will have the value for "organizationTitle" and roles which is an array.

This array will contain objects for each grouped objects, this object will have two properties: id which will have the value for "roleId" and title which will have the value for "roleTitle".

So the result should look like this:

[
    {
        id: 'ORG_01',
        lib: 'Organization 01',
        roles: [
            {
                id: 1,
                title: 'Admin'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    },
      {
        id: 'ORG_02',
        lib: 'Organization 02',
        roles: [
            {
                id: 4,
                title: 'Referent'
            },
            {
                id: 2,
                title: 'Agent'
            }
        ]
    }
]

So I did the following, which works and I get the expected result :

var organizations = [];

for(var i in filtered){
    var obj = {};
    obj.id = i;

    var roles = [];
    filtered[i].forEach(function(el){
        roles.push({'id' : el.roleId, 'lib': el.roleTitle})
        obj.lib = el.organizationTitle;
    });
    obj.roles = roles;
    organizations.push(obj);
}

console.log(organizations);

As you can see I used too much code for this, first I used the reduce function then a forEeach and inisde it another forEach.

Isn't there a simple way doing that using vanillaJS (ES5) with the minimun code possible ?

Thanks in advance.

Body:
You could do this with one loop:

 const result = [], hash = {};

 for(const {roleTitle : role, organizationId : id, organizationTitle : title, userId} of data){
   const key = id+"#"+title;
   if(hash[key]){
     hash[key].roles.push({ id: userId, role });
   } else {
     result.push(hash[key] = {
        id, title, roles : [{ id : userId, role}]
     });
  }
 }


问:
System.Runtime.InteropServices.COMException (0x80030020): The operation failed
I'm trying to save a Outlook.MailItem to a folder using:

MailItem.SaveAs(path, Outlook.OlSaveAsType.olMSG)

This works fine most of the time. However, when there's about 20 emails hitting Outlook at once, for a few of the I get the following exception:

```<code>System.Runtime.InteropServices.COMException (0x80030020): The operation failed.
   at Microsoft.Office.Interop.Outlook._MailItem.SaveAs(String Path, Object Type)
</code>```

I checked the code 0x80030020 which seems to mean "A share violation has occurred." However, I'm not sure what it means. In my application, I have the two below lines where the first one saves the email to a folder and the second method trying to POST that file to an API:

```<code>file = MailItemHelper.SaveMailItemToOFEFolder(mailItem);
bool isEmailSentByHttp = MailItemHelper.SendMailItemToOFEApi(_userid, file)
</code>```

The path has the subject of the email which is cleaned to remove non-alpha-numeric characters by doing:

```<code>Regex nonAlphaNumericRgx = new Regex(@"\W|_");
subject = nonAlphaNumericRgx.Replace(mail.Subject, "_");
</code>```

答:
I guess I can't tell directly what is the problem, but I can try giving you some tips.

According to MS documentation, Outlook seems to be using the StgOpenStorage function, throwing the STG_E_SHAREVIOLATION error:

Access denied because another caller has the file open and locked.

That means that either Outlook is messing up (the user clicked on the "message" and outlooks locks the file, or something else) or maybe after changing the file name with your regex your string ends up to be the same of another file, while it is in the middle of writing the other.

How are you hooking up to outlook? Is your app using a new thread per mail arrived? You could add a log4net and log all operations in your code, like:

```<code>// receive and email and store subject name on var subject
log.Info($"E mail with subject '{subject}' arrived.");
// convert name and save on var newSubject
log.Info($"Mail will be saved as '{newSubject}'.");
// notify the beginning of the operation
log.Info("Calling MailItemHelper.SaveMailItemToOFEFolder.");
// notify the end of the operation
log.Info("Mail saved successfully.");
// notify Post in REST API
log.Info("Sending in MailItemHelper.SendMailItemToOFEApi");
// notify end of Post in REST API
log.Info("MailItemHelper.SendMailItemToOFEApi sent");
</code>```

This will give a clear idea of how all mails are being retrieved and if there is some thread issues you can check which ones are finishing/starting first.

Body:
I'm trying to save a Outlook.MailItem to a folder using:

MailItem.SaveAs(path, Outlook.OlSaveAsType.olMSG)

This works fine most of the time. However, when there's about 20 emails hitting Outlook at once, for a few of the I get the following exception:

System.Runtime.InteropServices.COMException (0x80030020): The operation failed.
   at Microsoft.Office.Interop.Outlook._MailItem.SaveAs(String Path, Object Type)

I checked the code 0x80030020 which seems to mean "A share violation has occurred." However, I'm not sure what it means. In my application, I have the two below lines where the first one saves the email to a folder and the second method trying to POST that file to an API:

file = MailItemHelper.SaveMailItemToOFEFolder(mailItem);
bool isEmailSentByHttp = MailItemHelper.SendMailItemToOFEApi(_userid, file)

The path has the subject of the email which is cleaned to remove non-alpha-numeric characters by doing:

Regex nonAlphaNumericRgx = new Regex(@"\W|_");
subject = nonAlphaNumericRgx.Replace(mail.Subject, "_");

Body:
I guess I can't tell directly what is the problem, but I can try giving you some tips.

According to MS documentation, Outlook seems to be using the StgOpenStorage function, throwing the STG_E_SHAREVIOLATION error:

Access denied because another caller has the file open and locked.

That means that either Outlook is messing up (the user clicked on the "message" and outlooks locks the file, or something else) or maybe after changing the file name with your regex your string ends up to be the same of another file, while it is in the middle of writing the other.

How are you hooking up to outlook? Is your app using a new thread per mail arrived? You could add a log4net and log all operations in your code, like:

// receive and email and store subject name on var subject
log.Info($"E mail with subject '{subject}' arrived.");
// convert name and save on var newSubject
log.Info($"Mail will be saved as '{newSubject}'.");
// notify the beginning of the operation
log.Info("Calling MailItemHelper.SaveMailItemToOFEFolder.");
// notify the end of the operation
log.Info("Mail saved successfully.");
// notify Post in REST API
log.Info("Sending in MailItemHelper.SendMailItemToOFEApi");
// notify end of Post in REST API
log.Info("MailItemHelper.SendMailItemToOFEApi sent");

This will give a clear idea of how all mails are being retrieved and if there is some thread issues you can check which ones are finishing/starting first.


问:
Testing equivalence relation on dictionary in python

Given a relation as a list of tuples

```<code>[(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)]
</code>```

I have a dictionary that maps a key to list of its equivalent class

```<code>{1: [2, 3], 2: [3, 1, 2], 3: [2, 3]}
</code>```

I would like to write a function that, given this dictionary checks if relation is transitive and symmetric, which means

```<code>∀ a, b, c : if (a,b) ∈ Relation and (b,c) ∈ Relation ==> (a,c) ∈ Relation

∀ a, b : if (a,b) ∈ Relation ==> (b,a) ∈ Relation
</code>```

Is it possible to write this in an efficient way, without abusing nested loops? Using a dictionary is helpful in other parts of the program, but I am not sure if it is here.

Help?

答:
I don't think you need to use a dictionary here, because the relations are already easy to work with inside a list of tuples. If you use a dictionary, you would probably still end up converting it to a list of tuples with d.items() anyways.

Since these are relations, it really should be a set of tuples, not a list, which can have duplicates:

```<code>relations = {(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)}
</code>```

You can start off by making a function that checks if a relation is transitive:

```<code>def is_transitive(relation):
    for a, b in relation:
        for c, d in relation:
            # checks transitive property: (a, b) && (b, c) -> (a, c)
            if b == c and (a,d) not in relation:
                return False

    return True
</code>```

Then you can write a function that checks if a relation is symmetric with all():

```<code>def is_symmetric(relation):
    # checks symmetric property: (a, b) -> (b, a)
    return all(rel[::-1] in relation for rel in relation)
</code>```

Then you can just make a simple function which checks the conjunction of the above two functions:

```<code>def check_relation(relation):
    # True and True -> True
    # True and False -> False
    # False and True -> False
    # False and False -> False
    return is_symmetric(relation) and is_transitive(relation)
</code>```

Which works as follows (not extensively tested):

```<code>>>> relations = {(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)}
>>> print(check_relation(relations))
False
</code>```

Body:
Given a relation as a list of tuples

[(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)]

I have a dictionary that maps a key to list of its equivalent class

{1: [2, 3], 2: [3, 1, 2], 3: [2, 3]}

I would like to write a function that, given this dictionary checks if relation is transitive and symmetric, which means

∀ a, b, c : if (a,b) ∈ Relation and (b,c) ∈ Relation ==> (a,c) ∈ Relation

∀ a, b : if (a,b) ∈ Relation ==> (b,a) ∈ Relation

Is it possible to write this in an efficient way, without abusing nested loops? Using a dictionary is helpful in other parts of the program, but I am not sure if it is here.

Help?

Body:
I don't think you need to use a dictionary here, because the relations are already easy to work with inside a list of tuples. If you use a dictionary, you would probably still end up converting it to a list of tuples with d.items() anyways.

Since these are relations, it really should be a set of tuples, not a list, which can have duplicates:

relations = {(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)}

You can start off by making a function that checks if a relation is transitive:

def is_transitive(relation):
    for a, b in relation:
        for c, d in relation:
            # checks transitive property: (a, b) && (b, c) -> (a, c)
            if b == c and (a,d) not in relation:
                return False

    return True

Then you can write a function that checks if a relation is symmetric with all():

def is_symmetric(relation):
    # checks symmetric property: (a, b) -> (b, a)
    return all(rel[::-1] in relation for rel in relation)

Then you can just make a simple function which checks the conjunction of the above two functions:

def check_relation(relation):
    # True and True -> True
    # True and False -> False
    # False and True -> False
    # False and False -> False
    return is_symmetric(relation) and is_transitive(relation)

Which works as follows (not extensively tested):

>>> relations = {(1,2), (1,3), (2,3), (2,1), (2,2), (3,2), (3,3)}
>>> print(check_relation(relations))
False


问:
EF CTP5 error: Invalid object name
I followed the example on scottgu's  blog about EF code first CTP5 but I get the error that

System.Data.SqlClient.SqlException:
  Invalid object name 'dbo.Products'.

this is the code I got.

```<code><add name="CTP5Context"
     connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|EFCTP5.mdf;User Instance=true"
     providerName="System.Data.SqlClient" />

public class CTP5Context : DbContext
{
    public DbSet<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public int Amount { get; set; }
}

var context = new CTP5Context();
        var products = context.Products;

        return View(products);
</code>```

im kinda clueless here I done the same as the blogpost, its not my first time with EF (But CTP5 tho), I'm I overlooking something?

答:
Make sure your Products table was created with the dbo Schema, a lot of times  the schema will be something other than dbo, such as it can be your username or server name (if the account you're working with isnt in the db_owner schema). Open up the DB (since it's SQLExpress) with Server Explorer in Visual Studio)

To do this right click on the table name and select Open Table Definition then inside the table definition right click and select Properties and in the properties window check what is listed in the schema value. If it's not DBO then you should be able to change it to dbo and save it.

Title: EF CTP5 error: Invalid object name

Body:
I followed the example on scottgu's  blog about EF code first CTP5 but I get the error that

System.Data.SqlClient.SqlException:
  Invalid object name 'dbo.Products'.

this is the code I got.

<add name="CTP5Context"
     connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|EFCTP5.mdf;User Instance=true"
     providerName="System.Data.SqlClient" />

public class CTP5Context : DbContext
{
    public DbSet<Product> Products { get; set; }
}

public class Product
{
    public int Id { get; set; }
    public string ProductName { get; set; }
    public int Amount { get; set; }
}

var context = new CTP5Context();
        var products = context.Products;

        return View(products);

im kinda clueless here I done the same as the blogpost, its not my first time with EF (But CTP5 tho), I'm I overlooking something?


问:
Firebase authentication -Discarding data
As a beginner i am first time trying to work with firebase ,although as per process i did every thing i don't know where i am going wrong.
I'm working in Android Studio 3.0.1

Here is my gradle build file.

```<code>apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
    applicationId "courses.pluralsight.com.tabianconsulting"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
  "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
   }
   }

 dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
  {
    exclude group: 'com.android.support', module: 'support-annotations'
   })

compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:11.0.4'
testCompile 'junit:junit:4.12'
     }
 apply plugin: 'com.google.gms.google-services'
</code>```

After searching for long over the correct versions of sdk,firebase and google play service i am still unable to get it correct,tried combinaation and it isn't working .
Android SDK version 26.0.1
Google play service 46
Google repository 58

the error am getting is down below

```<code>        E/FA: Discarding data. Failed to send app launch
        E/FA: Failed to get app instance id
</code>```

Please some one help me out!!

答: From what I can gather, you need to go to your SDK manager and update your emulator to its latest version in order to support the firebase version you want to use. </p>

Body:
As a beginner i am first time trying to work with firebase ,although as per process i did every thing i don't know where i am going wrong.
I'm working in Android Studio 3.0.1

Here is my gradle build file.

apply plugin: 'com.android.application'

android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
    applicationId "courses.pluralsight.com.tabianconsulting"
    minSdkVersion 16
    targetSdkVersion 26
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
  "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
   }
   }

 dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',
  {
    exclude group: 'com.android.support', module: 'support-annotations'
   })

compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:11.0.4'
testCompile 'junit:junit:4.12'
     }
 apply plugin: 'com.google.gms.google-services'

After searching for long over the correct versions of sdk,firebase and google play service i am still unable to get it correct,tried combinaation and it isn't working .
Android SDK version 26.0.1
Google play service 46
Google repository 58

the error am getting is down below

        E/FA: Discarding data. Failed to send app launch
        E/FA: Failed to get app instance id

Please some one help me out!!


问:
Importing psf in eclipse issue?
I get this error while I'm trying to import this : http://www.jppf.org/private/svn-trunk-projectSet.psf into eclipse.

```<code>Building workspace has encountered a problem error occurred during the build
Errors occurred during the build.
Errors running builder 'Checkstyle Builder' on project 'admin'.
Fileset from project "admin" has no valid check configuration.
Fileset from project "admin" has no valid check configuration.
Fileset from project "admin" has no valid check configuration.
Fileset from project "admin" has no valid check configuration.
</code>```

Any suggestions what does it mean ?

Thank you

答:
This error means that your Eclipse project contains a .checkstyle configuration file which points to a non-existing Checkstyle configuration entry.

If you don't want to use Checkstyle you could simply delete the .checkstyle file.

If you want to use Checkstyle you should provide a valid location under Project -> Properties -> Checkstyle.

Title: Importing psf in eclipse issue?

Body:
I get this error while I'm trying to import this : http://www.jppf.org/private/svn-trunk-projectSet.psf into eclipse.

Building workspace has encountered a problem error occurred during the build
Errors occurred during the build.
Errors running builder 'Checkstyle Builder' on project 'admin'.
Fileset from project "admin" has no valid check configuration.
Fileset from project "admin" has no valid check configuration.
Fileset from project "admin" has no valid check configuration.
Fileset from project "admin" has no valid check configuration.

Any suggestions what does it mean ?

Thank you


问:
Jersey reading only first @QueryParam out of @BeanParam parameters
I have this Jersey POST resource :

```<code>@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response blablabla(InputStream inputStream,
@BeanParam ImportParams importParams) throws IOException, JAXBException, SAXException {
</code>```

Here is the ImportParams class :

```<code>public class ImportParams {
    @QueryParam(value = "importType")
    public ImportType importType = ImportType.MERGE;

    @ApiParam("Force stop point type for all stop points in file. Useful if no modality defined in the netex file.")
    @QueryParam(value = "forceStopType")
    public StopTypeEnumeration forceStopType;

}
</code>```

When I use curl to post to the the resource, only the first query parameter I specify after the question mark in the URL is read by jersey :

```<code>curl -XPOST -H"Content-Type: application/xml" -H"authorization: bearer $TOKEN" -d@$3  http://localhost:8585/services/stop_places/netex?forceStopType=TRAM_STATION&importType=MERGE

==> forceStopType has the right value, and importType is null

curl -XPOST -H"Content-Type: application/xml" -H"authorization: bearer $TOKEN" -d@$3  http://localhost:8585/services/stop_places/netex?importType=MERGE&forceStopType=TRAM_STATION

==> importType has the right value and forceStopType is null
</code>```

I've used @BeanParam many times before and it used to work, so I must be missing something obvious.... Thanks for your help

答:
Haha found out - stupid me. Had to put double quotes around the URL when cURLing :</p>

```<code>curl -XPOST -H"Content-Type: application/xml" -H"authorization: bearer $TOKEN" -d@$3  "http://localhost:8585/services/stop_places/netex?forceStopType=TRAM_STATION&importType=MERGE"
</code>```

Body:
I have this Jersey POST resource :

@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response blablabla(InputStream inputStream,
@BeanParam ImportParams importParams) throws IOException, JAXBException, SAXException {

Here is the ImportParams class :

public class ImportParams {
    @QueryParam(value = "importType")
    public ImportType importType = ImportType.MERGE;

    @ApiParam("Force stop point type for all stop points in file. Useful if no modality defined in the netex file.")
    @QueryParam(value = "forceStopType")
    public StopTypeEnumeration forceStopType;

}

When I use curl to post to the the resource, only the first query parameter I specify after the question mark in the URL is read by jersey :

curl -XPOST -H"Content-Type: application/xml" -H"authorization: bearer $TOKEN" -d@$3  http://localhost:8585/services/stop_places/netex?forceStopType=TRAM_STATION&importType=MERGE

==> forceStopType has the right value, and importType is null

curl -XPOST -H"Content-Type: application/xml" -H"authorization: bearer $TOKEN" -d@$3  http://localhost:8585/services/stop_places/netex?importType=MERGE&forceStopType=TRAM_STATION

==> importType has the right value and forceStopType is null

I've used @BeanParam many times before and it used to work, so I must be missing something obvious.... Thanks for your help

Body:
Haha found out - stupid me. Had to put double quotes around the URL when cURLing :

curl -XPOST -H"Content-Type: application/xml" -H"authorization: bearer $TOKEN" -d@$3  "http://localhost:8585/services/stop_places/netex?forceStopType=TRAM_STATION&importType=MERGE"


问:
For loop in python - beginner
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between

```<code>years = [n[1] for n in data]
</code>```

and

```<code>for n in data:
         years = n[1]
</code>```

here is the rest of the body

```<code>for m in years:
    if m not in year_counts:
        year_counts[m] = 0
    year_counts[m] += 1

print(year_counts)
</code>```

So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.

答:
```<code>li = [1, 2, 3, 4, 5, 6, 7]
# For loop uses for list iteration.
# for loop iterate every item in a list.

for i in li:
    print i

>>> 1
>>> 2
>>> 3
>>> 4
>>> 5
>>> 6
>>> 7
</code>```

Title: For loop in python - beginner

Body:
I'm trying to solve a project where i have to count the years in a list but I`m having problems understanding the difference between

years = [n[1] for n in data]

and

for n in data:
         years = n[1]

here is the rest of the body

for m in years:
    if m not in year_counts:
        year_counts[m] = 0
    year_counts[m] += 1

print(year_counts)

So if I use the first sentence then the code will run normally and will show the proper answer but if i use the second code it will give me random numbers I don't know from where.


问:
Keep all lines of a list with identical beginning (Notepad++)
From a list, how to keep all occurrences of those lines only whose "first part or beginning" (defined from the beginning of the line to the ^ character) is present in other lines? (The pattern of lines in the list: beginning-of-line^rest_of_line_012345)

The type of characters, length, etc. after the ^ is irrelevant (but needs to be kept). Every line has only one (1) ^ character. The "beginning" string that determines identity must be present in the same (analogous) position in other lines (i.e., from the beginning of the line to ^, and must be exact match). (Lines contain characters that trouble regex, such as \/()*., so these need to be summarily escaped.)

For example: Original list:

```<code>abc^123
0xyz^xxx
aaa-123^123
aaa-12^0xyz
0xyz^098
00xyz^098
0xyz^x111xx
</code>```

Keep all occurrences of lines with identical first part:

```<code>0xyz^xxx
0xyz^098
0xyz^x111xx
</code>```

This elegant script by @Lars Fischer    ((.*)\R(\2\R?)+)*\K.* (after pre-sorting) keeps all occurrences of duplicate lines, but it considers the entire line (it was designed to do so).

In this Q, I am looking for a solution that considers only the "beginning" of the line to see if it occurs more than once, and if yes, then keep the entire line. Any guidance?

答:
Note: in this solution the characters # and % are used based on the assumption that these characters do not show up ANYWHERE in the file to begin with. If that's not the case for you, just use different patterns that you know don't show up anywhere in the file, such as ##### and %%%%%.

Start by sorting the file Lexicographically with Notepad++ by going to Edit -> Line Operations -> Sort Lines Lexicographically Ascending

Do a regex Find-and-Replace (UNcheck the box for ". matches newline"):

Find what:

```<code>^(.*?)\^[^\r\n]+[\r\n]+(\1\^.*?[\r\n]+)*\1\^.*?$
</code>```

Replace with:

```<code>#$&%
</code>```

Now do another regex Find-and-Replace (CHECK the box for ". matches newline"):

Find what:

```<code>%.*?#
</code>```

Replace with:

```<code>\r\n
</code>```

Finally, do one last regex Find-and-Replace (CHECK the box for ". matches newline"):

Find what:

```<code>^.*?#|%.*
</code>```

Replace with nothing.

Body:
From a list, how to keep all occurrences of those lines only whose "first part or beginning" (defined from the beginning of the line to the ^ character) is present in other lines? (The pattern of lines in the list: beginning-of-line^rest_of_line_012345)

The type of characters, length, etc. after the ^ is irrelevant (but needs to be kept). Every line has only one (1) ^ character. The "beginning" string that determines identity must be present in the same (analogous) position in other lines (i.e., from the beginning of the line to ^, and must be exact match). (Lines contain characters that trouble regex, such as \/()*., so these need to be summarily escaped.)

For example: Original list:

abc^123
0xyz^xxx
aaa-123^123
aaa-12^0xyz
0xyz^098
00xyz^098
0xyz^x111xx

Keep all occurrences of lines with identical first part:

0xyz^xxx
0xyz^098
0xyz^x111xx

This elegant script by @Lars Fischer    ((.*)\R(\2\R?)+)*\K.* (after pre-sorting) keeps all occurrences of duplicate lines, but it considers the entire line (it was designed to do so).

In this Q, I am looking for a solution that considers only the "beginning" of the line to see if it occurs more than once, and if yes, then keep the entire line. Any guidance?

Body:
Note: in this solution the characters # and % are used based on the assumption that these characters do not show up ANYWHERE in the file to begin with. If that's not the case for you, just use different patterns that you know don't show up anywhere in the file, such as ##### and %%%%%.

Start by sorting the file Lexicographically with Notepad++ by going to Edit -> Line Operations -> Sort Lines Lexicographically Ascending

Do a regex Find-and-Replace (UNcheck the box for ". matches newline"):

Find what:

^(.*?)\^[^\r\n]+[\r\n]+(\1\^.*?[\r\n]+)*\1\^.*?$

Replace with:

#$&%

Now do another regex Find-and-Replace (CHECK the box for ". matches newline"):

Find what:

%.*?#

Replace with:

\r\n

Finally, do one last regex Find-and-Replace (CHECK the box for ". matches newline"):

Find what:

^.*?#|%.*

Replace with nothing.


问:
rails Gem's the Access the GMAIL, Y! Contact Lists via an API
Anyone know of any solid GEMs that integrate with the GMAIl and Y! Mail APIs to download a user's contacts (emails)?

thanks

答:
For gmail it's easy: https://rubygems.org/gems/gmail or maybe better for your purpose: https://rubygems.org/gems/gmail_contacts

I'm gonna have another look for yahoo...

EDIT 1:
yahoo is supposed to be part of https://github.com/mislav/contacts but no example given

EDIT 2:
Another way to see the question is to use the opensocial API as mentionned here. It could be a worthy generic solution even if resources are a bit scattered.


问:
What's wrong with this layout that's causing the elevation shadow not to appear?

I'm trying to use Android Elevation to achieve the 'shadow' look for a view. The following is the layout xml:

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sample.app.Main2Activity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clipChildren="false">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="165dp"
            android:background="#FFFFFF"
            android:padding="30dp"
            android:layout_margin="30dp"
            android:elevation="10dp"
            android:text="TextView" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>
</code>```

This is how the layout looks:
Look ma, no shadows!

Any suggestions to fix this?

答:
Here you go.... maybe you need someone to do it for you then....

I used a card view instead...

xml layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="5dp"
        card_view:contentPadding="10dp">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <TextView
                android:id="@+id/textView"
                android:text="hello"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/textView2"
                android:text="world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView"
                android:layout_marginTop="10dp"/>
        </RelativeLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>
</code>```

Add these to your app gradle file

```<code>compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'
</code>```

result:

and if you dont want to use a card view.....

xml -> layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/border"
            android:layout_margin="5dp"
            android:padding="5dp">

            <TextView
                android:id="@+id/textView"
                android:text="hello"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/textView2"
                android:text="world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView"
                android:layout_marginTop="10dp"/>
        </RelativeLayout>

</LinearLayout>
</code>```

@drawable/border

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <gradient
                android:centerColor="#D5E2ED"
                android:endColor="#0000"
                android:angle="90"/>
        </shape>
    </item>

    <item android:bottom="10dp">
        <shape>
            <solid android:color="#D5E2ED"/>
        </shape>
    </item>

    <!-- base background -->
    <item android:bottom="5dp" android:top="1dp">
        <shape android:shape="rectangle">
            <solid android:color="#fff"/>
            <padding android:bottom="10dp" android:top="10dp"/>
        </shape>
    </item>

</layer-list>
</code>```

result:

happy coding....

Body:
I'm trying to use Android Elevation to achieve the 'shadow' look for a view. The following is the layout xml:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sample.app.Main2Activity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clipChildren="false">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="165dp"
            android:background="#FFFFFF"
            android:padding="30dp"
            android:layout_margin="30dp"
            android:elevation="10dp"
            android:text="TextView" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

This is how the layout looks:
Look ma, no shadows!

Any suggestions to fix this?

Body:
Here you go.... maybe you need someone to do it for you then....

I used a card view instead...

xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_gravity="center"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="5dp"
        card_view:contentPadding="10dp">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <TextView
                android:id="@+id/textView"
                android:text="hello"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/textView2"
                android:text="world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView"
                android:layout_marginTop="10dp"/>
        </RelativeLayout>
    </android.support.v7.widget.CardView>

</LinearLayout>

Add these to your app gradle file

compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'

result:

and if you dont want to use a card view.....

xml -> layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="@drawable/border"
            android:layout_margin="5dp"
            android:padding="5dp">

            <TextView
                android:id="@+id/textView"
                android:text="hello"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:textStyle="bold"/>

            <TextView
                android:id="@+id/textView2"
                android:text="world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/textView"
                android:layout_marginTop="10dp"/>
        </RelativeLayout>

</LinearLayout>

@drawable/border

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Drop Shadow Stack -->
    <item>
        <shape>
            <gradient
                android:centerColor="#D5E2ED"
                android:endColor="#0000"
                android:angle="90"/>
        </shape>
    </item>

    <item android:bottom="10dp">
        <shape>
            <solid android:color="#D5E2ED"/>
        </shape>
    </item>

    <!-- base background -->
    <item android:bottom="5dp" android:top="1dp">
        <shape android:shape="rectangle">
            <solid android:color="#fff"/>
            <padding android:bottom="10dp" android:top="10dp"/>
        </shape>
    </item>

</layer-list>

result:

happy coding....


问:
How coloring data frame in R
I have data frame of the following type

```<code>> df
              V1 V2 V3 V4 V5
1   10.603.3.100  2  1  5  1
2   10.603.3.101  3  2  4  5
3   10.603.3.102  1  3  3  2
4   10.603.1.103  4  4  3  3
5   10.603.3.104  5  5  1  4
</code>```

And the task is to colorize values by any palette by columns V2, V3, V4, V5. But unfortunately I have absolutely no ideas how to do it. The forum found answers to the question of coloring in two colors.

Something similar

答:
If I understood your question correctly then you may use library(DT) to colorise your columns like below:

?datatable from DT package:

This function creates an HTML widget to display rectangular data (a
  matrix or data frame) using the JavaScript library DataTables.

```<code>df <- head(iris, 10)
library(tidyverse)
library(DT)

datatable(df, rownames = FALSE) %>%
  formatStyle(columns = "Sepal.Length",
              backgroundColor = "yellow") %>%
  formatStyle(columns = "Sepal.Width",
              backgroundColor = "blue") %>%
  formatStyle(columns = "Petal.Width",
              backgroundColor = "green")
</code>```

New EDIT after OP added Picture:

```<code>df <- data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))

breaks <- quantile(df, probs = seq(.05, .95, .05), na.rm = TRUE)
colors <- round(seq(255, 40, length.out = length(breaks) + 1), 0) %>%
  {paste0("rgb(255,", ., ",", ., ")")}
datatable(df) %>% formatStyle(names(df), backgroundColor = styleInterval(breaks, colors))
</code>```

You can check more from here:

The above example is taken straight from the above place, Please note that if you want to change the color you have to change the "colors" object with different value of rgb, for example if you change the above string with
this:

```<code>colors <- round(seq(255, 40, length.out = length(breaks) + 1), 0) %>%
  {paste0("rgb(", ., ",255,", ., ")")}
</code>```

You will get parrot green flavour instead of red.

Title: How coloring data frame in R

Body:
I have data frame of the following type

> df
              V1 V2 V3 V4 V5
1   10.603.3.100  2  1  5  1
2   10.603.3.101  3  2  4  5
3   10.603.3.102  1  3  3  2
4   10.603.1.103  4  4  3  3
5   10.603.3.104  5  5  1  4

And the task is to colorize values by any palette by columns V2, V3, V4, V5. But unfortunately I have absolutely no ideas how to do it. The forum found answers to the question of coloring in two colors.

Something similar

Body:
If I understood your question correctly then you may use library(DT) to colorise your columns like below:

?datatable from DT package:

This function creates an HTML widget to display rectangular data (a
  matrix or data frame) using the JavaScript library DataTables.

df <- head(iris, 10)
library(tidyverse)
library(DT)

datatable(df, rownames = FALSE) %>%
  formatStyle(columns = "Sepal.Length",
              backgroundColor = "yellow") %>%
  formatStyle(columns = "Sepal.Width",
              backgroundColor = "blue") %>%
  formatStyle(columns = "Petal.Width",
              backgroundColor = "green")

New EDIT after OP added Picture:

df <- data.frame(cbind(matrix(round(rnorm(50), 3), 10), sample(0:1, 10, TRUE)))

breaks <- quantile(df, probs = seq(.05, .95, .05), na.rm = TRUE)
colors <- round(seq(255, 40, length.out = length(breaks) + 1), 0) %>%
  {paste0("rgb(255,", ., ",", ., ")")}
datatable(df) %>% formatStyle(names(df), backgroundColor = styleInterval(breaks, colors))

You can check more from here:

The above example is taken straight from the above place, Please note that if you want to change the color you have to change the "colors" object with different value of rgb, for example if you change the above string with
this:

colors <- round(seq(255, 40, length.out = length(breaks) + 1), 0) %>%
  {paste0("rgb(", ., ",255,", ., ")")}

You will get parrot green flavour instead of red.


问:
LINQ - Need to find ID of existing or created record
The query below check to see if a Folder record exist. If not, it creates a new record. Note that the Folder table has a primary key called ID that is an auto incremented. I need to find out what the ID was of the record that was created or already existed.  Need an efficient way of doing it. Currently I do am doing a long about way to find it.  </p>

```<code>// Checks to see if record exist
 var record = (from pl in db.Folders
               where pl.FolderSystem == "OP"
               && pl.OrgID == orgID
               select pl).FirstOrDefault();

// If does not exist create the record
 if (record == null)
 {
   db.Folders.Add(
             new Folders
             {
                 OrgID = orgID,
                 FolderSystem = "OP",
                 CreatedUserID = 1,
                 CreatedDate = DateTime.UtcNow,
              });

             db.SaveChanges();
 }
</code>```

<p>Now I need to find the ID of the record that existed or needed to be created.  Need Folder.ID. Is there a more efficient way to find it. I am open to restructuring the query. </p>

答:
If in any scenario you only want to know whether a record exists you don't have to pull the entire entity from the database:

```<code>var exists = db.Folders.Any(f => f.FolderSystem == "OP"
                              && f.OrgID == orgID);
</code>```

This executes a cheap EXISTS query and returns a boolean.  About as light-weight as it gets.

If you want to know the ID of the existing record (for some reason) there is another light-weight pattern:

```<code>var id = db.Folders.Where(f => f.FolderSystem == "OP"
                            && f.OrgID == orgID)
                   .Select(f => f.ID).FirstOrDefault();
</code>```

This only queries one integer value (or null) from the database, still not the entire entity.

Now you can proceed by:

```<code>if(!id.HasValue)
{
    // Use an explicit variable for the new entity
    var record = new Folders
         {
             OrgID = orgID,
             FolderSystem = "OP",
             CreatedUserID = 1,
             CreatedDate = DateTime.UtcNow,
          });
    db.Folders.Add(record);
    db.SaveChanges();
    id = record.ID;
}
</code>```

So id will either be the retrieved (existing) value or the new value.

Note that in your case you're not out of the woods yet. There's always a chance that right between the first query and your insert a second user inserts the same id. You always have to catch unique constraint exceptions.

Body:
The query below check to see if a Folder record exist. If not, it creates a new record. Note that the Folder table has a primary key called ID that is an auto incremented. I need to find out what the ID was of the record that was created or already existed.  Need an efficient way of doing it. Currently I do am doing a long about way to find it.

// Checks to see if record exist
 var record = (from pl in db.Folders
               where pl.FolderSystem == "OP"
               && pl.OrgID == orgID
               select pl).FirstOrDefault();

// If does not exist create the record
 if (record == null)
 {
   db.Folders.Add(
             new Folders
             {
                 OrgID = orgID,
                 FolderSystem = "OP",
                 CreatedUserID = 1,
                 CreatedDate = DateTime.UtcNow,
              });

             db.SaveChanges();
 }

Now I need to find the ID of the record that existed or needed to be created.  Need Folder.ID. Is there a more efficient way to find it. I am open to restructuring the query.

Body:
If in any scenario you only want to know whether a record exists you don't have to pull the entire entity from the database:

var exists = db.Folders.Any(f => f.FolderSystem == "OP"
                              && f.OrgID == orgID);

This executes a cheap EXISTS query and returns a boolean.  About as light-weight as it gets.

If you want to know the ID of the existing record (for some reason) there is another light-weight pattern:

var id = db.Folders.Where(f => f.FolderSystem == "OP"
                            && f.OrgID == orgID)
                   .Select(f => f.ID).FirstOrDefault();

This only queries one integer value (or null) from the database, still not the entire entity.

Now you can proceed by:

if(!id.HasValue)
{
    // Use an explicit variable for the new entity
    var record = new Folders
         {
             OrgID = orgID,
             FolderSystem = "OP",
             CreatedUserID = 1,
             CreatedDate = DateTime.UtcNow,
          });
    db.Folders.Add(record);
    db.SaveChanges();
    id = record.ID;
}

So id will either be the retrieved (existing) value or the new value.

Note that in your case you're not out of the woods yet. There's always a chance that right between the first query and your insert a second user inserts the same id. You always have to catch unique constraint exceptions.


问:
Bootstrap - dropdown menu close on click in Datepicker
I am working with Bootstrap and date picker. I added a datepicker in boostrap dowpdown. When selecting the date the dropdown closes automatically. Refer the image for more info:

Action 1: Click the dropdown button, We see the dropdown list.
Action 2: When clicking on the fiel. I will dynamically add datepicker.
After the action 3: When selecting on the Date. The Dropdown is getting close so The user is back to Action 1.

What i am trying to do is After the user click the Date. The dropdown should not close.

I am using the following code to prevent the click which workes on the table inside the dropdown but not with the date picker.

```<code>$(document).on('click', '.dropdown-menu', function(e) {
            if ($(this).hasClass('keep-open-on-click')) { e.stopPropagation(); }
        });
</code>```

Can some one help me to prevent the dropdown close.

```<code><div class="dropdown">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"><span class="icon16 icomoon-icon-bell"></span><span class="notification" id="notification_count">11</span>
                    </a>
  <ul class="dropdown-menu keep-open-on-click">
    <li><a href="#">HTML</a></li>
    <li><a href="#">CSS</a></li>
    <li><a href="#">JavaScript</a></li>
  </ul>
</div>
</code>```

Note: The datepicker will be added dynamically when the user clicks on the table to end it the date. So is that the problem?

答:
This one was very troublesome. I also have a couple of datepickers located within some Bootstrap drop-down menus. I solved this using two ways.

The first uses jQuery to stop the event from bubbling up one time when the DatePicker is clicked

```<code>$('.yourDatePicker').on('hide', function(event) {
    event.stopPropagation();
    $(this).closest('.yourDropDown').one('hide.bs.dropdown', function(ev) {
       return false;
   });
});
</code>```

The other, more permant solution was to change the datepicker.js file itself. If you crack it open you will find code that looks like this

```<code>click: function(e){
        e.preventDefault();
        var target = $(e.target).closest('span, td, th'),
            year, month, day;
        if (target.length === 1){
            switch (target[0].nodeName.toLowerCase()){
...ect...
</code>```

If you add a e.stopPropagation() function to this area, like this

```<code>click: function(e){
        e.preventDefault();
        e.stopPropagation(); // <-- add this
        var target = $(e.target).closest('span, td, th'),
            year, month, day;
        if (target.length === 1){
            switch (target[0].nodeName.toLowerCase()){
</code>```

your datepickers will stop interfering with your other DOM elements, though this solution is more widespread, and I would test to make sure it doesn't impact other areas in your code.

Body:
I am working with Bootstrap and date picker. I added a datepicker in boostrap dowpdown. When selecting the date the dropdown closes automatically. Refer the image for more info:

Action 1: Click the dropdown button, We see the dropdown list.
Action 2: When clicking on the fiel. I will dynamically add datepicker.
After the action 3: When selecting on the Date. The Dropdown is getting close so The user is back to Action 1.

What i am trying to do is After the user click the Date. The dropdown should not close.

I am using the following code to prevent the click which workes on the table inside the dropdown but not with the date picker.

$(document).on('click', '.dropdown-menu', function(e) {
            if ($(this).hasClass('keep-open-on-click')) { e.stopPropagation(); }
        });

Can some one help me to prevent the dropdown close.

  11

HTML

CSS

JavaScript

Note: The datepicker will be added dynamically when the user clicks on the table to end it the date. So is that the problem?

Body:
This one was very troublesome. I also have a couple of datepickers located within some Bootstrap drop-down menus. I solved this using two ways.

The first uses jQuery to stop the event from bubbling up one time when the DatePicker is clicked

$('.yourDatePicker').on('hide', function(event) {
    event.stopPropagation();
    $(this).closest('.yourDropDown').one('hide.bs.dropdown', function(ev) {
       return false;
   });
});

The other, more permant solution was to change the datepicker.js file itself. If you crack it open you will find code that looks like this

click: function(e){
        e.preventDefault();
        var target = $(e.target).closest('span, td, th'),
            year, month, day;
        if (target.length === 1){
            switch (target[0].nodeName.toLowerCase()){
...ect...

If you add a e.stopPropagation() function to this area, like this

click: function(e){
        e.preventDefault();
        e.stopPropagation(); // <-- add this
        var target = $(e.target).closest('span, td, th'),
            year, month, day;
        if (target.length === 1){
            switch (target[0].nodeName.toLowerCase()){

your datepickers will stop interfering with your other DOM elements, though this solution is more widespread, and I would test to make sure it doesn't impact other areas in your code.


答: I'd go with second version since it'll reduce loop cycles count. Still if there're too much values mapping to the same int, you can split them up in separate hash elements.</p>

Title: Faster to consolidate regexes in a hash of regexes in Ruby?

Body:
I have a string that I want to map to an integer. Many strings can map to the same integer, so I'm using regexes to match strings that should map to the same integer.

Example:

str = "hello"

REGEXES.each do |key, val|
  if str =~ key
    print val
  end
end

where REGEXES is a hash that maps regex to integer.

Which is better:

REGEXES = [/hello/ => 2, /foo/ => 2, /bar/ => 3]

or

REGEXES = [/(hello|foo)/ => 2, /bar/ => 3]


问:
Unmerge/remove git branch that was merged into master dozens of commits ago
A large feature branch was approved and merged into master a week or so ago.  Right before release it was decided that it needs to be pulled, but several of the bug fixes that were merged into master do need to be released. The problem is that these bug fixes were either based off the point in master after where the feature was merged in, or they had a late version of master pulled into them.

```<code>             __bad-feature __
master______/_________________\_____________________________________
       \                             ^         /    \_bug-fix-1__/
        \___bug-fix-2_____[pull from master]__/
</code>```

So I've tried just cherrypicking the bugfix commits.  This doesn't work because they largely have the feature merged in somewhere in the middle.  I was trying to figure out how to "replay" the individual bug fix commits over a "bad-feature" free version of master.  This sounds like a thing that should be possible?

Short of grabbing individual files in each bugfix branch, is there a better way to extract this branch from master?

答:
It looks like I was having issues because I was trying to cherrypick the commits at the end of the bugfix branches.  What I ended up doing is individually cherrypicking all the commits I wanted from the bugfix branches (and excluding the commits that tied into bad-feature).

Like @evolutionxbox suggested, I applied those commits to the end of a new branch that diverged from master right before the bad-feature.

Body:
A large feature branch was approved and merged into master a week or so ago.  Right before release it was decided that it needs to be pulled, but several of the bug fixes that were merged into master do need to be released. The problem is that these bug fixes were either based off the point in master after where the feature was merged in, or they had a late version of master pulled into them.

             __bad-feature __
master______/_________________\_____________________________________
       \                             ^         /    \_bug-fix-1__/
        \___bug-fix-2_____[pull from master]__/

So I've tried just cherrypicking the bugfix commits.  This doesn't work because they largely have the feature merged in somewhere in the middle.  I was trying to figure out how to "replay" the individual bug fix commits over a "bad-feature" free version of master.  This sounds like a thing that should be possible?

Short of grabbing individual files in each bugfix branch, is there a better way to extract this branch from master?