问:
regex condition out of log file using python way
I have a log file needed to extract and I'm using a regex way in python to extract the data but i can't figure out the correct condition to extract the bunch of text.

Right now for the current condition was selecting the undesired text but still able to get the portion of the text i needed.

Hope someone can help me.

Here is the regex condition that im using:

```<code>(Item|Chamber|DC|Etch|Depo)\s+[^:].+
</code>```

here is the url where i test it:

http://myregexp.com/

sample log file:

```<code>Nexus Cluster Tool Controller     Process Data Log

Version CTCflex V2.102.00

Data Log Name: 2017-03-01_001_A2B

Tool ID: B

User ID: Maintenance-C

Run Number: 01

Number of Steps:  0

Schedule: DLCX_ARO2_6535_15A_PORD2=PRD

Run Date: 2017-03-01 (Y M D)

Run Start Time: 00:20:56

Wafer from LLA Slot 02 (Wafer ID:2017-03-01_001_A2B)

Module

Module              : PM3 (DLCXIC)

PM Software Version : PMflex2008 (DLCX) Version 02.104.00.00

Process Name        : PM3_ARO2_Ni35A_fillin_2AD2.prc

Step Number     : 1

Step Name       : CouponcheckD2

Step Time       : 00:00:15.000

Run Time        : 01Mar17 00:22:39

Chamber Pressure    : 1.6e-006

Depo Source-DC Source Parameters

    Use Source                : False

    Continuous Beam           : False

    Depo ControlMode          : Continuous

    Depo RegulationMode       : Continuous

    Depo RampTime       (Sec) :     0.000

    Depo Power            (W) :     0.0

    Depo Voltage          (V) :     0.0

    Depo JoulesQuantity       :     0.0

    Depo PulseMode            : False

    Depo PulseFrequency  (kHz):     0.0

    Depo PulseReverseTime (uS):     0.0

     Depo ArcDetectEnabled     : False

     Depo ArcCountAlarm        : 10000

     Depo ArcResetDelay        :     1

    Depo Gas 1 Flow    (SCCM) :     0.0

    Depo Gas 2 Flow    (SCCM) :     0.0

Etch Source Parameters

    Use Source                : False

    Beam At Start             : Shutoff

    Beam At End               : Shutoff

    Neutralizer On            : False

    Continuous Beam           : False

    Beam Voltage          (V) :     0.0

    Beam Current         (mA) :     0.0

    Suppressor Voltage    (V) :     0.0

    Incident RF Power     (W) :     0.0

    K Factor                  :     0.0

    Etch Gas 1 Flow    (SCCM) :     0.0

    Etch Gas 2 Flow    (SCCM) :     0.0

    Etch Gas 3 Flow    (SCCM) :     0.0

    PBN Gas Flow       (SCCM) :     0.0

    Source Magnet             :

        Use Source Magnet     : False

        Current           (A) :     0.000

Control Parameters

    Step Ends By              : Time

    Time Total Seconds        :    15.000

    End Pressure Setpoint     : 2.0e-007

    Power Down Sources        : False

Fixture Parameters

    Tilt Angle                : -55.0

    Rotate Fixture            : True

    Rotation Speed      (RPM) : 30.0

Shutter Parameters

    Depo Shutter At Start     : Closed

    Depo Shutter At Process   : Closed

    Depo Shutter At End       : Closed

    Etch Shutter At Start     : Open

    Etch Shutter At Process   : Open

    Etch Shutter At End       : Open

Data Tracing Parameters

    Tracing Enabled           : True

    Interval            (Sec) :    1

Ellipsometer Parameters

    Monitor                   : True

    Step Type                 : View

    Points or Angstroms       :     4.0

    Model Name                : Model1

Process Results

    Step Elapsed Time         : 00:00:15.000

    Step Remaining Time       : 00:00:00.000

Process Statistics

Item Name                                       Minimum     Maximum        Mean      StdDev      Median

Chamber Pressure                                1.6e-006    1.7e-006    1.6e-006    2.5e-008    1.6e-006

DC Current Current  (mA)                           0.010       0.010       0.010       0.000       0.010

DC Current Impedance                               0.000       0.000       0.000       0.000       0.000

DC Current Power (W)                               0.000       0.000       0.000       0.000       0.000

DC Current Voltage (V)                             0.000       0.000       0.000       0.000       0.000

Etch Beam Voltage (V)                              4.746       4.746       4.746       0.000       4.746

Etch Beam Current (mA)                             3.900       3.900       3.900       0.000       3.900

Etch Suppressor Voltage (V)                        1.409       1.593       1.438       0.069       1.409

Etch Suppressor Current (mA)                       0.000       0.000       0.000       0.000       0.000

Etch Forward RF Power (W)                          0.000       0.000       0.000       0.000       0.000

Etch Reflected RF Power (W)                        0.000       0.000       0.000       0.000       0.000

Etch PBN Filament (A)                              0.104       0.110       0.105       0.002       0.104

Etch PBN Body (A)                                  0.001       0.002       0.002       0.001       0.002

Etch Source Magnet (A)                             0.003       0.004       0.004       0.000       0.004

Depo Gas 1 Actual Flow (SCCM)                      0.679       0.679       0.679       0.000       0.679

Depo Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch Gas 1 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch Gas 3 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch PBN Gas Actual Flow (SCCM)                    0.000       0.000       0.000       0.000       0.000

Events Which Occurred During The Process:

03/01/2017 00:22:10.279   U:Event:   Current Process Recipe Name = PM3_ARO2_Ni35A_fillin_2AD2.prc [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.279   U:Event:   Current Step Number = 1 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.279   U:Event:   Current Step = CouponcheckD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.281   U:Event:   Current Step Number = 2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.281   U:Event:   Current Step = ArWarmupD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.283   U:Event:   Current Step Number = 3 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.283   U:Event:   Current Step = ArStableD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.284   U:Event:   Current Step Number = 4 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.284   U:Event:   Current Step = ArO2WarmupD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.286   U:Event:   Current Step Number = 5 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.286   U:Event:   Current Step = ArO2_EtchD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.288   U:Event:   Current Step Number = 6 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.288   U:Event:   Current Step = ArO2PurgeD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.290   U:Event:   Current Step Number = 7 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.290   U:Event:   Current Step = EtchwarmD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.292   U:Event:   Current Step Number = 8 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.292   U:Event:   Current Step = EtchstableD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.294   U:Event:   Current Step Number = 9 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.294   U:Event:   Current Step = PTREtch_6535D2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.296   U:Event:   Current Step Number = 10 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.296   U:Event:   Current Step = SiNstartD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.298   U:Event:   Current Step Number = 11 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.298   U:Event:   Current Step = SiNfillinD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.300   U:Event:   Current Step Number = 12 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.300   U:Event:   Current Step = SiNviewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.301   U:Event:   Current Step Number = 13 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.302   U:Event:   Current Step = EtchbackNewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.303   U:Event:   Current Step Number = 14 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.303   U:Event:   Current Step = SiNviewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.305   U:Event:   Current Step Number = 15 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.305   U:Event:   Current Step = SiNstartD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.306   U:Event:   Current Step Number = 16 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.306   U:Event:   Current Step = SiNdepo_2AD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.308   U:Event:   Current Step Number = 17 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.308   U:Event:   Current Step = SiNviewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.472   U:Event:   Current Step Number = 1 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.472   U:Event:   Current Step = CouponcheckD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.475   U:Event:   Waiting for Process Pressure [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.660   U:Event:   Waiting for Process Start Pressure [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.821   U:Event:   Process Starting [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.821   U:Event:   Waiting for Source PreStart [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:13.743   U:Event:   Clamping Wafer for Processing [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:22.500   U:Event:   Wafer is clamped for Processing [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:22.955   U:Event:   Configuring Rotation Axis to Step Configuration [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:23.001   U:Event:   Sequence MotionToInitialPosition - Moving Fixture to process position [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:42.232   U:Event:   Waiting for Step to Complete [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:57.041   U:Event:   Step Completed. [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:58.002   U:Event:   Current Step Number = 2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:58.003   U:Event:   Current Step = ArWarmupD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:59.312   U:Event:   Configuring Rotation Axis to Step Configuration [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:59.398   U:Event:   Sequence MotionToInitialPosition - Moving Fixture to -135 degrees [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:09.269   U:Event:   Sequence MotionToInitialPosition - Moving Etch Shutter to Initial Position [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:15.622   U:Event:   SourceManager RF Generator Status Update: External Interlock - OK [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:15.758   U:Event:   Etch : Ramping Started [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:17.767   U:Event:   Etch: Gas is stable... [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:25.779   U:Event:   Etch: Turning On RF [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:39.709   U:Event:   Etch: Igniting Beam... [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:40.797   U:Event:   Etch: Waiting for the beam to stabilize/regulate... [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:44.370   U:Event:   Etch: Beam stabilized/regulated. [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:46.120   U:Event:   Source 'SourceManager_Etch' has indicated an error. [LLA_02] [2017-03-01_001_A2B]

Alarms Which Occurred During The Process:

03/01/2017 00:23:46.013   U:Alarm:   Etch: Maximum Suppressor Current Limit Detected (SI=0.298)! [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:46.120   U:Alarm:   Sequence IgniteBeam - Failed to Ignite all Sources [LLA_02] [2017-03-01_001_A2B]

Data Log Event: Process Aborted

Process has been abnormally terminated. - 03/01/2017 00:23:46.251

    Processing should be continued from:

        Process Name:   PM3_ARO2_Ni35A_fillin_2AD2.prc

        Step Name:      ArWarmupD2

        Step Number:    2

        Elapsed Time:   0.000

        Remaining Time: 60.000

        Total Steps:    17
</code>```

Here is the sample portion i want to extract per step:

```<code> Item Name                                       Minimum     Maximum        Mean      StdDev      Median

    Chamber Pressure                                1.6e-006    1.7e-006    1.6e-006    2.5e-008    1.6e-006

    DC Current Current  (mA)                           0.010       0.010       0.010       0.000       0.010

    DC Current Impedance                               0.000       0.000       0.000       0.000       0.000

    DC Current Power (W)                               0.000       0.000       0.000       0.000       0.000

    DC Current Voltage (V)                             0.000       0.000       0.000       0.000       0.000

    Etch Beam Voltage (V)                              4.746       4.746       4.746       0.000       4.746

    Etch Beam Current (mA)                             3.900       3.900       3.900       0.000       3.900

    Etch Suppressor Voltage (V)                        1.409       1.593       1.438       0.069       1.409

    Etch Suppressor Current (mA)                       0.000       0.000       0.000       0.000       0.000

    Etch Forward RF Power (W)                          0.000       0.000       0.000       0.000       0.000

    Etch Reflected RF Power (W)                        0.000       0.000       0.000       0.000       0.000

    Etch PBN Filament (A)                              0.104       0.110       0.105       0.002       0.104

    Etch PBN Body (A)                                  0.001       0.002       0.002       0.001       0.002

    Etch Source Magnet (A)                             0.003       0.004       0.004       0.000       0.004

    Depo Gas 1 Actual Flow (SCCM)                      0.679       0.679       0.679       0.000       0.679

    Depo Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch Gas 1 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch Gas 3 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch PBN Gas Actual Flow (SCCM)                    0.000       0.000       0.000       0.000       0.000
</code>```

答:
Regex by your request is:

```<code>(?P<Item>(Item|Chamber|DC|Etch|Depo)(\s{1,3}\w*){1,5}(\((mA|A|W|V|SCCM)\))?)\s{4,}(?P<minimum>[0-9]\.[0-9e-]+)\s+(?P<maximum>[0-9]\.[0-9e-]+)\s+(?P<mean>[0-9]\.[0-9e-]+)\s+(?P<stddev>[0-9]\.[0-9e-]+)\s+(?P<median>[0-9]\.[0-9e-]+)
</code>```

This way you will have 6 regex named groups: item, minimum, maximum mean, stddev and median which you can extract in python code by groupdict() method.

Also don't forget to enable MULTILINE flag if you're using web sites for check your regex (in python it's re.MULTILINE).

This is how groupdict() method works:

import re
h_regex = re.match(r'(?P<hello>H)', 'Hello', re.MULTILINE)
print(h_regex.groupdict())
```

<p>Good luck and thanks for such complex and interesting question! :)</p>

<p>You can check it with details in http://pythex.org/, it's more convenient than http://myregexp.com/ in my opinion. </p>

<p><strong>UPD:</strong> python 3 script (just get correct input filename): </p>

<pre class="lang-py prettyprint-override"><code>import re

input_filename = 'log.txt'
pattern = re.compile(r'(?P<item>(Item|Chamber|DC|Etch|Depo)(\s{1,3}\w*){1,5}(\((mA|A|W|V|SCCM)\))?)\s{4,}(?P<minimum>[0-9]\.[0-9e-]+)\s+(?P<maximum>[0-9]\.[0-9e-]+)\s+(?P<mean>[0-9]\.[0-9e-]+)\s+(?P<stddev>[0-9]\.[0-9e-]+)\s+(?P<median>[0-9]\.[0-9e-]+)')
matched = []

with open(input_filename, 'r') as f:
    log_content = f.readlines()

for line in log_content:
    result = re.match(pattern, line)
    if result:
        matched.append(result)

for line in matched:
    print(line.groupdict())
</code>```

Body:
I have a log file needed to extract and I'm using a regex way in python to extract the data but i can't figure out the correct condition to extract the bunch of text.

Right now for the current condition was selecting the undesired text but still able to get the portion of the text i needed.

Hope someone can help me.

Here is the regex condition that im using:

(Item|Chamber|DC|Etch|Depo)\s+[^:].+

here is the url where i test it:

http://myregexp.com/

sample log file:

Nexus Cluster Tool Controller     Process Data Log

Version CTCflex V2.102.00

Data Log Name: 2017-03-01_001_A2B

Tool ID: B

User ID: Maintenance-C

Run Number: 01

Number of Steps:  0

Schedule: DLCX_ARO2_6535_15A_PORD2=PRD

Run Date: 2017-03-01 (Y M D)

Run Start Time: 00:20:56

Wafer from LLA Slot 02 (Wafer ID:2017-03-01_001_A2B)

Module

Module              : PM3 (DLCXIC)

PM Software Version : PMflex2008 (DLCX) Version 02.104.00.00

Process Name        : PM3_ARO2_Ni35A_fillin_2AD2.prc

Step Number     : 1

Step Name       : CouponcheckD2

Step Time       : 00:00:15.000

Run Time        : 01Mar17 00:22:39

Chamber Pressure    : 1.6e-006

Depo Source-DC Source Parameters

    Use Source                : False

    Continuous Beam           : False

    Depo ControlMode          : Continuous

    Depo RegulationMode       : Continuous

    Depo RampTime       (Sec) :     0.000

    Depo Power            (W) :     0.0

    Depo Voltage          (V) :     0.0

    Depo JoulesQuantity       :     0.0

    Depo PulseMode            : False

    Depo PulseFrequency  (kHz):     0.0

    Depo PulseReverseTime (uS):     0.0

     Depo ArcDetectEnabled     : False

     Depo ArcCountAlarm        : 10000

     Depo ArcResetDelay        :     1

    Depo Gas 1 Flow    (SCCM) :     0.0

    Depo Gas 2 Flow    (SCCM) :     0.0

Etch Source Parameters

    Use Source                : False

    Beam At Start             : Shutoff

    Beam At End               : Shutoff

    Neutralizer On            : False

    Continuous Beam           : False

    Beam Voltage          (V) :     0.0

    Beam Current         (mA) :     0.0

    Suppressor Voltage    (V) :     0.0

    Incident RF Power     (W) :     0.0

    K Factor                  :     0.0

    Etch Gas 1 Flow    (SCCM) :     0.0

    Etch Gas 2 Flow    (SCCM) :     0.0

    Etch Gas 3 Flow    (SCCM) :     0.0

    PBN Gas Flow       (SCCM) :     0.0

    Source Magnet             :

        Use Source Magnet     : False

        Current           (A) :     0.000

Control Parameters

    Step Ends By              : Time

    Time Total Seconds        :    15.000

    End Pressure Setpoint     : 2.0e-007

    Power Down Sources        : False

Fixture Parameters

    Tilt Angle                : -55.0

    Rotate Fixture            : True

    Rotation Speed      (RPM) : 30.0

Shutter Parameters

    Depo Shutter At Start     : Closed

    Depo Shutter At Process   : Closed

    Depo Shutter At End       : Closed

    Etch Shutter At Start     : Open

    Etch Shutter At Process   : Open

    Etch Shutter At End       : Open

Data Tracing Parameters

    Tracing Enabled           : True

    Interval            (Sec) :    1

Ellipsometer Parameters

    Monitor                   : True

    Step Type                 : View

    Points or Angstroms       :     4.0

    Model Name                : Model1

Process Results

    Step Elapsed Time         : 00:00:15.000

    Step Remaining Time       : 00:00:00.000

Process Statistics

Item Name                                       Minimum     Maximum        Mean      StdDev      Median

Chamber Pressure                                1.6e-006    1.7e-006    1.6e-006    2.5e-008    1.6e-006

DC Current Current  (mA)                           0.010       0.010       0.010       0.000       0.010

DC Current Impedance                               0.000       0.000       0.000       0.000       0.000

DC Current Power (W)                               0.000       0.000       0.000       0.000       0.000

DC Current Voltage (V)                             0.000       0.000       0.000       0.000       0.000

Etch Beam Voltage (V)                              4.746       4.746       4.746       0.000       4.746

Etch Beam Current (mA)                             3.900       3.900       3.900       0.000       3.900

Etch Suppressor Voltage (V)                        1.409       1.593       1.438       0.069       1.409

Etch Suppressor Current (mA)                       0.000       0.000       0.000       0.000       0.000

Etch Forward RF Power (W)                          0.000       0.000       0.000       0.000       0.000

Etch Reflected RF Power (W)                        0.000       0.000       0.000       0.000       0.000

Etch PBN Filament (A)                              0.104       0.110       0.105       0.002       0.104

Etch PBN Body (A)                                  0.001       0.002       0.002       0.001       0.002

Etch Source Magnet (A)                             0.003       0.004       0.004       0.000       0.004

Depo Gas 1 Actual Flow (SCCM)                      0.679       0.679       0.679       0.000       0.679

Depo Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch Gas 1 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch Gas 3 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

Etch PBN Gas Actual Flow (SCCM)                    0.000       0.000       0.000       0.000       0.000

Events Which Occurred During The Process:

03/01/2017 00:22:10.279   U:Event:   Current Process Recipe Name = PM3_ARO2_Ni35A_fillin_2AD2.prc [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.279   U:Event:   Current Step Number = 1 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.279   U:Event:   Current Step = CouponcheckD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.281   U:Event:   Current Step Number = 2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.281   U:Event:   Current Step = ArWarmupD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.283   U:Event:   Current Step Number = 3 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.283   U:Event:   Current Step = ArStableD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.284   U:Event:   Current Step Number = 4 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.284   U:Event:   Current Step = ArO2WarmupD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.286   U:Event:   Current Step Number = 5 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.286   U:Event:   Current Step = ArO2_EtchD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.288   U:Event:   Current Step Number = 6 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.288   U:Event:   Current Step = ArO2PurgeD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.290   U:Event:   Current Step Number = 7 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.290   U:Event:   Current Step = EtchwarmD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.292   U:Event:   Current Step Number = 8 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.292   U:Event:   Current Step = EtchstableD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.294   U:Event:   Current Step Number = 9 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.294   U:Event:   Current Step = PTREtch_6535D2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.296   U:Event:   Current Step Number = 10 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.296   U:Event:   Current Step = SiNstartD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.298   U:Event:   Current Step Number = 11 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.298   U:Event:   Current Step = SiNfillinD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.300   U:Event:   Current Step Number = 12 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.300   U:Event:   Current Step = SiNviewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.301   U:Event:   Current Step Number = 13 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.302   U:Event:   Current Step = EtchbackNewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.303   U:Event:   Current Step Number = 14 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.303   U:Event:   Current Step = SiNviewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.305   U:Event:   Current Step Number = 15 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.305   U:Event:   Current Step = SiNstartD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.306   U:Event:   Current Step Number = 16 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.306   U:Event:   Current Step = SiNdepo_2AD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.308   U:Event:   Current Step Number = 17 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.308   U:Event:   Current Step = SiNviewD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.472   U:Event:   Current Step Number = 1 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.472   U:Event:   Current Step = CouponcheckD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.475   U:Event:   Waiting for Process Pressure [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.660   U:Event:   Waiting for Process Start Pressure [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.821   U:Event:   Process Starting [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:10.821   U:Event:   Waiting for Source PreStart [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:13.743   U:Event:   Clamping Wafer for Processing [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:22.500   U:Event:   Wafer is clamped for Processing [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:22.955   U:Event:   Configuring Rotation Axis to Step Configuration [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:23.001   U:Event:   Sequence MotionToInitialPosition - Moving Fixture to process position [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:42.232   U:Event:   Waiting for Step to Complete [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:57.041   U:Event:   Step Completed. [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:58.002   U:Event:   Current Step Number = 2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:58.003   U:Event:   Current Step = ArWarmupD2 [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:59.312   U:Event:   Configuring Rotation Axis to Step Configuration [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:22:59.398   U:Event:   Sequence MotionToInitialPosition - Moving Fixture to -135 degrees [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:09.269   U:Event:   Sequence MotionToInitialPosition - Moving Etch Shutter to Initial Position [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:15.622   U:Event:   SourceManager RF Generator Status Update: External Interlock - OK [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:15.758   U:Event:   Etch : Ramping Started [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:17.767   U:Event:   Etch: Gas is stable... [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:25.779   U:Event:   Etch: Turning On RF [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:39.709   U:Event:   Etch: Igniting Beam... [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:40.797   U:Event:   Etch: Waiting for the beam to stabilize/regulate... [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:44.370   U:Event:   Etch: Beam stabilized/regulated. [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:46.120   U:Event:   Source 'SourceManager_Etch' has indicated an error. [LLA_02] [2017-03-01_001_A2B]

Alarms Which Occurred During The Process:

03/01/2017 00:23:46.013   U:Alarm:   Etch: Maximum Suppressor Current Limit Detected (SI=0.298)! [LLA_02] [2017-03-01_001_A2B]

03/01/2017 00:23:46.120   U:Alarm:   Sequence IgniteBeam - Failed to Ignite all Sources [LLA_02] [2017-03-01_001_A2B]

Data Log Event: Process Aborted

Process has been abnormally terminated. - 03/01/2017 00:23:46.251

    Processing should be continued from:

        Process Name:   PM3_ARO2_Ni35A_fillin_2AD2.prc

        Step Name:      ArWarmupD2

        Step Number:    2

        Elapsed Time:   0.000

        Remaining Time: 60.000

        Total Steps:    17

Here is the sample portion i want to extract per step:

 Item Name                                       Minimum     Maximum        Mean      StdDev      Median

    Chamber Pressure                                1.6e-006    1.7e-006    1.6e-006    2.5e-008    1.6e-006

    DC Current Current  (mA)                           0.010       0.010       0.010       0.000       0.010

    DC Current Impedance                               0.000       0.000       0.000       0.000       0.000

    DC Current Power (W)                               0.000       0.000       0.000       0.000       0.000

    DC Current Voltage (V)                             0.000       0.000       0.000       0.000       0.000

    Etch Beam Voltage (V)                              4.746       4.746       4.746       0.000       4.746

    Etch Beam Current (mA)                             3.900       3.900       3.900       0.000       3.900

    Etch Suppressor Voltage (V)                        1.409       1.593       1.438       0.069       1.409

    Etch Suppressor Current (mA)                       0.000       0.000       0.000       0.000       0.000

    Etch Forward RF Power (W)                          0.000       0.000       0.000       0.000       0.000

    Etch Reflected RF Power (W)                        0.000       0.000       0.000       0.000       0.000

    Etch PBN Filament (A)                              0.104       0.110       0.105       0.002       0.104

    Etch PBN Body (A)                                  0.001       0.002       0.002       0.001       0.002

    Etch Source Magnet (A)                             0.003       0.004       0.004       0.000       0.004

    Depo Gas 1 Actual Flow (SCCM)                      0.679       0.679       0.679       0.000       0.679

    Depo Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch Gas 1 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch Gas 2 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch Gas 3 Actual Flow (SCCM)                      0.000       0.000       0.000       0.000       0.000

    Etch PBN Gas Actual Flow (SCCM)                    0.000       0.000       0.000       0.000       0.000

Body:
Regex by your request is:

(?P<Item>(Item|Chamber|DC|Etch|Depo)(\s{1,3}\w*){1,5}(\((mA|A|W|V|SCCM)\))?)\s{4,}(?P<minimum>[0-9]\.[0-9e-]+)\s+(?P<maximum>[0-9]\.[0-9e-]+)\s+(?P<mean>[0-9]\.[0-9e-]+)\s+(?P<stddev>[0-9]\.[0-9e-]+)\s+(?P<median>[0-9]\.[0-9e-]+)

This way you will have 6 regex named groups: item, minimum, maximum mean, stddev and median which you can extract in python code by groupdict() method.

Also don't forget to enable MULTILINE flag if you're using web sites for check your regex (in python it's re.MULTILINE).

This is how groupdict() method works:

import re
h_regex = re.match(r'(?P<hello>H)', 'Hello', re.MULTILINE)
print(h_regex.groupdict())

Good luck and thanks for such complex and interesting question! :)

You can check it with details in http://pythex.org/, it's more convenient than http://myregexp.com/ in my opinion.

UPD: python 3 script (just get correct input filename):

import re

input_filename = 'log.txt'
pattern = re.compile(r'(?P<item>(Item|Chamber|DC|Etch|Depo)(\s{1,3}\w*){1,5}(\((mA|A|W|V|SCCM)\))?)\s{4,}(?P<minimum>[0-9]\.[0-9e-]+)\s+(?P<maximum>[0-9]\.[0-9e-]+)\s+(?P<mean>[0-9]\.[0-9e-]+)\s+(?P<stddev>[0-9]\.[0-9e-]+)\s+(?P<median>[0-9]\.[0-9e-]+)')
matched = []

with open(input_filename, 'r') as f:
    log_content = f.readlines()

for line in log_content:
    result = re.match(pattern, line)
    if result:
        matched.append(result)

for line in matched:
    print(line.groupdict())


来源: stackexchange

问:
Load CycleJS with SystemJS
I tried to load Cycle DOM from their CDN through SystemJS with something like:

```<code>System.config({
  map: {
    'cycle-dom': 'https://unpkg.com/@cycle/dom@17.1.0/dist/cycle-dom.js',
    'xstream': 'https://cdnjs.cloudflare.com/ajax/libs/xstream/10.3.0/xstream.min.js',
  }
});

System.import('cycle-dom', cycleDOM => {
    ...
});
</code>```

But I quickly found out cycle-dom needs xstream. So I try to load both:

```<code>Promise.all([
  System.import('xstream'),
  System.import('cycle-dom')
])
.then(([xs, cycleDOM]) => {
  ...
});
</code>```

But I still get the same error. It looks like cycle-dom is expecting xstream to exist on window when it's first loaded. So I tried:

```<code>System.import('xstream')
  .then(xs => window['xstream'] = xs)
  .then(() => System.import('cycle-dom'))
  .then(cycleDOM => {
    ...
  });
</code>```

I feel like I'm going about this all wrong. How can I do this?

Update:

Following martin's advice below, I tried configuring xstream as a dependency of cycle-dom.

Here's a jsbin that demonstrates. What I'm doing is loading cycle-run and cycle-dom and then running the example off the cycle home page.

But I get the error:

"TypeError: Cannot read property 'default' of undefined"

Undefined in this case is cycle-dom trying to load window['xstream'], which isn't being loaded.

Thanks.

答:
The System.import() call returns a Promise so you need to put the callback into its then() method (the second parameter is the parent name; not a callback).

```<code>System.import('cycle-dom').then(function(cycleDOM) {
  console.log(cycleDOM);
});
</code>```

This prints the module exports.

I don't have any experience with cycle.js so I can't tell whether this is enough or not. Nonetheless you can set this package dependencies with meta config:

```<code>System.config({
  map: {
    'cycle-dom': 'https://unpkg.com/@cycle/dom@17.1.0/dist/cycle-dom.js',
    'xstream': 'https://cdnjs.cloudflare.com/ajax/libs/xstream/10.3.0/xstream.min.js',
  },
  meta: {
    'cycle-dom': {
      deps: [
        'xstream'
      ]
    }
  }
});
</code>```

Again, I don't know whether this is enough or not. The SystemJS documentation contains pretty well explained example how to load dependencies that need to register some global variables. See https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md#shim-dependencies

Edit:

In this case it's a little more complicated. The cycle-run.js script is generated probably by browserify and you can see it contains a line as follows:

```<code>var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null);
</code>```

This checks whether window['xstream'] exists when it's loaded. This means that the xstream has to be loaded before loading the cycle-run.js script. The way SystemJS works is that it loads the requested module and then loads its dependencies (you can see the order in Developer Tools). So it's the opposite order than you need (this is very similar to my question on SystemJS GitHub page).

This means you need to restructure the import calls:

```<code>System.config({
  // ...
  meta: {
    'xstream': {
      format: 'global',
      exports: 'xstream',
    }
  }
});

System.import('xstream').then(function() {
  Promise.all([
    System.import('cycle-run'),
    System.import('cycle-dom'),
  ])
  .then(([cycle, cycleDOM]) => {
    // ...
  });
});
</code>```

This registers the xstream before loading cycle-run. Also with the meta configuration for xstream this ensures that the window.xstream exists only inside these callbacks and doesn't leak to the global scope.

See your updated demo: https://jsbin.com/qadezus/35/edit?js,output

Also to use format and exports you need to use the newer SystemJS 0.20.* and not 0.19.*.

ContentLicense: CC BY-SA 3.0

Title: Load CycleJS with SystemJS

Body:
I tried to load Cycle DOM from their CDN through SystemJS with something like:

System.config({
  map: {
    'cycle-dom': 'https://unpkg.com/@cycle/dom@17.1.0/dist/cycle-dom.js',
    'xstream': 'https://cdnjs.cloudflare.com/ajax/libs/xstream/10.3.0/xstream.min.js',
  }
});

System.import('cycle-dom', cycleDOM => {
    ...
});

But I quickly found out cycle-dom needs xstream. So I try to load both:

Promise.all([
  System.import('xstream'),
  System.import('cycle-dom')
])
.then(([xs, cycleDOM]) => {
  ...
});

But I still get the same error. It looks like cycle-dom is expecting xstream to exist on window when it's first loaded. So I tried:

System.import('xstream')
  .then(xs => window['xstream'] = xs)
  .then(() => System.import('cycle-dom'))
  .then(cycleDOM => {
    ...
  });

I feel like I'm going about this all wrong. How can I do this?

Update:

Following martin's advice below, I tried configuring xstream as a dependency of cycle-dom.

Here's a jsbin that demonstrates. What I'm doing is loading cycle-run and cycle-dom and then running the example off the cycle home page.

But I get the error:

"TypeError: Cannot read property 'default' of undefined"

Undefined in this case is cycle-dom trying to load window['xstream'], which isn't being loaded.

Thanks.

Body:
The System.import() call returns a Promise so you need to put the callback into its then() method (the second parameter is the parent name; not a callback).

System.import('cycle-dom').then(function(cycleDOM) {
  console.log(cycleDOM);
});

This prints the module exports.

I don't have any experience with cycle.js so I can't tell whether this is enough or not. Nonetheless you can set this package dependencies with meta config:

System.config({
  map: {
    'cycle-dom': 'https://unpkg.com/@cycle/dom@17.1.0/dist/cycle-dom.js',
    'xstream': 'https://cdnjs.cloudflare.com/ajax/libs/xstream/10.3.0/xstream.min.js',
  },
  meta: {
    'cycle-dom': {
      deps: [
        'xstream'
      ]
    }
  }
});

Again, I don't know whether this is enough or not. The SystemJS documentation contains pretty well explained example how to load dependencies that need to register some global variables. See https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md#shim-dependencies

Edit:

In this case it's a little more complicated. The cycle-run.js script is generated probably by browserify and you can see it contains a line as follows:

var xstream_1 = (typeof window !== "undefined" ? window['xstream'] : typeof global !== "undefined" ? global['xstream'] : null);

This checks whether window['xstream'] exists when it's loaded. This means that the xstream has to be loaded before loading the cycle-run.js script. The way SystemJS works is that it loads the requested module and then loads its dependencies (you can see the order in Developer Tools). So it's the opposite order than you need (this is very similar to my question on SystemJS GitHub page).

This means you need to restructure the import calls:

System.config({
  // ...
  meta: {
    'xstream': {
      format: 'global',
      exports: 'xstream',
    }
  }
});

System.import('xstream').then(function() {
  Promise.all([
    System.import('cycle-run'),
    System.import('cycle-dom'),
  ])
  .then(([cycle, cycleDOM]) => {
    // ...
  });
});

This registers the xstream before loading cycle-run. Also with the meta configuration for xstream this ensures that the window.xstream exists only inside these callbacks and doesn't leak to the global scope.

See your updated demo: https://jsbin.com/qadezus/35/edit?js,output

Also to use format and exports you need to use the newer SystemJS 0.20.* and not 0.19.*.


问:
Datatables not working with 5 columns or less
I have been working with Datatables plugin on my Laravel 5.2 project.

I'm feeding the table with jQuery and Ajax post.

This is my HTML table:

```<code><table id="entidadeTable" class="table">
     <thead>
        <tr>
           <th>ID</th>
           <th>Nome</th>
           <th>Descrição</th>
           <th>Ações</th>
        </tr>
     </thead>
</table>
</code>```

And after that I instantiate the table by Datatable:

```<code>var entidadeTable = $('#entidadeTable').DataTable({
    "language": {
        "url":"//cdn.datatables.net/plugins/9dcbecd42ad/i18n/Portuguese.json"
    },
    "order": [[0, "desc"]],
    "ajax": {
         "method": "POST",
         "url": "{{ route('getTabelaEntidades') }}",
         "data": {_token: "{{ Session::token() }}"}
    },
    "columns": [
         {"data": "id"},
         {"data": "nome"},
         {"data": "descricao"},
         {"data": "actions"}
    ],
});
</code>```

This is my controller code, that is responsible to get the data to the datatable:

```<code>$entidades = Entidade::all();

return response()->json(['draw' => 1, 'recordsTotal' => $entidades->count(),
            'recordsFiltered' => $entidades->count(), 'data' => $entidades]);
</code>```

But I'm getting this datatable error:

https://www.datatables.net/manual/tech-notes/4

I only get this error if my table has less than 6 columns.
I tried to put more than 5 columns on my table and after that it worked and the error disappeared

Error:

```<code>DataTables warning: table id=entidadeTable - Requested unknown parameter '4' for row 0, column 4. For more information about this error, please see http://datatables.net/tn/4
</code>```

答:
I added this datatables property and the error disappeared

columnDefs: [{ }],

Body:
I have been working with Datatables plugin on my Laravel 5.2 project.

I'm feeding the table with jQuery and Ajax post.

This is my HTML table:

           ID
           Nome
           Descrição
           Ações

And after that I instantiate the table by Datatable:

var entidadeTable = $('#entidadeTable').DataTable({
    "language": {
        "url":"//cdn.datatables.net/plugins/9dcbecd42ad/i18n/Portuguese.json"
    },
    "order": [[0, "desc"]],
    "ajax": {
         "method": "POST",
         "url": "{{ route('getTabelaEntidades') }}",
         "data": {_token: "{{ Session::token() }}"}
    },
    "columns": [
         {"data": "id"},
         {"data": "nome"},
         {"data": "descricao"},
         {"data": "actions"}
    ],
});

This is my controller code, that is responsible to get the data to the datatable:

$entidades = Entidade::all();

return response()->json(['draw' => 1, 'recordsTotal' => $entidades->count(),
            'recordsFiltered' => $entidades->count(), 'data' => $entidades]);

But I'm getting this datatable error:

https://www.datatables.net/manual/tech-notes/4

I only get this error if my table has less than 6 columns.
I tried to put more than 5 columns on my table and after that it worked and the error disappeared

Error:

DataTables warning: table id=entidadeTable - Requested unknown parameter '4' for row 0, column 4. For more information about this error, please see http://datatables.net/tn/4


问:
MVC 3 Add-in View attempting to resolve _ViewStart.cshtml from Add-in
I've been scouring the Internet and learning how to enable an ASP.Net MVC 3 site to use MEF.  The idea being to build a modular site, so we can expand features as needed.  I have just about every piece of code working, but for some reason, when I'm trying to load my Index view from the Add-in, it's trying to load the _ViewStart.cshtml file from the Add-in, and not the main MVC site.

Has anyone run into this, and if so, what was the work around?

答:
You do realize how the _ViewStart hierarchy is resolved don't you? Basically, the ViewStart closest in hierarchy to the view is given precedence for display. In your case, the viewstart in your addin is most likely to be displayed.

If you don't want that displayed, delete or remove it, and the next ViewStart up in the hierarchy will be given display precedence and it will display, be used, just like you want.

Let me know if this has been of use to you, because the way you described it, it is doing/working just like it is supposed to according to my understanding.

ContentLicense: CC BY-SA 2.5


问:
Node js: Express js asynchronous db query execution-return results got undefiend
Just started to learn express js framework ,here is my simple database query execution part its invoked with this url localhost:3000/api/test.

```<code>db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is:', results[0].id);

            return results;
        });
</code>```

Does it really asynchronous?? suppose another user request this url does he need to wait for the previous query execution??.

I've heard about async package ,but don't know how this is applicable in my case

UPDATE

I got proper result in console.log(); but when i return the result i got undefined error

Here is my model.js

```<code>module.exports = {
    getUser:function () {
        db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is: ', results[0].id);

        });

    }

}
</code>```

From my controller.js

```<code>var model = require('../models/user.js');
module.exports = {
    getData : function(req, res){
        //invoke model
        console.log(model.getUser());

    }
}
</code>```

答:
Node is non-blocking and will serve this request as and when it's called.

If another user hits this endpoint then it will execute again regardless if the first query has completed or not (unless the SQL has locked the table, in which case all consecutive connections/queries will wait and may timeout because of it). This happens on a connection basis.

You should make sure to check your SQL server (MySQL?) configs here to make sure there are enough max_connections to be able to cope with whatever load you are expecting.

Remember that the biggest bottleneck to an application is usually the database.

Your query above will need a callback to return the data asynchronously.

```<code>db.query('SELECT * FROM user', function (error, results, fields) {
    if (error) throw error;
    console.log('The result is:', results[0].id);

    //cb=callback function passed in to context
    if (cb) cb(results);
});
</code>```

Updated answer from updated question

In your model.js:

```<code>module.exports = {
    getUser:function (cb) {
        db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is: ', results[0].id);
            if (cb) cb(results);

        });

    }

}
</code>```

In your controller.js:

```<code>module.exports = {
    getData : function(req, res){
        //invoke model

        model.getUser(function(results) {
            console.log(results);
        });

    }
}
</code>```

Body:
Just started to learn express js framework ,here is my simple database query execution part its invoked with this url localhost:3000/api/test.

db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is:', results[0].id);

            return results;
        });

Does it really asynchronous?? suppose another user request this url does he need to wait for the previous query execution??.

I've heard about async package ,but don't know how this is applicable in my case

UPDATE

I got proper result in console.log(); but when i return the result i got undefined error

Here is my model.js

module.exports = {
    getUser:function () {
        db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is: ', results[0].id);

        });

    }

}

From my controller.js

var model = require('../models/user.js');
module.exports = {
    getData : function(req, res){
        //invoke model
        console.log(model.getUser());

    }
}

Body:
Node is non-blocking and will serve this request as and when it's called.

If another user hits this endpoint then it will execute again regardless if the first query has completed or not (unless the SQL has locked the table, in which case all consecutive connections/queries will wait and may timeout because of it). This happens on a connection basis.

You should make sure to check your SQL server (MySQL?) configs here to make sure there are enough max_connections to be able to cope with whatever load you are expecting.

Remember that the biggest bottleneck to an application is usually the database.

Your query above will need a callback to return the data asynchronously.

db.query('SELECT * FROM user', function (error, results, fields) {
    if (error) throw error;
    console.log('The result is:', results[0].id);

    //cb=callback function passed in to context
    if (cb) cb(results);
});

Updated answer from updated question

In your model.js:

module.exports = {
    getUser:function (cb) {
        db.query('SELECT * FROM user', function (error, results, fields) {
            if (error) throw error;
            console.log('The result is: ', results[0].id);
            if (cb) cb(results);

        });

    }

}

In your controller.js:

module.exports = {
    getData : function(req, res){
        //invoke model

        model.getUser(function(results) {
            console.log(results);
        });

    }
}


问:
What is a tail trap in html
I found some weird markup in the end of a web page, could someone please tell me what is this for?

```<code>    </body>
</html>
<!--tailTrap<body></body><head></head><html></html>-->
</code>```

It's a Chinese website: http://mp.weixin.qq.com/s?__biz=MjM5ODMwMzExNQ==&mid=2651714590&idx=1&sn=bfdfeda82219e580807ea2c701b3d695&scene=0#wechat_redirect

答:
It's a Wechat page, which is the most popular app in China.
The tags is for prevent html hijacking.</p>

Title: What is a tail trap in html

Body:
I found some weird markup in the end of a web page, could someone please tell me what is this for?

It's a Chinese website: http://mp.weixin.qq.com/s?__biz=MjM5ODMwMzExNQ==&mid=2651714590&idx=1&sn=bfdfeda82219e580807ea2c701b3d695&scene=0#wechat_redirect


问:
Adding custom SQLite3 function using wxSQLite3
I am using wxSQLite3 (part of wxWidgets) to access a SQLite database. Everything works fine, but now I need to add a cutsom function to SQLite. Since everything in the code is done through wxSQLite3, I'd like to use wxSQLite3 interface to add the function and not the normal C SQLite API.
Following the documentation, I've declared a class that inherits wxSQLite3ScalarFunction:

```<code>class checkDateFun : public wxSQLite3ScalarFunction {
public:
    void Execute(wxSQLite3FunctionContext& ctx);
};
</code>```

and override the pure virtual wxSQLite3ScalarFunction::Execute() method as follows

```<code>void checkDateFun::Execute(wxSQLite3FunctionContext& ctx)
{
    wxString date1 = ctx.GetString(0);
    wxString date2 = ctx.GetString(1);

    //some checks on dates

    ctx.SetResult(1);
    return;
}
</code>```

Then, during database creation, I register the function doing

```<code>checkDateFun fun;
bool regOk = m_db->CreateFunction("CheckDate", 2, fun);
</code>```

but when I later try to make a query that uses the function, I get this error:
"Exception thrown: read access violation. func-> was 0xFFFFFFFFFFFF7".

What am I doing wrong?
Thanks for your help and time.

答:
I figured it out!
I had to declare checkDateFun fun as a member of the class that creates the database, and then pass the member to  CreateFunction.
Indeed, I was instantiating my checkDateFun inside the function that creates the database, but the checkDateFun destructor will be called on exiting that function and further SQL queries will point to nowhere.
Hope this can help somebody, though I was making quite a stupid mistake ;-)

Body:
I am using wxSQLite3 (part of wxWidgets) to access a SQLite database. Everything works fine, but now I need to add a cutsom function to SQLite. Since everything in the code is done through wxSQLite3, I'd like to use wxSQLite3 interface to add the function and not the normal C SQLite API.
Following the documentation, I've declared a class that inherits wxSQLite3ScalarFunction:

class checkDateFun : public wxSQLite3ScalarFunction {
public:
    void Execute(wxSQLite3FunctionContext& ctx);
};

and override the pure virtual wxSQLite3ScalarFunction::Execute() method as follows

void checkDateFun::Execute(wxSQLite3FunctionContext& ctx)
{
    wxString date1 = ctx.GetString(0);
    wxString date2 = ctx.GetString(1);

    //some checks on dates

    ctx.SetResult(1);
    return;
}

Then, during database creation, I register the function doing

checkDateFun fun;
bool regOk = m_db->CreateFunction("CheckDate", 2, fun);

but when I later try to make a query that uses the function, I get this error:
"Exception thrown: read access violation. func-> was 0xFFFFFFFFFFFF7".

What am I doing wrong?
Thanks for your help and time.


问:
EF 4.3 migrations throwing "Unable to open configSource file"
I'm trying to use EF 4.3 migrations feature. My ASP.NET MVC project stores connection strings in external file:

```<code><connectionStrings configSource="bin\connections.config" />
</code>```

All runtime procedures (including automatic migrations) work fine. However, no powershell commandlet, connecting to the database, is able to find external file. It throws "Unable to open configSource file" exception. I was trying to place .config file in different places as well as changing configured external file location to no avail. Is there any workaround available?

Update: I've found that EF creates a temporary AppDomain with configuration file located in temp directory. So the only workaround at the moment, it seems, is to place external configuration in the same temp directory. Any other suggestions?

答:
Using EF 6.1 here.

If like me you were linking to a connectionStrings.config file located in another project than your Entity Framework migrations project (using Add as link), you'll probably need to move the file back to this EF project and link to the moved file from the other projects instead...

Body:
I'm trying to use EF 4.3 migrations feature. My ASP.NET MVC project stores connection strings in external file:

<connectionStrings configSource="bin\connections.config" />

All runtime procedures (including automatic migrations) work fine. However, no powershell commandlet, connecting to the database, is able to find external file. It throws "Unable to open configSource file" exception. I was trying to place .config file in different places as well as changing configured external file location to no avail. Is there any workaround available?

Update: I've found that EF creates a temporary AppDomain with configuration file located in temp directory. So the only workaround at the moment, it seems, is to place external configuration in the same temp directory. Any other suggestions?


问:
on scroll moving the two divs in v shape
As I am new to CSS and jQuery I am trying to learn the different animations. Right now I want to do the animation similar to domain.me.

I am using jQuery's scrolltop() to get the position and based on the scroll position displayed in the console using console.log I manually added the if statement and addClass(). Below is my complete code (style and script in same file)

js fiddle

$(window).scroll(example);

function example() {
  var tempScrollTop = $(window).scrollTop();
  console.log("Scroll from Top: " + tempScrollTop.toString());

  if (tempScrollTop > 20 && tempScrollTop < 50) {
    $("#div1").addClass("slide");
    $("#div2").addClass("slider");
  }

  if (tempScrollTop > 50 && tempScrollTop < 100) {
    $("#div1").addClass("slide1");
    $("#div2").addClass("slider1");
  }

  if (tempScrollTop > 100 && tempScrollTop < 200) {
    $("#div1").addClass("slide2");
    $("#div2").addClass("slider2");
  }

  if (tempScrollTop > 200 && tempScrollTop < 300) {
    $("#div1").addClass("slide2");
  }
};```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#mainbord {
  border: 5px solid black;
  height: 100%;
  width: 100%;
  background-image: url("2.jpg");
}

.divv {
  border: 1px solid black;
  width: 200px;
  height: 200px;
  margin-top: 300px;
  margin-left: 500px;
  border-radius: 50%;
}

.div2 {
  border: 1px solid black;
  width: 400px;
  height: 50px;
  margin-left: 400px;
}

.div3 {
  border: 1px solid black;
  width: 500px;
  height: 500px;
  margin-top: 200px;
}

.div4 {
  border: 1px solid black;
  width: 500px;
  height: 500px;
  margin-top: 200px;
}

.slide {
  background-color: green;
  border: 1px solid black;
  width: 180px;
  height: 180px;
  margin-top: 250px;
  margin-left: 420px;
  -moz-transform: scale(0.2);
  transition: all 600ms ease-in;
  */
}

.slide1 {
  background-color: red;
  border: 1px solid black;
  width: px;
  height: 160px;
  margin-top: 160px;
  margin-left: 400px;
  transition: all 600ms ease-in;
}

.slide2 {
  background-color: blue;
  border: 1px solid black;
  width: 100px;
  height: 100px;
  margin-top: 200px;
  margin-left: 350px;
  -moz-transform: scale(0.2);
  transition: all 600ms ease-in;
}

.slider {
  margin-left: 550px;
  margin-top: background-color:green;
  transition: all 600ms ease-in;
  width: 300px;
}

.slider1 {
  margin-left: 700px;
  background-color: red;
  transition: all 600ms ease-in;
  width: 250px;
}

.slider2 {
  margin-left: 730px;
  background-color: blue;
  transition: all 600ms ease-in;
  width: 250px;
}</code>```

```

答:
Assuming you are familiar with the chrome dev console,

Select the .me icon <div id ="slikadiv".. (check the screen shot) and now slowly scroll in the web section, see how CSS properties width, top, left changes for the same.

Write your own function in the .scroll jquery function to move the icon.

Also check the other CSS properties too.

Body:
As I am new to CSS and jQuery I am trying to learn the different animations. Right now I want to do the animation similar to domain.me.

I am using jQuery's scrolltop() to get the position and based on the scroll position displayed in the console using console.log I manually added the if statement and addClass(). Below is my complete code (style and script in same file)

js fiddle

$(window).scroll(example);

function example() {
  var tempScrollTop = $(window).scrollTop();
  console.log("Scroll from Top: " + tempScrollTop.toString());

  if (tempScrollTop > 20 && tempScrollTop < 50) {
    $("#div1").addClass("slide");
    $("#div2").addClass("slider");
  }

  if (tempScrollTop > 50 && tempScrollTop < 100) {
    $("#div1").addClass("slide1");
    $("#div2").addClass("slider1");
  }

  if (tempScrollTop > 100 && tempScrollTop < 200) {
    $("#div1").addClass("slide2");
    $("#div2").addClass("slider2");
  }

  if (tempScrollTop > 200 && tempScrollTop < 300) {
    $("#div1").addClass("slide2");
  }
};

#mainbord {
  border: 5px solid black;
  height: 100%;
  width: 100%;
  background-image: url("2.jpg");
}

.divv {
  border: 1px solid black;
  width: 200px;
  height: 200px;
  margin-top: 300px;
  margin-left: 500px;
  border-radius: 50%;
}

.div2 {
  border: 1px solid black;
  width: 400px;
  height: 50px;
  margin-left: 400px;
}

.div3 {
  border: 1px solid black;
  width: 500px;
  height: 500px;
  margin-top: 200px;
}

.div4 {
  border: 1px solid black;
  width: 500px;
  height: 500px;
  margin-top: 200px;
}

.slide {
  background-color: green;
  border: 1px solid black;
  width: 180px;
  height: 180px;
  margin-top: 250px;
  margin-left: 420px;
  -moz-transform: scale(0.2);
  transition: all 600ms ease-in;
  */
}

.slide1 {
  background-color: red;
  border: 1px solid black;
  width: px;
  height: 160px;
  margin-top: 160px;
  margin-left: 400px;
  transition: all 600ms ease-in;
}

.slide2 {
  background-color: blue;
  border: 1px solid black;
  width: 100px;
  height: 100px;
  margin-top: 200px;
  margin-left: 350px;
  -moz-transform: scale(0.2);
  transition: all 600ms ease-in;
}

.slider {
  margin-left: 550px;
  margin-top: background-color:green;
  transition: all 600ms ease-in;
  width: 300px;
}

.slider1 {
  margin-left: 700px;
  background-color: red;
  transition: all 600ms ease-in;
  width: 250px;
}

.slider2 {
  margin-left: 730px;
  background-color: blue;
  transition: all 600ms ease-in;
  width: 250px;
}


问:
Excel VBA: There must be a better way to use a loop to delete rows based on cell contents
A report produces a sheet that looks like this:

Format is inherited from source data, data is in cols A, D and G, with A merging ABC, D merging DEF and G on its own.

I want to keep only the lines highlighted in blue. I want the macro to check the contents of G:G and if Cell.Text = "" then entirerow.delete, else leave it alone.

Only problem is when it deletes row 2, then row 3 becomes row 2, meaning that it doesn't delete it, because it's already checked row 2. What was row 4 now becomes row 3, which is the next one to check, and it sees that text is there and doesn't delete, moves on to row four, deletes it, row 5 becomes row 4, remains unchecked, it moves on to row 6 (now row 5), sees that's blank, deletes it, but row 7 now becomes row 6 and isn't deleted... and so on.

The only way I've found around it is to use GOTO to restart the loop, then to use another GOTO to get out of the loop early. I appreciate that probably isn't the most elegant solution.

```<code>iRange = Application.Workbooks(2).Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row + 1
Debug.Print (iRange)

RestartLoop:

For Each rCell In Application.Workbooks(2).Worksheets(2).Range("G2:G" & iRange)

    If Not rCell.Offset(0, -3).Value = "" Then

        If rCell.Text = "" Then
            Debug.Print (rCell.Address)
            rCell.EntireRow.Delete
            GoTo RestartLoop
        End If

    Else0

        GoTo LeaveLoop

    End If
Next rCell

LeaveLoop:
'Do the next thing
</code>```

(code is Option Explicit: Dim iRange As Integer Dim rCell as Range in declarations at top of code)

Here's the debug.print:

```<code>26
$G$2
$G$2
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$4
$G$4
$G$4
$G$4
$G$4
$G$6
$G$6
$G$7
</code>```

If anyone knows of a solution, and can also explain it for a layman, I'd appreciate it. The solution needs to be dynamic, because the original sheet produced is a different length each time, with a different number of blank and blue cells each time.

I have searched around a little but either I'm not understanding the answers fully, or they seem to give me the same problem.

答:
You should use Autofilter on G column for selecting blank rows and then delete those rows, so can have all those rows where there is text in G. This will delete all rows where column G has a blank cell.New row needs to be added i.e. dummy row so as it serves as a reference point to further select and delete rows

```<code>Dim lastrow As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
' Add dummy row
Rows("1:1").Copy
Rows("2:2").Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Paste
CutCopyMode = False

'add filter
With ActiveSheet

.AutoFilterMode = False
.Range("A2:G2").AutoFilter field:=7, Criteria1:="=", Operator:=xlOr, Criteria2:="=" & ""
End With

'delete blank rows
Range("A2:G2").Select
Range(Selection, Selection.End(xlDown)).EntireRow.Delete
</code>```

Hope this helps :)

Body:
A report produces a sheet that looks like this:

Format is inherited from source data, data is in cols A, D and G, with A merging ABC, D merging DEF and G on its own.

I want to keep only the lines highlighted in blue. I want the macro to check the contents of G:G and if Cell.Text = "" then entirerow.delete, else leave it alone.

Only problem is when it deletes row 2, then row 3 becomes row 2, meaning that it doesn't delete it, because it's already checked row 2. What was row 4 now becomes row 3, which is the next one to check, and it sees that text is there and doesn't delete, moves on to row four, deletes it, row 5 becomes row 4, remains unchecked, it moves on to row 6 (now row 5), sees that's blank, deletes it, but row 7 now becomes row 6 and isn't deleted... and so on.

The only way I've found around it is to use GOTO to restart the loop, then to use another GOTO to get out of the loop early. I appreciate that probably isn't the most elegant solution.

iRange = Application.Workbooks(2).Worksheets(2).Cells(Rows.Count, "A").End(xlUp).Row + 1
Debug.Print (iRange)

RestartLoop:

For Each rCell In Application.Workbooks(2).Worksheets(2).Range("G2:G" & iRange)

    If Not rCell.Offset(0, -3).Value = "" Then

        If rCell.Text = "" Then
            Debug.Print (rCell.Address)
            rCell.EntireRow.Delete
            GoTo RestartLoop
        End If

    Else0

        GoTo LeaveLoop

    End If
Next rCell

LeaveLoop:
'Do the next thing

(code is Option Explicit: Dim iRange As Integer Dim rCell as Range in declarations at top of code)

Here's the debug.print:

26
$G$2
$G$2
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$3
$G$4
$G$4
$G$4
$G$4
$G$4
$G$6
$G$6
$G$7

If anyone knows of a solution, and can also explain it for a layman, I'd appreciate it. The solution needs to be dynamic, because the original sheet produced is a different length each time, with a different number of blank and blue cells each time.

I have searched around a little but either I'm not understanding the answers fully, or they seem to give me the same problem.

Body:
You should use Autofilter on G column for selecting blank rows and then delete those rows, so can have all those rows where there is text in G. This will delete all rows where column G has a blank cell.New row needs to be added i.e. dummy row so as it serves as a reference point to further select and delete rows

Dim lastrow As Long
lastrow = Range("A" & Rows.Count).End(xlUp).Row
' Add dummy row
Rows("1:1").Copy
Rows("2:2").Insert shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("2:2").Paste
CutCopyMode = False

'add filter
With ActiveSheet

.AutoFilterMode = False
.Range("A2:G2").AutoFilter field:=7, Criteria1:="=", Operator:=xlOr, Criteria2:="=" & ""
End With

'delete blank rows
Range("A2:G2").Select
Range(Selection, Selection.End(xlDown)).EntireRow.Delete

Hope this helps :)


问:
convert a list -class numeric- into a distance structure in R
I have a list that looks like this, it is a measure of dispersion for each sample.

```<code>         1          2          3          4          5
0.11829384 0.24987017 0.08082147 0.13355495 0.12933790
</code>```

To further analyze this I need it to be a distance structure, the -vegan- package need it as a 'dist' object.

I found some solutions that applies to matrices > dist, but how could I change this current data into a dist object?

I am using the FD package, at the manual I found,

Still, one potential advantage of FDis over Rao’s Q is that in the unweighted case
  (i.e. with presence-absence data), it opens possibilities for formal statistical tests for differences in
  FD between two or more communities through a distance-based test for homogeneity of multivariate
  dispersions (Anderson 2006); see betadisper for more details

I wanted to use vegan betadisper function to test if there are differences among different regions (I provided this using element "region" with column "region" too)

```<code>functional <- FD(trait, comun)
mod <- betadisper(functional$FDis, region$region)
</code>```

using gowdis or fdisp from FD didn't work too.

```<code>distancias <-  gowdis(rasgo)
mod <- betadisper(distancias, region$region)
dispersion <- fdisp(distancias, presence)
mod <- betadisper(dispersion, region$region)
</code>```

I tried this but I need a list object. I thought I could pass those results to betadisper.

答: You cannot do this: FD::fdisp() does not return dissimilarities. It returns a list of three elements: the dispersions FDis for each sampling unit (SU), and the results of the eigen decomposition of input dissimilarities (eig for eigenvalues, vectors for orthonormal eigenvectors). The FDis values are summarized for each original SU, but there is no information on the differences among SUs. The eigen decomposition can be used to reconstruct the original input dissimilarities (your distancias from FD::gowdis()), but you can directly use the input dissimilarities. Function FD::gowdis() returns a regular "dist" structure that you can directly use in vegan::betadisper() if that gives you a meaningful analysis. For this, your grouping variable must be based on the same units as your distancias. In typical application of fdisp, the units are species (taxa), but it seems you want to get analysis for communities/sites/whatever. This will not be possible with these tools.

Body:
I have a list that looks like this, it is a measure of dispersion for each sample.

         1          2          3          4          5
0.11829384 0.24987017 0.08082147 0.13355495 0.12933790

To further analyze this I need it to be a distance structure, the -vegan- package need it as a 'dist' object.

I found some solutions that applies to matrices > dist, but how could I change this current data into a dist object?

I am using the FD package, at the manual I found,

Still, one potential advantage of FDis over Rao’s Q is that in the unweighted case
  (i.e. with presence-absence data), it opens possibilities for formal statistical tests for differences in
  FD between two or more communities through a distance-based test for homogeneity of multivariate
  dispersions (Anderson 2006); see betadisper for more details

I wanted to use vegan betadisper function to test if there are differences among different regions (I provided this using element "region" with column "region" too)

functional <- FD(trait, comun)
mod <- betadisper(functional$FDis, region$region)

using gowdis or fdisp from FD didn't work too.

distancias <-  gowdis(rasgo)
mod <- betadisper(distancias, region$region)
dispersion <- fdisp(distancias, presence)
mod <- betadisper(dispersion, region$region)

I tried this but I need a list object. I thought I could pass those results to betadisper.


问:
Why access specifiers can't be used for variables declared inside method in a Java Class?
Why we can't use access specifiers for variables declared inside method in a Java Class?</p>

答:
There is no sense of applying access modifier as the local variable access scope is restricted to the method scope. Hence there is no meaning of applying access modifier.

```<code>class Foo{
    public void stuff(){
     private String x=2;  //compilation error.
}
}
</code>```

The above code will not compile if we explicitly apply access modifier.

Body:
There is no sense of applying access modifier as the local variable access scope is restricted to the method scope. Hence there is no meaning of applying access modifier.

class Foo{
    public void stuff(){
     private String x=2;  //compilation error.
}
}

The above code will not compile if we explicitly apply access modifier.


问:
Will providing APIs help deter screen scraping?
I have been thinking quite a bit here lately about screen scraping and what a task it can be. So I pose the following question.

Would you as a site developer expose simple APIs to prevent users from screen scraping, such as JSON results?

These results could then implement caching, and they are much smaller for traffic than the huge amounts of markup that could potentially be downloaded.

I am not looking at prevention, but deterring scraping.

Scraping Bandwidth Sample

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

users: 200,000

% of users using utility: 5

filesize: 1kb

freq: 1 minute

Formula:

((users * (% / 100)) * ((freq * 60) * 24)) * filesize

10,000 * 1440 * 1

14400000kb or 13.73291015625gb

Assuming your JSON result is 200 bytes that's now (10,000 * 1440 * 0.2) or 2.74658203125gb a day.

That's a change of about 11gb of traffic a day.

My Stack Overflow profile is 96k for reference.

The reason for this question prompted asking for a JSON result from users profiles:

http://stackoverflow.uservoice.com/pages/general/suggestions/101342-add-json-for-user-information

I wanted to find out if other developers would expose this type of API, and if it is worth your time to provide these APIs to reduce bandwidth.

答: If you want to encourage people to integrate with your site or it is popular enough for this to be a problem (so that you are forced to allow people to integrate with it), then by all means provide an API.  If your API is adequate and easy to use, then people will prefer it to screen scraping.  If your API is inadequate or harder to use than a screen scraper then you may still have the problem.</p>

OwnerDisplayName: Tom Anderson

LastEditorDisplayName: Tom Anderson

OwnerDisplayName: tvanfosson


问:
Is it possible to ignore case using xpath and c#?
Just wondered if its possible to ignore case with c# and xpath when searching an xml document?</p>

答:
The bad news is that Xpath is case sensitive, however there are ways to get around this.  Have a look at the following MSDN blog:

http://blogs.msdn.com/b/shjin/archive/2005/07/22/442025.aspx


问:
Bootstrap-select not working with dynamically populated dropdown
My Form looks like:

```<code><form action="/submit/" method="post" >{% csrf_token %}
<div class="col-lg-4 col-lg-offset-4">
<div class="form-group has-feedback">
<label class="control-label" for="inputSuccess2">Enter twitter username</label>
<input type="text" class="form-control" id="inputSuccess2", name='user'/>
<span class="glyphicon glyphicon-search form-control-feedback"></span>
<div class="text-center">

<label class="control-label" for="inputSuccess2">Select Job Type</label><br>
<select  class="selectpicker" id="type" name="type"></select>
<br>
<div class="btn-group">
    <select  name="specialization" id="specialization"></select>
    <br/></div>
    <script language="javascript">
        populateCountries("type", "specialization");
    </script>
    <br/>
    <input class="btn btn-primary" type="submit" value="Submit">
    </div>
    </div>
    </div>
</form>
</code>```

and the js file for the drop down looks like this:

```<code>var country_arr = new Array("Social Service and Education","Business and Sales","Language and Arts","Engineering and Technology", "Information Technology" );

// States
var s_a = new Array();
s_a[0] = "Please Select One";
s_a[1]="Counselor|School or Career Counselor|Community Service Manager|Social Worker|Preschool Teacher|Librarian|Professor|Psychologist";
s_a[2]="Sales Agent|Real Estate Agent|Accountant|Budget Analyst|Cost Estimator|Sales Engineer";
s_a[3]="Graphic Designer|Musician|Editor|Photographer|Translator|Artist";
s_a[4]="Chemical Engineer|Civil Engineer|Electronics Engineer|Environmental Engineer|Mechanical Engineer";
s_a[5]="Computer Programmer|Database Administrator|Software Developer|Web Developer";

function populateStates(countryElementId, stateElementId) {

    var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;

    var stateElement = document.getElementById(stateElementId);

    stateElement.length = 0; // Fixed by Julian Woods
    stateElement.options[0] = new Option('Select Specialization', '');
    stateElement.selectedIndex = 0;

    var state_arr = s_a[selectedCountryIndex].split("|");

    for (var i = 0; i < state_arr.length; i++) {
        stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
    }
}

function populateCountries(countryElementId, stateElementId) {
    // given the id of the <select> tag as function argument, it inserts <option> tags
    var countryElement = document.getElementById(countryElementId);
    countryElement.length = 0;
    countryElement.options[0] = new Option('Select Job Type', '-1');
    countryElement.selectedIndex = 0;
    for (var i = 0; i < country_arr.length; i++) {
        countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
    }
    $countryElementy.selectpicker('refresh');
    // Assigned all countries. Now assign event listener for the states.

    if (stateElementId) {
        countryElement.onchange = function () {
            populateStates(countryElementId, stateElementId);
        };
    }
}
</code>```

Hoowever, the drop down doesnt work. If i remove the selectpicker class, I lose the styling.

Is there a way i can use the bootstrap styling along with this code?

答:
Why you need to use javascript for populate the select?

Just save the values necessary in a list in your view and print them in the select in the template.

example:

```<code><select id="id_select" name="select">
    <option value="">your select</option>
    {% for value in yourdata %}
            <option value="{{value}}">{{ value }}</option>
        {% endif %}
    {% endfor %}
</select>
</code>```

and use the bootstrap style :)

Body:
My Form looks like:

<form action="/submit/" method="post" >{% csrf_token %}

Enter twitter username
<input type="text" class="form-control" id="inputSuccess2", name='user'/>

Select Job Type

<select  class="selectpicker" id="type" name="type"></select>

    <select  name="specialization" id="specialization"></select>

    <input class="btn btn-primary" type="submit" value="Submit">

</form>

and the js file for the drop down looks like this:

var country_arr = new Array("Social Service and Education","Business and Sales","Language and Arts","Engineering and Technology", "Information Technology" );

// States
var s_a = new Array();
s_a[0] = "Please Select One";
s_a[1]="Counselor|School or Career Counselor|Community Service Manager|Social Worker|Preschool Teacher|Librarian|Professor|Psychologist";
s_a[2]="Sales Agent|Real Estate Agent|Accountant|Budget Analyst|Cost Estimator|Sales Engineer";
s_a[3]="Graphic Designer|Musician|Editor|Photographer|Translator|Artist";
s_a[4]="Chemical Engineer|Civil Engineer|Electronics Engineer|Environmental Engineer|Mechanical Engineer";
s_a[5]="Computer Programmer|Database Administrator|Software Developer|Web Developer";

function populateStates(countryElementId, stateElementId) {

    var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;

    var stateElement = document.getElementById(stateElementId);

    stateElement.length = 0; // Fixed by Julian Woods
    stateElement.options[0] = new Option('Select Specialization', '');
    stateElement.selectedIndex = 0;

    var state_arr = s_a[selectedCountryIndex].split("|");

    for (var i = 0; i < state_arr.length; i++) {
        stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
    }
}

function populateCountries(countryElementId, stateElementId) {
    // given the id of the <select> tag as function argument, it inserts <option> tags
    var countryElement = document.getElementById(countryElementId);
    countryElement.length = 0;
    countryElement.options[0] = new Option('Select Job Type', '-1');
    countryElement.selectedIndex = 0;
    for (var i = 0; i < country_arr.length; i++) {
        countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
    }
    $countryElementy.selectpicker('refresh');
    // Assigned all countries. Now assign event listener for the states.

    if (stateElementId) {
        countryElement.onchange = function () {
            populateStates(countryElementId, stateElementId);
        };
    }
}

Hoowever, the drop down doesnt work. If i remove the selectpicker class, I lose the styling.

Is there a way i can use the bootstrap styling along with this code?

Body:
Why you need to use javascript for populate the select?

Just save the values necessary in a list in your view and print them in the select in the template.

example:

<select id="id_select" name="select">
    <option value="">your select</option>
    {% for value in yourdata %}
            <option value="{{value}}">{{ value }}</option>
        {% endif %}
    {% endfor %}
</select>

and use the bootstrap style :)


问:
How to drop and recreate Indexes inside PLSQL Stored Procedure
In PLSQL stored procedure, I would like to drop indexes and truncate the table
before inserting data into the table. Then I want to recreate the indexes afterwards . What is the best way of achieving this?

I need something similar like this

```<code>Begin:

Truncate Table
Drop index1
Drop  index2

loop
--- other code
Insert data
commit;
end loop;

Create index1
Create index2

End;
</code>```

答:
You can use dynamic SQL , specifically, execute immediate, based on your requirements:</p>

```<code>Begin:

execute immediate 'truncate table statement';
execute immediate 'DROP index statement';

loop
--- other code
Insert data
commit;
end loop;

execute immediate 'Create index1 statement';
execute immediate 'Create index2 statement';

End;
</code>```

Body:
In PLSQL stored procedure, I would like to drop indexes and truncate the table
before inserting data into the table. Then I want to recreate the indexes afterwards . What is the best way of achieving this?

I need something similar like this

Begin:

Truncate Table
Drop index1
Drop  index2

loop
--- other code
Insert data
commit;
end loop;

Create index1
Create index2

End;

Body:
You can use dynamic SQL , specifically, execute immediate, based on your requirements:

Begin:

execute immediate 'truncate table statement';
execute immediate 'DROP index statement';

loop
--- other code
Insert data
commit;
end loop;

execute immediate 'Create index1 statement';
execute immediate 'Create index2 statement';

End;


问:
Dispose DbContext in MVC Controller, which way "better"?
In MVC 5, the scaffolding codes will have something like:

```<code>    public class MyController : Controller
{
    private MyContext db = new MyContext();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
</code>```

otherwise, I need to have

```<code>using (var db = new MyContext())
{...}
</code>```

in each action.

The codes look good, so I don't need to use using in each action. However, is this subject to preference of programmers, or such style has some advantage over using in each action that needs to use the dbcontext?

答:
For simple scenarios calling Dispose (or using Using) is not necessary at all :)
"The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed."
From here:
http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/</p>

Body:
In MVC 5, the scaffolding codes will have something like:

    public class MyController : Controller
{
    private MyContext db = new MyContext();

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }

otherwise, I need to have

using (var db = new MyContext())
{...}

in each action.

The codes look good, so I don't need to use using in each action. However, is this subject to preference of programmers, or such style has some advantage over using in each action that needs to use the dbcontext?


问:
In django migrations are not being applied to the database
I have updated some fields of a table in my database by removing a field and adding some, as well as adding a new table. I run:

```<code>python manage.py makemigrations
python manage.py migrate
</code>```

And I get no changes detected and no changes were applied.

In django admin I don't see the new table and when I click add a new record into the database it displays the old fields. This is also reflected in the database as it displays the old fields and not the new table.

I have dropped all tables in the database and deleted all migrations in each app leaving init.py and I still get this error which confuses me because how can it show old fields which I have deleted and there are no record of as I have deleted the table and migrations?

The code in question:

```<code>from __future__ import unicode_literals
from django.db import models
from src.profiles.models import Profiles

# Create your models here.
class Product(models.Model):
    name = models.CharField(max_length=200, primary_key=True)
    description = models.CharField(max_length=1000)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class ProductsOwned(models.Model):
    ownedID = models.ForeignKey(Profiles.user)
    product = models.ForeignKey(Product.name)
    purchaseDate = models.DateTimeField(auto_now=True)
    expiryDate = models.DateTimeField()

    def __str__(self):
        return self.name
</code>```

If you need any clarification or have any questions please ask.

Edit: I can literally delete all my code in the models and no changes will still be detected.

Edit 2: Make migrations code uploaded to a pastebin: http://pastebin.com/GywuiCZj

Edit 3: The app I am editing is catalog, my installed apps:

```<code>INSTALLED_APPS = [
    'profiles',
    'contact',
    'crispy_forms',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'stripe',
    'checkout',
    'catalog',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]
</code>```

答:
Could be possible the migration file is flagged as migrated due to certain reason.

Note:
1. If this is the 1 migration file in this app, the name of file would be 0001_initial. It could be possible you had migration file with name earlier which you could have deleted.

Also something I would suggest is in installed_apps keep all the django app i.e django.contrib.admin, django.contrib.auth ... above your custom apps.

Finally If nothing works you can unfake your migration file.

python manage.py migrate --fake core 0003

python manage.py migrate --fake core zero
(caution with this. It would unfake all the migration files)

and then

Reference: fake/unfake migration

Body:
I have updated some fields of a table in my database by removing a field and adding some, as well as adding a new table. I run:

python manage.py makemigrations
python manage.py migrate

And I get no changes detected and no changes were applied.

In django admin I don't see the new table and when I click add a new record into the database it displays the old fields. This is also reflected in the database as it displays the old fields and not the new table.

I have dropped all tables in the database and deleted all migrations in each app leaving init.py and I still get this error which confuses me because how can it show old fields which I have deleted and there are no record of as I have deleted the table and migrations?

The code in question:

from __future__ import unicode_literals
from django.db import models
from src.profiles.models import Profiles

# Create your models here.
class Product(models.Model):
    name = models.CharField(max_length=200, primary_key=True)
    description = models.CharField(max_length=1000)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class ProductsOwned(models.Model):
    ownedID = models.ForeignKey(Profiles.user)
    product = models.ForeignKey(Product.name)
    purchaseDate = models.DateTimeField(auto_now=True)
    expiryDate = models.DateTimeField()

    def __str__(self):
        return self.name

If you need any clarification or have any questions please ask.

Edit: I can literally delete all my code in the models and no changes will still be detected.

Edit 2: Make migrations code uploaded to a pastebin: http://pastebin.com/GywuiCZj

Edit 3: The app I am editing is catalog, my installed apps:

INSTALLED_APPS = [
    'profiles',
    'contact',
    'crispy_forms',
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'stripe',
    'checkout',
    'catalog',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]


问:
Replace text not contained in a tag using either Regex or XmlParser
I know that using Regular expressions to parse or manipulate HTML/XML is a bad idea and I usually would never do it. But considering it because of lack of alternatives.

I need to replace text inside a string that is not already part of a  tag (ideally a span tag with specific id) using C#.

For example, Lets say I want to replace all instaces of ABC in the following text that are not inside a span with Alternate text (another span in my case)

ABC at start of line or ABC here must be replaced but, ABC inside span must not be replaced with anything. Another ABC here  this ABC must also be replaced

I tried using regex with both look ahead and look behind assertion. Various combinations along the lines of

```<code>string regexPattern = "(?<!id=\"__publishingReusableFragment\").*?" + stringToMatch + ".*?(?!span)";
</code>```

but gave up on that.

I tried loading it into an XElement and trying to create a writer from there and getting text not inside of a  node. But couldn't figure that out either.

```<code>XElement xel = XElement.Parse("<payload>" + inputString + @"</payload>");
XmlWriter requiredWriter = xel.CreateWriter();
</code>```

I am hoping somehow to use the writer to get the strings that are not part of a node and replacing them.

Basically I am open to any suggestions/solutions to solve this problem.

Thanks in advance for the help.

答:
```<code>resultString = Regex.Replace(subjectString,
    @"(?<!              # assert that we can't match the following
                        # before the current position:
                        # An opening span tag with specified id
     <\s*span\s*id=""__publishingReusableFragment""\s*>
     (?:                # if it is not followed by...
      (?!<\s*/\s*span)  # a closing span tag
      .                 # at any position between the opening tag
     )*                 # and our text
    )                   # End of lookbehind assertion
    ABC                 # Match ABC",
    "XYZ", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);
</code>```

will work with all the caveats about HTML parsing (that you seem to know, so I won't repeat them here) still valid.

The regex matches ABC if it's not preceded by an opening  tag  and if there is no closing  tag between the two. It will obviously fail if there can be nested  tags.

Body:
I know that using Regular expressions to parse or manipulate HTML/XML is a bad idea and I usually would never do it. But considering it because of lack of alternatives.

I need to replace text inside a string that is not already part of a  tag (ideally a span tag with specific id) using C#.

For example, Lets say I want to replace all instaces of ABC in the following text that are not inside a span with Alternate text (another span in my case)

ABC at start of line or ABC here must be replaced but, ABC inside span must not be replaced with anything. Another ABC here  this ABC must also be replaced

I tried using regex with both look ahead and look behind assertion. Various combinations along the lines of

string regexPattern = "(?<!id=\"__publishingReusableFragment\").*?" + stringToMatch + ".*?(?!span)";

but gave up on that.

I tried loading it into an XElement and trying to create a writer from there and getting text not inside of a  node. But couldn't figure that out either.

XElement xel = XElement.Parse("<payload>" + inputString + @"</payload>");
XmlWriter requiredWriter = xel.CreateWriter();

I am hoping somehow to use the writer to get the strings that are not part of a node and replacing them.

Basically I am open to any suggestions/solutions to solve this problem.

Thanks in advance for the help.

Body:
resultString = Regex.Replace(subjectString,
    @"(?<!              # assert that we can't match the following
                        # before the current position:
                        # An opening span tag with specified id
     <\s*span\s*id=""__publishingReusableFragment""\s*>
     (?:                # if it is not followed by...
      (?!<\s*/\s*span)  # a closing span tag
      .                 # at any position between the opening tag
     )*                 # and our text
    )                   # End of lookbehind assertion
    ABC                 # Match ABC",
    "XYZ", RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace);

will work with all the caveats about HTML parsing (that you seem to know, so I won't repeat them here) still valid.

The regex matches ABC if it's not preceded by an opening <span id=__publishingReusableFragment"> tag  and if there is no closing <span> tag between the two. It will obviously fail if there can be nested <span> tags.


问:
Android app with fragments and listviews
I am developing an android app and I have multiple fragments with a listview  in each fragment.

I fill my listviews with data from an api.

I am wondering how can I cache my data so when a user changes the fragment(slide left - right) the data will not be loaded again.

答:
Try to add your Fragments when you open new fragment rather replace your fragments
something like below:</p>

```<code>CommittiesActivity abstractFragment = new CommittiesActivity();
                           FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                            ft.setCustomAnimations(android.R.anim.slide_in_left,
                                    android.R.anim.slide_out_right);
                            **ft.add**(R.id.frame_container, abstractFragment, "CommittiesActivity");
                            ft.addToBackStack(null);
                            ft.commit();
</code>```

Body:
Try to add your Fragments when you open new fragment rather replace your fragments
something like below:

CommittiesActivity abstractFragment = new CommittiesActivity();
                           FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
                            ft.setCustomAnimations(android.R.anim.slide_in_left,
                                    android.R.anim.slide_out_right);
                            **ft.add**(R.id.frame_container, abstractFragment, "CommittiesActivity");
                            ft.addToBackStack(null);
                            ft.commit();


问:
Vim syntax coloring: How do I highlight long lines only?
I would like vim to color "long" lines for me.  Using 80 columns as an example, I would like to highlight lines that exceed that length.  Here is roughly what I think the .vimrc file should contain, although it (1) doesn't work, and (2) uses Perl's regex syntax to illustrate my point, because I don't know Vim's well enough:

```<code>...
highlight Excess ctermbg=0
au Syntax * syn match Excess /.{80,}$/
...
</code>```

This (in my mind at least) should mark lines that exceed 80 columns.  What I would ideally like is the ability to color only the part of the line that exceeds 80 columns, so if a line is 85 columns, then the 81st through the 85th columns would be highlighted.

I'm sure Vim can do this, just not with me at the helm.

答:
This uses an autocommand to adjust the OverLength value to match your file type.</p>

```<code>" highlight lines longer than `textwidth` size for each filetype
autocmd FileType *
    \ if &textwidth |
    \    exec 'match OverLength /\%' . string(&textwidth+2) . 'v.*/' |
    \ endif
</code>```

Body:
I would like vim to color "long" lines for me.  Using 80 columns as an example, I would like to highlight lines that exceed that length.  Here is roughly what I think the .vimrc file should contain, although it (1) doesn't work, and (2) uses Perl's regex syntax to illustrate my point, because I don't know Vim's well enough:

...
highlight Excess ctermbg=0
au Syntax * syn match Excess /.{80,}$/
...

This (in my mind at least) should mark lines that exceed 80 columns.  What I would ideally like is the ability to color only the part of the line that exceeds 80 columns, so if a line is 85 columns, then the 81st through the 85th columns would be highlighted.

I'm sure Vim can do this, just not with me at the helm.

Body:
This uses an autocommand to adjust the OverLength value to match your file type.

" highlight lines longer than `textwidth` size for each filetype
autocmd FileType *
    \ if &textwidth |
    \    exec 'match OverLength /\%' . string(&textwidth+2) . 'v.*/' |
    \ endif


问:
Tkinter/ttk frame size
I'm trying to set the frame size via theme_settings and it just doesn't work.

```<code>from Tkinter import *
from ttk import *

root = Tk()

style = Style()
style.theme_settings('default',{'TFrame':{'configure':{'width':100, 'height':100}}})

frame = Frame(root)
frame.pack()

root.mainloop()
</code>```

But if I set it explicitly, then it works:

```<code>frame.configure(width=100, height=100)
</code>```

Why?

ttk.version = "0.3.1"

Tkinter.version = "$Revision: 81008 $"

P.S. I need to set this size via .theme_settings() method, the question exactly about it.

UPD: I've checked the same behavior with Button element and it works. Something is wrong with frames...

```<code>style = Style()
style.theme_settings('default',{'TButton':{'configure':{'width':100}}})

button = Button(root)
button.pack()
</code>```

UPD2: The same story with 'padding'. It works with buttons, but not with frames. While frames 'background' for example can be set via theme_settings

答:
The Answer should be like that:

root = tk.Tk()

width x height + x_offset + y_offset

root.geometry("500x300+250+100")

Title: Tkinter/ttk frame size

Body:
I'm trying to set the frame size via theme_settings and it just doesn't work.

from Tkinter import *
from ttk import *

root = Tk()

style = Style()
style.theme_settings('default',{'TFrame':{'configure':{'width':100, 'height':100}}})

frame = Frame(root)
frame.pack()

root.mainloop()

But if I set it explicitly, then it works:

frame.configure(width=100, height=100)

Why?

ttk.version = "0.3.1"

Tkinter.version = "$Revision: 81008 $"

P.S. I need to set this size via .theme_settings() method, the question exactly about it.

UPD: I've checked the same behavior with Button element and it works. Something is wrong with frames...

style = Style()
style.theme_settings('default',{'TButton':{'configure':{'width':100}}})

button = Button(root)
button.pack()

UPD2: The same story with 'padding'. It works with buttons, but not with frames. While frames 'background' for example can be set via theme_settings