问:
Excel VBA Determining Mass of Truck Shipments
I have a system where I have a list of data from a truck scale reading the weight of a truck on a scale. This data ranges from -30,000lbs or so due to the scale being tared but truckless, to 40,000lbs with a full and tared truck on it. My task is to determine the total weight that has left our facility via truck. The problem is some days only a few trucks leave our facility and others a dozen leave, all with slightly different weights.

The graph of these weights looks like a saw tooth pattern. It is a largely negative value (due to tare), quickly reaches approximately zero as a truck pulls onto the scale, and slowly builds to a final weight. After the final weight is reached the weight quickly goes back to the largely negative value as the truck pulls away.

My idea on how to approach this is look for where the data is less than zero and return the max weight of the sensor between zeros. If the max weight is above some noise filter value (say, 5000lbs) then add the max weight to some counter. In theory, not bad, in practice, a bit out of my league.

Here's my code so far, as I know I need to show my effort so far. I recommend ignoring it as it's mostly just a failed start after a few days of restarting work.

```<code>Public Function TruckLoad(rngData As Range)
Dim intCount As Integer
intCount = 0
For Each cell In rngData
    intCount = intCount + 1
Next cell
Dim n As Integer
n = 1
Dim x As Integer
x = 1
Dim arr() As Double
For i = 1 To intCount
    If rngData(i, 1) < 0 Then
        arr(n) = x
        n = n + 1
        x = x + 1
    Else
        x = x + 1
    End If
Next
TruckLoad = arr(1)

End Function
</code>```

If anyone could give me advice on how to proceed it would be extremely valuable. I'm not a computer programmer outside of the very basics.

Edit: Sorry, I should have said this initially. I can't post the entirety of the raw sample data but I can post a photo of a graph. There is a degree to which I can't post publicly (not that you can do anything particularly nefarious with the data, it's a corporate rule).

www.imgur.com/a/LGQY9

答:
My understanding of the data is in line with Robin's comment.  There are a couple of ways to solve this problem.  I've written a function loops through data range looking for the 'next zero' in the data set, and calculates the max value between the current row and the row that the 'next zero' is in.  If the max value is above the value of your noise filter, the value will be added to the running total.  </p>

```<code>Option Explicit

Private Const NOISE_FILTER As Double = 5000

Public Function TruckLoad(rngData As Range) As Double

    Dim r As Integer
    Dim runningTruckLoad As Double
    Dim maxLoadReading As Double
    Dim nextZeroRow As Integer

    For r = 1 To rngData.Rows.Count

        nextZeroRow = FindNextZeroRow(r, rngData)

        maxLoadReading = Application.WorksheetFunction.Max(Range(rngData.Cells(r, 1), rngData.Cells(nextZeroRow, 1)))

        If maxLoadReading > NOISE_FILTER Then
            runningTruckLoad = runningTruckLoad + maxLoadReading
        End If

        r = nextZeroRow 'skip the loop counter ahead to our new 0 row

    Next r

    TruckLoad = runningTruckLoad

End Function

Private Function FindNextZeroRow(startRow As Integer, searchRange As Range) As Integer

    Dim nextZeroRow As Range

    Set nextZeroRow = searchRange.Find(0, searchRange.Rows(startRow))

    If nextZeroRow.Row < startRow Then 'we've hit the end of the data range
        FindNextZeroRow = startRow
    ElseIf nextZeroRow.Value <> 0 Then  'we've found a data point with a zero in it, not interested in this row
        FindNextZeroRow = FindNextZeroRow(nextZeroRow.Row, searchRange)
    Else
        FindNextZeroRow = nextZeroRow.Row 'we've found our next zero data point
    End If

End Function
</code>```

Body:
I have a system where I have a list of data from a truck scale reading the weight of a truck on a scale. This data ranges from -30,000lbs or so due to the scale being tared but truckless, to 40,000lbs with a full and tared truck on it. My task is to determine the total weight that has left our facility via truck. The problem is some days only a few trucks leave our facility and others a dozen leave, all with slightly different weights.

The graph of these weights looks like a saw tooth pattern. It is a largely negative value (due to tare), quickly reaches approximately zero as a truck pulls onto the scale, and slowly builds to a final weight. After the final weight is reached the weight quickly goes back to the largely negative value as the truck pulls away.

My idea on how to approach this is look for where the data is less than zero and return the max weight of the sensor between zeros. If the max weight is above some noise filter value (say, 5000lbs) then add the max weight to some counter. In theory, not bad, in practice, a bit out of my league.

Here's my code so far, as I know I need to show my effort so far. I recommend ignoring it as it's mostly just a failed start after a few days of restarting work.

Public Function TruckLoad(rngData As Range)
Dim intCount As Integer
intCount = 0
For Each cell In rngData
    intCount = intCount + 1
Next cell
Dim n As Integer
n = 1
Dim x As Integer
x = 1
Dim arr() As Double
For i = 1 To intCount
    If rngData(i, 1) < 0 Then
        arr(n) = x
        n = n + 1
        x = x + 1
    Else
        x = x + 1
    End If
Next
TruckLoad = arr(1)

End Function

If anyone could give me advice on how to proceed it would be extremely valuable. I'm not a computer programmer outside of the very basics.

Edit: Sorry, I should have said this initially. I can't post the entirety of the raw sample data but I can post a photo of a graph. There is a degree to which I can't post publicly (not that you can do anything particularly nefarious with the data, it's a corporate rule).

www.imgur.com/a/LGQY9

Body:
My understanding of the data is in line with Robin's comment.  There are a couple of ways to solve this problem.  I've written a function loops through data range looking for the 'next zero' in the data set, and calculates the max value between the current row and the row that the 'next zero' is in.  If the max value is above the value of your noise filter, the value will be added to the running total.

Option Explicit

Private Const NOISE_FILTER As Double = 5000

Public Function TruckLoad(rngData As Range) As Double

    Dim r As Integer
    Dim runningTruckLoad As Double
    Dim maxLoadReading As Double
    Dim nextZeroRow As Integer

    For r = 1 To rngData.Rows.Count

        nextZeroRow = FindNextZeroRow(r, rngData)

        maxLoadReading = Application.WorksheetFunction.Max(Range(rngData.Cells(r, 1), rngData.Cells(nextZeroRow, 1)))

        If maxLoadReading > NOISE_FILTER Then
            runningTruckLoad = runningTruckLoad + maxLoadReading
        End If

        r = nextZeroRow 'skip the loop counter ahead to our new 0 row

    Next r

    TruckLoad = runningTruckLoad

End Function

Private Function FindNextZeroRow(startRow As Integer, searchRange As Range) As Integer

    Dim nextZeroRow As Range

    Set nextZeroRow = searchRange.Find(0, searchRange.Rows(startRow))

    If nextZeroRow.Row < startRow Then 'we've hit the end of the data range
        FindNextZeroRow = startRow
    ElseIf nextZeroRow.Value <> 0 Then  'we've found a data point with a zero in it, not interested in this row
        FindNextZeroRow = FindNextZeroRow(nextZeroRow.Row, searchRange)
    Else
        FindNextZeroRow = nextZeroRow.Row 'we've found our next zero data point
    End If

End Function


来源: stackexchange

问:
Registering namespaced PHP class methods with NuSoap
Is it possible to register a PHP autoloaded namespaced class method with the NuSoap library?  To be clear, the PHP class is namespaced.  This is not a question about XML namespacing.

For example, if I had a class defined in some file:

```<code><?php

  namespace \My\Fancy\Namespace;

  class MyClass {
       public static function foo() { /* ... */ }
       // ...
  }
</code>```

and I wanted to register it with my soap server:

```<code>    <?php

    use \My\Fancy\Namespace\MyClass; // autoloaded

    $server = new soap_server();

    // ... server configuration ...

    $server->register(
        'MyClass..foo'  // This does not work
        // ... etc. ...
    );
</code>```

I've run so many searches for this with no luck, so I hope I'm not asking a bad question.

答:
On nusoap_server class in invoke_method method, the code does not allow to use namespaces.

```<code>function invoke_method() {
    // many lines of code...

    $class = '';
    $method = '';
    if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
        $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
        if (class_exists($try_class)) {
            // get the class and method name
            $class = $try_class;
            $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
            $this->debug("in invoke_method, class=$class method=$method delim=$delim");
        } else {
            $this->debug("in invoke_method, class=$try_class not found");
        }
    } else {
        $try_class = '';
        $this->debug("in invoke_method, no class to try");
    }

    // many lines of code...
}
</code>```

But thank god for open source so lets modify the code!

This is what you could do:

```<code>function invoke_method() {
    // many lines of code...

    $class = '';
    $method = '';
    if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
        $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
        if (class_exists($try_class)) {
            // get the class and method name
            $class = $try_class;
            $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
            $this->debug("in invoke_method, class=$class method=$method delim=$delim");
        } else {
            $this->debug("in invoke_method, class=$try_class not found");
        }
    } elseif (strlen($delim) > 0 && substr_count($this->methodname, $delim) > 1) {
        $split = explode($delim, $this->methodname);
        $method = array_pop($split);
        $class = implode('\\', $split);
    } else {
        $try_class = '';
        $this->debug("in invoke_method, no class to try");
    }

    // many lines of code...
}
</code>```

Explaining:

```<code>// Example of namespaced class
// $this->methodname = 'Namespace.Namespace2.Class.MethodName';

// Has delimiter "." or ".." more than one time.
if (strlen($delim) > 0 && substr_count($this->methodname, $delim) > 1) {
    // code below
}

// Transform in array
$split = explode($delim, $this->methodname);
// $split = array('Namespace', 'Namespace2', 'Class', 'MethodName')

// Get the last item (method name) and remove from array.
$method = array_pop($split);
// $method = 'MethodName'
// $split = array('Namespace', 'Namespace2', 'Class')

// Transform the class name
$class = implode('\\', $split);
// $class = 'Namespace\Namespace2\Class'
</code>```

With this simple modification you can have the PHP namespace feature working.

I know that a long time passes but I hope to help some one with this answer.

ContentLicense: CC BY-SA 3.0

Body:
Is it possible to register a PHP autoloaded namespaced class method with the NuSoap library?  To be clear, the PHP class is namespaced.  This is not a question about XML namespacing.

For example, if I had a class defined in some file:

<?php

  namespace \My\Fancy\Namespace;

  class MyClass {
       public static function foo() { /* ... */ }
       // ...
  }

and I wanted to register it with my soap server:

    <?php

    use \My\Fancy\Namespace\MyClass; // autoloaded

    $server = new soap_server();

    // ... server configuration ...

    $server->register(
        'MyClass..foo'  // This does not work
        // ... etc. ...
    );

I've run so many searches for this with no luck, so I hope I'm not asking a bad question.

Body:
On nusoap_server class in invoke_method method, the code does not allow to use namespaces.

function invoke_method() {
    // many lines of code...

    $class = '';
    $method = '';
    if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
        $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
        if (class_exists($try_class)) {
            // get the class and method name
            $class = $try_class;
            $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
            $this->debug("in invoke_method, class=$class method=$method delim=$delim");
        } else {
            $this->debug("in invoke_method, class=$try_class not found");
        }
    } else {
        $try_class = '';
        $this->debug("in invoke_method, no class to try");
    }

    // many lines of code...
}

But thank god for open source so lets modify the code!

This is what you could do:

function invoke_method() {
    // many lines of code...

    $class = '';
    $method = '';
    if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) {
        $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim));
        if (class_exists($try_class)) {
            // get the class and method name
            $class = $try_class;
            $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim));
            $this->debug("in invoke_method, class=$class method=$method delim=$delim");
        } else {
            $this->debug("in invoke_method, class=$try_class not found");
        }
    } elseif (strlen($delim) > 0 && substr_count($this->methodname, $delim) > 1) {
        $split = explode($delim, $this->methodname);
        $method = array_pop($split);
        $class = implode('\\', $split);
    } else {
        $try_class = '';
        $this->debug("in invoke_method, no class to try");
    }

    // many lines of code...
}

Explaining:

// Example of namespaced class
// $this->methodname = 'Namespace.Namespace2.Class.MethodName';

// Has delimiter "." or ".." more than one time.
if (strlen($delim) > 0 && substr_count($this->methodname, $delim) > 1) {
    // code below
}

// Transform in array
$split = explode($delim, $this->methodname);
// $split = array('Namespace', 'Namespace2', 'Class', 'MethodName')

// Get the last item (method name) and remove from array.
$method = array_pop($split);
// $method = 'MethodName'
// $split = array('Namespace', 'Namespace2', 'Class')

// Transform the class name
$class = implode('\\', $split);
// $class = 'Namespace\Namespace2\Class'

With this simple modification you can have the PHP namespace feature working.

I know that a long time passes but I hope to help some one with this answer.


问:
Logstash metric filter for log-level
Can someone please help me with my metric filter. i want to set up logstash to check the log-level= Error for every 5s and if log-level = ERROR exceeds more than 1 , should send an email. i am using logstash 2.2.4 </p>

```<code>input {
      file {
        path => "/var/log/logstash/example"
        start_position => beginning
      }
    }

filter {
 grok{
   match => { "message" => "\[%{TIMESTAMP_ISO8601:timestamp}\]\[%{LOGLEVEL:log-level}\s*\]" }
 }
 if [log-level] == "ERROR" {
   metrics {
       meter => [ "log-level" ]
       flush_interval => 5
       clear_interval => 5
      }
   }
}
output {
if [log-level] == "ERROR" {
  if [log-level][count] < 1 {
    email {
        port => 25
        address => "mail.abc.com"
        authentication => "login"
        use_tls => true
        from => "alerts@logstash.com"
        subject => "logstash alert"
        to => "siya@abc.com"
        via => "smtp"
        body => "here is the event line %{message}"
        debug => true
      }
    }
  }
}
</code>```

答:
Editorial:

I am not a fan of the metrics {} filter, because it breaks assumptions. Logstash is multi-threaded, and metrics is one of the filters that only keeps state within its thread. If you use it, you need to be aware that if you're running 4 pipeline workers, you have 4 independent threads keeping their own state. This breaks the assumption that all events coming "into logstash" will be counted "by the metrics filter".

For your use-case, I'd recommend not using Logstash to issue this email, and instead rely on an external polling mechanism that hits your backing stores.

Because this is the metrics filter, I highly recommend you set your number of filter-workers to 1. This is the -w command-line option when logstash starts. You'll lose parallelism, but you'll gain the ability for a single filter to see all events. If you don't, you can get cases where all, say, 6 threads each see an ERROR event; and you will get six emails.

Your config could use some updates. It's recommended to add a tag or something to the metrics {} filter.

```<code> metrics {
     meter => [ "log-level" ]
     flush_interval => 5
     clear_interval => 5
     add_tag => "error_metric"
    }
 }
</code>```

This way, you can better filter your email segment.

```<code>output {
  if [tags] include "error_metric" and [log-level][count] > 1 {
    email {
    }
  }
}
</code>```

This is because the metrics {} filter creates a new event when it flushes, rather than amending an existing one. You need to catch the new event with your filters.

Title: Logstash metric filter for log-level

Body:
Can someone please help me with my metric filter. i want to set up logstash to check the log-level= Error for every 5s and if log-level = ERROR exceeds more than 1 , should send an email. i am using logstash 2.2.4

input {
      file {
        path => "/var/log/logstash/example"
        start_position => beginning
      }
    }

filter {
 grok{
   match => { "message" => "\[%{TIMESTAMP_ISO8601:timestamp}\]\[%{LOGLEVEL:log-level}\s*\]" }
 }
 if [log-level] == "ERROR" {
   metrics {
       meter => [ "log-level" ]
       flush_interval => 5
       clear_interval => 5
      }
   }
}
output {
if [log-level] == "ERROR" {
  if [log-level][count] < 1 {
    email {
        port => 25
        address => "mail.abc.com"
        authentication => "login"
        use_tls => true
        from => "alerts@logstash.com"
        subject => "logstash alert"
        to => "siya@abc.com"
        via => "smtp"
        body => "here is the event line %{message}"
        debug => true
      }
    }
  }
}

Body:
Editorial:

I am not a fan of the metrics {} filter, because it breaks assumptions. Logstash is multi-threaded, and metrics is one of the filters that only keeps state within its thread. If you use it, you need to be aware that if you're running 4 pipeline workers, you have 4 independent threads keeping their own state. This breaks the assumption that all events coming "into logstash" will be counted "by the metrics filter".

For your use-case, I'd recommend not using Logstash to issue this email, and instead rely on an external polling mechanism that hits your backing stores.

Because this is the metrics filter, I highly recommend you set your number of filter-workers to 1. This is the -w command-line option when logstash starts. You'll lose parallelism, but you'll gain the ability for a single filter to see all events. If you don't, you can get cases where all, say, 6 threads each see an ERROR event; and you will get six emails.

Your config could use some updates. It's recommended to add a tag or something to the metrics {} filter.

 metrics {
     meter => [ "log-level" ]
     flush_interval => 5
     clear_interval => 5
     add_tag => "error_metric"
    }
 }

This way, you can better filter your email segment.

output {
  if [tags] include "error_metric" and [log-level][count] > 1 {
    email {
    }
  }
}

This is because the metrics {} filter creates a new event when it flushes, rather than amending an existing one. You need to catch the new event with your filters.


问:
how can i left join and add where condition its doesn't read the where it brings all the ridedriver object?
How can I LEFT and add WHERE condition?
It doesn't read the where it brings all the ridedriver object?

```<code>SELECT p
FROM RideDriverEmployeeBundle:Ridedriver p
LEFT JOIN Chaya3niUserBundle:Bookings b WITH b.idridedriver = p.id
WHERE p.frequency IS NOT NULL
  AND p.nbrplaces > 0
  AND b.iduser != 2
  OR b.iduser IS NULL
</code>```

答:
If I understand your question correctly it is probably an issue with your WHERE clause. Try using parantheses with the OR portion of the clause.

```<code>SELECT p
FROM RideDriverEmployeeBundle:Ridedriver p
LEFT JOIN Chaya3niUserBundle:Bookings b WITH b.idridedriver = p.id
WHERE p.frequency IS NOT NULL
  AND p.nbrplaces > 0
  AND (b.iduser != 2 OR b.iduser IS NULL)
</code>```

To answer the question you asked in the comments..

i want to select all the driverrides except the one that the user already booked in

Sounds like you just do not want the other conditions you have in your WHERE clause.

```<code>SELECT p
FROM RideDriverEmployeeBundle:Ridedriver p
LEFT JOIN Chaya3niUserBundle:Bookings b WITH b.idridedriver = p.id
WHERE b.iduser IS NULL
</code>```

By doing a LEFT JOIN and then only taking records that did not exist in the joined table with WHERE .. IS NULL, this is doing a LEFT OUTER JOIN.

In your case Ridedriver is Table A and Bookings is Table B, so this will return records in Ridedriver that do not join to anything in Bookings.

Body:
How can I LEFT and add WHERE condition?
It doesn't read the where it brings all the ridedriver object?

SELECT p
FROM RideDriverEmployeeBundle:Ridedriver p
LEFT JOIN Chaya3niUserBundle:Bookings b WITH b.idridedriver = p.id
WHERE p.frequency IS NOT NULL
  AND p.nbrplaces > 0
  AND b.iduser != 2
  OR b.iduser IS NULL

Body:
If I understand your question correctly it is probably an issue with your WHERE clause. Try using parantheses with the OR portion of the clause.

SELECT p
FROM RideDriverEmployeeBundle:Ridedriver p
LEFT JOIN Chaya3niUserBundle:Bookings b WITH b.idridedriver = p.id
WHERE p.frequency IS NOT NULL
  AND p.nbrplaces > 0
  AND (b.iduser != 2 OR b.iduser IS NULL)

To answer the question you asked in the comments..

i want to select all the driverrides except the one that the user already booked in

Sounds like you just do not want the other conditions you have in your WHERE clause.

SELECT p
FROM RideDriverEmployeeBundle:Ridedriver p
LEFT JOIN Chaya3niUserBundle:Bookings b WITH b.idridedriver = p.id
WHERE b.iduser IS NULL

By doing a LEFT JOIN and then only taking records that did not exist in the joined table with WHERE .. IS NULL, this is doing a LEFT OUTER JOIN.

In your case Ridedriver is Table A and Bookings is Table B, so this will return records in Ridedriver that do not join to anything in Bookings.


问:
Vba: ‘On error’ statement safety
I made a macro that records, then changes the local settings (in my case the decimal separator). At the end of the macro it would restore the settings.

When there is an error I make the program also restore the local settings using the ‘on error’ statement.
(A simplified  example of the program is given below)

So far I got no issues; however, as I am now planning to transfer the program to my working colleagues, I really wish to not interfere with them and overwrite their own local settings.

Does the On error statement is here safe enough to use and make sure that the settings are restored?

Is there any case where the program could run into an error that the On error would fail to redirect to the error handler?

PS: I already know I can convert all my numbers using String = Replace(Number, ",", ".") but for some reasons I cannot afford to go through all the many variables of the macro.

Example Code:

```<code>Private Declare Function GetUserDefaultLCID% Lib "kernel32" ()
Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function SetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean

Sub test()
  ' what to do on error
  On Error GoTo ErrorHandler:
  ' define a number (Your local settings are set up to
  Dim MyNumber As Single
  MyNumber = 0.03
  MsgBox ("Number is 0,03 ->" & MyNumber)
  ' record the settings in the variable LocalSettingsDecimal
  Dim LocalSettingsDecimal As String
  Dim Buffer As String
  Buffer = String(256, 0)
  Dim le As Integer
  le = GetLocaleInfoA(GetUserDefaultLCID(), 14, Buffer, Len(Buffer))
  LocalSettingsDecimal = Left(Buffer, le - 1)

  ' force decimal settings to '.'
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, ".")

  ' Now is the program body
  MsgBox ("Number is now 0.03 ->" & MyNumber)
  ' an unfortunate error:
  MyNumber = "aa"

  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("Number should be back 0,03 ->" & MyNumber)
  Exit Sub
  ErrorHandler:
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("There was an error but it's ok, it should be back to 0,03 ->" & MyNumber)
End Sub
</code>```

答:
If the End command is encountered anywhere in the code then this will foil your plan.

Take a look at the example below. If A calls B then no problem, errors are handled and when control returns to A the handler will still execute your locale reset. But uncomment the call to C and run the code again. Execution simply stops and control never returns to A so the reset is not performed.

So your scenario is that you send the workbook to your colleague and then they to add on some more logic which uses the End command for whatever reason.

```<code>Option Explicit

Sub A()
    On Error GoTo ErrHandler

    Dim foo As Long

    'call B
    B
    ' call C - uncomment to see impact
    'C

ErrHandler:
    Debug.Print "Error occurred in A"
    Debug.Print "Fixing locale stuff..."

End Sub

Sub B()
    On Error GoTo ErrHandler

    Dim foo As Long

    'cause an error
    foo = "bar"

ErrHandler:
    Debug.Print "Error occurred in B"
    Debug.Print Err.Description

End Sub

Sub C()
    On Error GoTo ErrHandler

    Dim foo As Long

    'cause an error
    foo = "bar"

ErrHandler:
    Debug.Print "Error occurred in C"
    Debug.Print Err.Description
    End

End Sub
</code>```

Title: Vba: ‘On error’ statement safety

Body:
I made a macro that records, then changes the local settings (in my case the decimal separator). At the end of the macro it would restore the settings.

When there is an error I make the program also restore the local settings using the ‘on error’ statement.
(A simplified  example of the program is given below)

So far I got no issues; however, as I am now planning to transfer the program to my working colleagues, I really wish to not interfere with them and overwrite their own local settings.

Does the On error statement is here safe enough to use and make sure that the settings are restored?

Is there any case where the program could run into an error that the On error would fail to redirect to the error handler?

PS: I already know I can convert all my numbers using String = Replace(Number, ",", ".") but for some reasons I cannot afford to go through all the many variables of the macro.

Example Code:

Private Declare Function GetUserDefaultLCID% Lib "kernel32" ()
Private Declare Function GetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Declare Function SetLocaleInfoA Lib "kernel32" (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String) As Boolean

Sub test()
  ' what to do on error
  On Error GoTo ErrorHandler:
  ' define a number (Your local settings are set up to
  Dim MyNumber As Single
  MyNumber = 0.03
  MsgBox ("Number is 0,03 ->" & MyNumber)
  ' record the settings in the variable LocalSettingsDecimal
  Dim LocalSettingsDecimal As String
  Dim Buffer As String
  Buffer = String(256, 0)
  Dim le As Integer
  le = GetLocaleInfoA(GetUserDefaultLCID(), 14, Buffer, Len(Buffer))
  LocalSettingsDecimal = Left(Buffer, le - 1)

  ' force decimal settings to '.'
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, ".")

  ' Now is the program body
  MsgBox ("Number is now 0.03 ->" & MyNumber)
  ' an unfortunate error:
  MyNumber = "aa"

  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("Number should be back 0,03 ->" & MyNumber)
  Exit Sub
  ErrorHandler:
  Call SetLocaleInfoA(GetUserDefaultLCID(), 14, LocalSettingsDecimal)
  MsgBox ("There was an error but it's ok, it should be back to 0,03 ->" & MyNumber)
End Sub

Body:
If the End command is encountered anywhere in the code then this will foil your plan.

Take a look at the example below. If A calls B then no problem, errors are handled and when control returns to A the handler will still execute your locale reset. But uncomment the call to C and run the code again. Execution simply stops and control never returns to A so the reset is not performed.

So your scenario is that you send the workbook to your colleague and then they to add on some more logic which uses the End command for whatever reason.

Option Explicit

Sub A()
    On Error GoTo ErrHandler

    Dim foo As Long

    'call B
    B
    ' call C - uncomment to see impact
    'C

ErrHandler:
    Debug.Print "Error occurred in A"
    Debug.Print "Fixing locale stuff..."

End Sub

Sub B()
    On Error GoTo ErrHandler

    Dim foo As Long

    'cause an error
    foo = "bar"

ErrHandler:
    Debug.Print "Error occurred in B"
    Debug.Print Err.Description

End Sub

Sub C()
    On Error GoTo ErrHandler

    Dim foo As Long

    'cause an error
    foo = "bar"

ErrHandler:
    Debug.Print "Error occurred in C"
    Debug.Print Err.Description
    End

End Sub


问:
PHP HTML select option not working
I have a dropdown with 3 choices. Blank, Option A, and Option B. The code should be selecting the correct one, but it's making the wrong one selected.

Updated code with new parenthesis syntax

```<code>    <select name="memType">
        <option value="" selected="<?php if ( ($status !== 'Option A') && ($status !== 'Option B') ){echo 'selected';}?>">None</option>
        <option value="Option A" selected="<?php if (($status) == ('Option A')){echo 'selected';}?>">Option A</option>
        <option value="Option B" selected="<?php if (($status) == ('Option B')){echo 'selected';}?>">Option B</option>
    </select>
</code>```

答: @Elbarto is correct, all I needed to do was echo "checked" and not "checked='checked'"</p>

Title: PHP HTML select option not working

Body:
I have a dropdown with 3 choices. Blank, Option A, and Option B. The code should be selecting the correct one, but it's making the wrong one selected.

Updated code with new parenthesis syntax

    <select name="memType">
        <option value="" selected="<?php if ( ($status !== 'Option A') && ($status !== 'Option B') ){echo 'selected';}?>">None</option>
        <option value="Option A" selected="<?php if (($status) == ('Option A')){echo 'selected';}?>">Option A</option>
        <option value="Option B" selected="<?php if (($status) == ('Option B')){echo 'selected';}?>">Option B</option>
    </select>


问:
Number of different ways n + 1 factors can be completely parenthesized
Imagine I have four letters a,b,c and d. I want to determine what are the ways to  validly parenthesize and multiply them. For instance (a.b).(c.d) can be a solution or (a.(b.c)).d another solution. The number of combinations is 5 for 4 letters. (Which is also equivalent to Catalan Number n-1 in that case catalan number 3 which is 5).

I have realized that these combinations can be written as full binary trees and each binary tree represents one combination :

```<code> abcd                abcd
  /  \                / \      .....
 /    \              /   \
a     bcd           ab    cd
       / \          / \   /\
      bc  d        a   b c  d
      / \
     b   c
</code>```

Starting from the deepest leaf, algorithm can generate for instance for the first tree :  1 - (b.c)  then 2 - (b.c).d   then 3- a.((b.c).d).

I want to have a recursive or normal function which can generate all the possible trees and do the multiplications but not sure how I can achieve that. Any help and suggestion is greatly appreciated.

答:
Here's a JavaScript adaptation of ninjagecko's Python code from How to print all possible balanced parentheses for an expression?

function associations(seq, kw){
  var grouper = kw.grouper || ((a,b) => [a,b]),
      lifter = kw.lifter || (x => [x]);

  if (seq.length === 1){
    return lifter(seq[0]);

  } else {
    var result = [];

    for (let i=1; i<seq.length; i++){
      // split sequence on index i
      var left = seq.slice(0,i),
          right = seq.slice(i);

      // return cartesian product of left x right
      for (let l of associations(left,kw))
        for (let r of associations(right,kw))
          result.push(grouper(l,r));
    }
    return result;
  }
}

console.log(JSON.stringify(associations([1,2,3,4],{})));```

Body:
Imagine I have four letters a,b,c and d. I want to determine what are the ways to  validly parenthesize and multiply them. For instance (a.b).(c.d) can be a solution or (a.(b.c)).d another solution. The number of combinations is 5 for 4 letters. (Which is also equivalent to Catalan Number n-1 in that case catalan number 3 which is 5).

I have realized that these combinations can be written as full binary trees and each binary tree represents one combination :

 abcd                abcd
  /  \                / \      .....
 /    \              /   \
a     bcd           ab    cd
       / \          / \   /\
      bc  d        a   b c  d
      / \
     b   c

Starting from the deepest leaf, algorithm can generate for instance for the first tree :  1 - (b.c)  then 2 - (b.c).d   then 3- a.((b.c).d).

I want to have a recursive or normal function which can generate all the possible trees and do the multiplications but not sure how I can achieve that. Any help and suggestion is greatly appreciated.


问:
How to check if TcpClient Connection is closed?
I'm playing around with the TcpClient and I'm trying to figure out how to make the Connected property say false when a connection is dropped.

I tried doing

```<code>NetworkStream ns = client.GetStream();
ns.Write(new byte[1], 0, 0);
</code>```

But it still will not show me if the TcpClient is disconnected. How would you go about this using a TcpClient?

答:
In my case, I was sending some command to a server (running in a virtual machine on the same computer) and waiting for the response. However, if the server stopped unexpectedly while waiting, I did not get any notification. I tried the possibilities proposed by the other posters, but neither did work (it always said that the server is still connected). For me, the only thing that is working is to write 0 bytes to the stream:</p>

```<code>var client = new TcpClient();
//... open the client

var stream = client.GetStream();

//... send something to the client

byte[] empty = { 0 };
//wait for response from server
while (client.Available == 0)
{
    //throws a SocketException if the connection is closed by the server
    stream.Write(empty, 0, 0);
    Thread.Sleep(10);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm playing around with the TcpClient and I'm trying to figure out how to make the Connected property say false when a connection is dropped.

I tried doing

NetworkStream ns = client.GetStream();
ns.Write(new byte[1], 0, 0);

But it still will not show me if the TcpClient is disconnected. How would you go about this using a TcpClient?

Body:
In my case, I was sending some command to a server (running in a virtual machine on the same computer) and waiting for the response. However, if the server stopped unexpectedly while waiting, I did not get any notification. I tried the possibilities proposed by the other posters, but neither did work (it always said that the server is still connected). For me, the only thing that is working is to write 0 bytes to the stream:

var client = new TcpClient();
//... open the client

var stream = client.GetStream();

//... send something to the client

byte[] empty = { 0 };
//wait for response from server
while (client.Available == 0)
{
    //throws a SocketException if the connection is closed by the server
    stream.Write(empty, 0, 0);
    Thread.Sleep(10);
}


问:
Framework7 autocomplete working only locally
I have this autocomplete element from Framework7:

```<code>var autocompleteDropdownSimple = myApp.autocomplete({
    input: '#autocomplete-dropdown',
    openIn: 'dropdown',
    source: function (autocomplete, query, render) {
        var results = [];
        names = ["name1","framework","server","local","bank"]
        if (query.length === 0) {
            render(results);
            return;
        }
        // Find matched items
        for (var i = 0; i < names.length; i++) {
            if (names[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) {
                results.push(names[i]);
            }
        }
        // Render items by passing array with result items
        render(results);
    },
    onClose: function () {
    },
    onError: function() {
    }
});
</code>```

My problem is that autocomplete works fine only if my html file is loaded locally (file://...). If this run on a webserver (such as PhoneGap or python simplehttpserver) i have no autocomplete and no suggestion while typing.
How is that possible?

All other js functions are working fine, like alert() on page init, so js files are correctly loaded.

答: Solved adding that code in onInit function of relative page.</p>

Body:
I have this autocomplete element from Framework7:

var autocompleteDropdownSimple = myApp.autocomplete({
    input: '#autocomplete-dropdown',
    openIn: 'dropdown',
    source: function (autocomplete, query, render) {
        var results = [];
        names = ["name1","framework","server","local","bank"]
        if (query.length === 0) {
            render(results);
            return;
        }
        // Find matched items
        for (var i = 0; i < names.length; i++) {
            if (names[i].toLowerCase().indexOf(query.toLowerCase()) >= 0) {
                results.push(names[i]);
            }
        }
        // Render items by passing array with result items
        render(results);
    },
    onClose: function () {
    },
    onError: function() {
    }
});

My problem is that autocomplete works fine only if my html file is loaded locally (file://...). If this run on a webserver (such as PhoneGap or python simplehttpserver) i have no autocomplete and no suggestion while typing.
How is that possible?

All other js functions are working fine, like alert() on page init, so js files are correctly loaded.


问:
Page auto reload without refresh
Hi
I want to know How to make the page reload asynchronous, for example if someone has received a message , the last message will appear without refreshing the page. just like facebook. thank you.</p>

答:
well there is alot of approaches
but the basics is that you call an ajax function every second or so that
checks with external php/asp or whatever file if any changes has been made to your
database/text if so
append it to the chatbox.

p.s. using libraries such as jquery simplifies things alot

Title: Page auto reload without refresh


问:
Redirection and Regex in WordPress
I have recently visited by Google Search Console just to discover that when I was updating my site back in 2011 that I have previously used a different type of permalinks withing WordPress thus creating over 500 404 errors.

Now I installed the plugin called "Redirections" for WordPress and tried to get rid of the 404 errors with simple ragex commands but it seems I am doing something wrong.

My old link looks like this:
http://www.example.com/category/blog_domain/2011/02/random-title-inserted-here/
New links are like this:
http://www.example.com/random-title-inserted-here/

So I inputted this under source url: /([A-Za-z_0-9-]*)/([A-Za-z0-9-]*)/(\d*)/(\d*)/([A-Za-z0-9-]*)
And this under target: `/$5``

Any ideas what I'm doing wrong?

答:
To anyone else looking for an answer to this:

Source: ^/category/blog_domain/([0-9]{4})/([0-9]{2})/([^/]+)/$

Target: /$3

Title: Redirection and Regex in WordPress


问:
HowTo: Increment the value of an integer based field in GraphQL
So, I wish to create a GraphQL mutation, in GraphCool, that increments the existing value of an integer field by a predetermined amount, passed in as a variable. For example:

mutation updateLikes ($id: ID!, $count: Int) {
  updatePosts (id: $id, likes: incrementBy $count) {
    id
    likes
  }
}

Query variable

{
  "id" : "cj0qkl04vep8k0177tky596og",
  "count": 1
}```
</div>
</div>
</p>

<p>How do I do this?</p>

<p>Also, I am attempting to trigger the above mentioned process from a onClick event, but am getting an 'cannot read property 'props' of null' error message, I suspect on this.props.client.query:</p>

<p>Photo.js</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>import React from 'react';
import Comments from './Comments';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { Link } from 'react-router';
import {
  gql,
  graphql,
  withApollo
} from 'react-apollo';
import ApolloClient from 'apollo-client';

class Photo extends React.Component {

  incrementQuery(currentID) {
    console.log("like of id=" + currentID+ " has been incremented by 1");

    this.props.client.query({
      query: gql`
        mutation updatePosts($id: ID!) {
          updatePosts (id: $id, likes: 1) {
            id
            likes
          }
        }
      `,
      variables: {
        id: currentID,
      },
    });
  }

  render() {
    const { post, i } = this.props;

    return (
      <figure key={i} className="grid-figure">

        <div className='grid-photo-wrap'>
          <Link to={`/view/${post.id}`}>
            <img className='grid-photo' src={post.displaysrc} alt={post.caption} />
          </Link>

          <CSSTransitionGroup transitionName="like" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
            <span key={post.likes} className="likes-heart">{post.likes}</span>
          </CSSTransitionGroup>

        </div>

        <figcaption>
          <p>{post.caption}</p>

          <div className="control-buttons">
            <button onClick={this.incrementQuery.bind(null,i)} className="likes">♥ {post.likes}</button>

            <Link to={`/view/${post.id}`} className="button">
              <span className="comment-count">
                <span className="speech-bubble"></span> {(post.comments ? Object.keys(post.comments).length : 0)}
              </span>
            </Link>
          </div>

        </figcaption>

      </figure>
    )
  }
};

Photo.PropTypes = {
  client: React.PropTypes.instanceOf(ApolloClient).isRequired,
  query: React.PropTypes.object,
  variables: React.PropTypes.object,
  data: React.PropTypes.shape({
    loading: React.PropTypes.bool.isRequired,
    error: React.PropTypes.bool.isRequired,
    updatePosts: React.PropTypes.object,
  }).isRequired,
}

const PhotoWithApollo = withApollo(Photo);

export default PhotoWithApollo;</code>```

The thrown error is as follows:

Uncaught TypeError: Cannot read property 'props' of null
    at incrementQuery (http://localhost:7770/static/bundle.js:56347:12)
    at proxiedMethod (http://localhost:7770/static/bundle.js:54898:31)
    at HTMLUnknownElement.wrapped (http://localhost:7770/static/bundle.js:47347:30)
    at Object.ReactErrorUtils.invokeGuardedCallback (http://localhost:7770/static/bundle.js:6346:17)
    at executeDispatch (http://localhost:7770/static/bundle.js:6146:22)
    at Object.executeDispatchesInOrder (http://localhost:7770/static/bundle.js:6169:6)
    at executeDispatchesAndRelease (http://localhost:7770/static/bundle.js:5599:23)
    at executeDispatchesAndReleaseTopLevel (http://localhost:7770/static/bundle.js:5610:11)
    at Array.forEach (native)
    at forEachAccumulated (http://localhost:7770/static/bundle.js:6446:10)
    at Object.processEventQueue (http://localhost:7770/static/bundle.js:5815:8)
    at runEventQueueInBatch (http://localhost:7770/static/bundle.js:6475:19)
    at Object.handleTopLevel [as _handleTopLevel] (http://localhost:7770/static/bundle.js:6491:6)
    at handleTopLevelWithoutPath (http://localhost:7770/static/bundle.js:16697:25)
    at handleTopLevelImpl (http://localhost:7770/static/bundle.js:16677:4)
    at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:7770/static/bundle.js:8643:21)
    at Object.batchedUpdates (http://localhost:7770/static/bundle.js:12680:20)
    at Object.batchedUpdates (http://localhost:7770/static/bundle.js:8148:21)
    at dispatchEvent (http://localhost:7770/static/bundle.js:16808:21)
    at HTMLDocument.wrapped (http://localhost:7770/static/bundle.js:47347:30)```

答:
Currently you need to first query the value:

```<code>query Post($id: ID!) {
  Post (id: $id) {
    id
    likes
  }
}
</code>```

Then increment the likes client-side and update the post with the new value for likes:

```<code>mutation updateLikes ($id: ID!, $likes: Int!) {
  updatePost (id: $id, likes: $likes) {
    id
    likes
  }
}
</code>```

Incrementing the likes by a special number is a great use case for a custom mutation, which we are already working on.

Body:
So, I wish to create a GraphQL mutation, in GraphCool, that increments the existing value of an integer field by a predetermined amount, passed in as a variable. For example:

mutation updateLikes ($id: ID!, $count: Int) {
  updatePosts (id: $id, likes: incrementBy $count) {
    id
    likes
  }
}

Query variable

{
  "id" : "cj0qkl04vep8k0177tky596og",
  "count": 1
}

How do I do this?

Also, I am attempting to trigger the above mentioned process from a onClick event, but am getting an 'cannot read property 'props' of null' error message, I suspect on this.props.client.query:

Photo.js

import React from 'react';
import Comments from './Comments';
import CSSTransitionGroup from 'react-addons-css-transition-group';
import { Link } from 'react-router';
import {
  gql,
  graphql,
  withApollo
} from 'react-apollo';
import ApolloClient from 'apollo-client';

class Photo extends React.Component {

  incrementQuery(currentID) {
    console.log("like of id=" + currentID+ " has been incremented by 1");

    this.props.client.query({
      query: gql`
        mutation updatePosts($id: ID!) {
          updatePosts (id: $id, likes: 1) {
            id
            likes
          }
        }
      `,
      variables: {
        id: currentID,
      },
    });
  }

  render() {
    const { post, i } = this.props;

    return (

          <Link to={`/view/${post.id}`}>

          </Link>

          <CSSTransitionGroup transitionName="like" transitionEnterTimeout={500} transitionLeaveTimeout={500}>
            {post.likes}
          </CSSTransitionGroup>

{post.caption}

            <button onClick={this.incrementQuery.bind(null,i)} className="likes">♥ {post.likes}</button>

            <Link to={`/view/${post.id}`} className="button">

                 {(post.comments ? Object.keys(post.comments).length : 0)}

            </Link>

    )
  }
};

Photo.PropTypes = {
  client: React.PropTypes.instanceOf(ApolloClient).isRequired,
  query: React.PropTypes.object,
  variables: React.PropTypes.object,
  data: React.PropTypes.shape({
    loading: React.PropTypes.bool.isRequired,
    error: React.PropTypes.bool.isRequired,
    updatePosts: React.PropTypes.object,
  }).isRequired,
}

const PhotoWithApollo = withApollo(Photo);

export default PhotoWithApollo;

The thrown error is as follows:

Uncaught TypeError: Cannot read property 'props' of null
    at incrementQuery (http://localhost:7770/static/bundle.js:56347:12)
    at proxiedMethod (http://localhost:7770/static/bundle.js:54898:31)
    at HTMLUnknownElement.wrapped (http://localhost:7770/static/bundle.js:47347:30)
    at Object.ReactErrorUtils.invokeGuardedCallback (http://localhost:7770/static/bundle.js:6346:17)
    at executeDispatch (http://localhost:7770/static/bundle.js:6146:22)
    at Object.executeDispatchesInOrder (http://localhost:7770/static/bundle.js:6169:6)
    at executeDispatchesAndRelease (http://localhost:7770/static/bundle.js:5599:23)
    at executeDispatchesAndReleaseTopLevel (http://localhost:7770/static/bundle.js:5610:11)
    at Array.forEach (native)
    at forEachAccumulated (http://localhost:7770/static/bundle.js:6446:10)
    at Object.processEventQueue (http://localhost:7770/static/bundle.js:5815:8)
    at runEventQueueInBatch (http://localhost:7770/static/bundle.js:6475:19)
    at Object.handleTopLevel [as _handleTopLevel] (http://localhost:7770/static/bundle.js:6491:6)
    at handleTopLevelWithoutPath (http://localhost:7770/static/bundle.js:16697:25)
    at handleTopLevelImpl (http://localhost:7770/static/bundle.js:16677:4)
    at ReactDefaultBatchingStrategyTransaction.perform (http://localhost:7770/static/bundle.js:8643:21)
    at Object.batchedUpdates (http://localhost:7770/static/bundle.js:12680:20)
    at Object.batchedUpdates (http://localhost:7770/static/bundle.js:8148:21)
    at dispatchEvent (http://localhost:7770/static/bundle.js:16808:21)
    at HTMLDocument.wrapped (http://localhost:7770/static/bundle.js:47347:30)

Body:
Currently you need to first query the value:

query Post($id: ID!) {
  Post (id: $id) {
    id
    likes
  }
}

Then increment the likes client-side and update the post with the new value for likes:

mutation updateLikes ($id: ID!, $likes: Int!) {
  updatePost (id: $id, likes: $likes) {
    id
    likes
  }
}

Incrementing the likes by a special number is a great use case for a custom mutation, which we are already working on.


问:
AngularJS: server call on tab/browser close
I have a section in my application where I establish a communication between the server and the client that loops forever until the user leaves this screen. When the user leaves the screen, I detect this issue with $rootScope.$on('$stateChangeStart') and send a $http call to stop the process in the server.

I want to perform that same $http when the user closes the current tab or browser but I cannot get this done.

First of all this is the service function that makes the $http call:

```<code>function cancelCommProcess(webId, commActionId) {
          return $http.get(BASE_URL + '/rest/comm/kill-current-com-process/' + webId + '/' + commActionId)
            .then(
                    function(response) {
                        return response;
                    }
            );
      }
</code>```

As I said, when I call this function in the $rootScope.$on('$stateChangeStart') or some other point, it works.

Now I have the following code to call this function when tab/browser is closed:

```<code>$window.onbeforeunload = function (evt) {
            if ($rootScope.CMC_ACTION_IDENTIFIER.CMC_ACTION_MONITORING === currentCommActionId) {
                CMCService.cancelCommProcess(currentWebId, currentCommActionId)
                    .then(
                            function() {
                                console.log('HELLO');
                            }
                    );
            }
        }
</code>```

This way the $http call doesn't reach the server, but if I simply made the next change, then it works:

```<code>$window.onbeforeunload = function (evt) {
            if ($rootScope.CMC_ACTION_IDENTIFIER.CMC_ACTION_MONITORING === currentCommActionId) {
                CMCService.cancelCommProcess(currentWebId, currentCommActionId)
                    .then(
                            function() {
                                myTest();
                            }
                    );
            }
        }

        function myTest() {
            console.log('HELLO');
        }
</code>```

Even more, previous method works in Chrome and Firefox but not in Edge. But it works (I mean, the $http call reaches the server) if I do it like this:

```<code>$window.onbeforeunload = function (evt) {
    if ($rootScope.CMC_ACTION_IDENTIFIER.CMC_ACTION_MONITORING === currentCommActionId) {
        CMCService.cancelCommProcess(currentWebId, currentCommActionId)
            .then(
                    function() {
                        myTest();
                        //console.log('HELLO');
                    }
            );
    }
    return "";
}

function myTest() {
    console.log('HELLO');
}
</code>```

Of course I get the confirm message to leave or stay the page, but I don't know why the call reaches the server just by showing this message.

I don't really understand how this works so I appreciate your help. The idea of the $http call is to tell the server to interrupt the current communication process but I feel this method is not truthful.

Would you help me to figure out what's the best approach for this?

Thank you.

答:
I suggest you to use socket.io that keep connection alive between client and server and not loop in server. </p>

<p>This event fire when controller destory you can use it </p>

```<code>$scope.$on('$destroy', function() {
   console.log("destory");
});
</code>```

Body:
I have a section in my application where I establish a communication between the server and the client that loops forever until the user leaves this screen. When the user leaves the screen, I detect this issue with $rootScope.$on('$stateChangeStart') and send a $http call to stop the process in the server.

I want to perform that same $http when the user closes the current tab or browser but I cannot get this done.

First of all this is the service function that makes the $http call:

function cancelCommProcess(webId, commActionId) {
          return $http.get(BASE_URL + '/rest/comm/kill-current-com-process/' + webId + '/' + commActionId)
            .then(
                    function(response) {
                        return response;
                    }
            );
      }

As I said, when I call this function in the $rootScope.$on('$stateChangeStart') or some other point, it works.

Now I have the following code to call this function when tab/browser is closed:

$window.onbeforeunload = function (evt) {
            if ($rootScope.CMC_ACTION_IDENTIFIER.CMC_ACTION_MONITORING === currentCommActionId) {
                CMCService.cancelCommProcess(currentWebId, currentCommActionId)
                    .then(
                            function() {
                                console.log('HELLO');
                            }
                    );
            }
        }

This way the $http call doesn't reach the server, but if I simply made the next change, then it works:

$window.onbeforeunload = function (evt) {
            if ($rootScope.CMC_ACTION_IDENTIFIER.CMC_ACTION_MONITORING === currentCommActionId) {
                CMCService.cancelCommProcess(currentWebId, currentCommActionId)
                    .then(
                            function() {
                                myTest();
                            }
                    );
            }
        }

        function myTest() {
            console.log('HELLO');
        }

Even more, previous method works in Chrome and Firefox but not in Edge. But it works (I mean, the $http call reaches the server) if I do it like this:

$window.onbeforeunload = function (evt) {
    if ($rootScope.CMC_ACTION_IDENTIFIER.CMC_ACTION_MONITORING === currentCommActionId) {
        CMCService.cancelCommProcess(currentWebId, currentCommActionId)
            .then(
                    function() {
                        myTest();
                        //console.log('HELLO');
                    }
            );
    }
    return "";
}

function myTest() {
    console.log('HELLO');
}

Of course I get the confirm message to leave or stay the page, but I don't know why the call reaches the server just by showing this message.

I don't really understand how this works so I appreciate your help. The idea of the $http call is to tell the server to interrupt the current communication process but I feel this method is not truthful.

Would you help me to figure out what's the best approach for this?

Thank you.

Body:
I suggest you to use socket.io that keep connection alive between client and server and not loop in server.

This event fire when controller destory you can use it

$scope.$on('$destroy', function() {
   console.log("destory");
});


问:
Addition of two integer in binary representation
I would like to implement code which will add two integers by their binary representation.

For instance:

```<code>a = [1 1 1 0];
</code>```

and

```<code>b = [1 0 1 1];
</code>```

So I implemented the following algorithm:

```<code>function s=add_binary(a,b)
  m=length(a);
  s=zeros(m+1,0);
  n=length(a);
  c=0;
  for ii=n:-1:1
    d=floor((a(ii)+b(ii)+c)/2);
    s(ii)=a(ii)+b(ii)+c-2*d;
    c=d;
  end
  s(1)=c;
end
</code>```

However, it returns this as a result:

```<code>s=add_binary(a,b)

s =

     1     0     0     1
</code>```

Here, there should be an additional 1 on the left, such that it would read:

```<code>1 1 0 0 1
</code>```

Where am I making a mistake?

答:
This problem was discussed in a 2011 question on MATLAB Answers. I'd like to mention 2 more solutions:

If you have the Communications System Toolbox, you can use bi2de and de2bi:

```<code>de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb')
</code>```

If the amount of "digits" in the input is known (and reasonable), one solution could be to store all possible input combinations in some data-structure, which would facilitate rapid access. One such example is the MapN class (though it can just as easily be done with regular numeric arrays). I will provide a small example to show this idea (including a benchmark):

```<code>function allResults = q43095156(allResults)
  if nargin == 0
  % Let's store all combinations of 8 binary digits:
  in = uint8(0:255);
  out = uint16(in)+uint16(in.');
  outB = logical(de2bi(out(:),'left-msb'));
  [in1,in2] = meshgrid(in,in);
  allResults = MapN(...
     num2cell([num2cell(in1(:),2),num2cell(in2(:),2)],2),...
     num2cell(outB,2));
  end
  benchmark(allResults);
end

function benchmark(allResults)
  rng(43095156);
  a = logical(randi([0 1],10,8,'uint8'));
  b = logical(randi([0 1],10,8,'uint8'));
  % Test:
  R{5} = de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb');
  R{4} = add_a_bunch_gnovice(a,b);
  R{3} = add_a_bunch_Sardar(a,b);
  R{2} = add_a_bunch_dato(a,b);
  R{1} = getFromMap(a, b, allResults);
  assert(isequal(R{:}));
  % Benchmark:
  a = logical(randi([0 1],1000,8,'uint8'));
  b = logical(randi([0 1],1000,8,'uint8'));
  fprintf(1,'\nSardar''s method:\t%f',timeit(@() add_a_bunch_Sardar(a, b) ));
  fprintf(1,'\nDev-iL''s method:\t%f',timeit(@() getFromMap(a, b, allResults) ));
  fprintf(1,'\ngnovice''s method:\t%f',timeit(@() add_a_bunch_gnovice(a, b) ));
  fprintf(1,'\ndato''s method:\t\t%f',timeit(@() add_a_bunch_dato(a, b) ));
  fprintf(1,'\nbi2de method:\t\t%f',timeit(@() de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb')));
end

function out = getFromMap(a,b,map)
out = cell2mat(values(map, num2cell([ num2cell(bi2de(a,'left-msb'),2),...
                                      num2cell(bi2de(b,'left-msb'),2)],2)));
end

function out = add_a_bunch_gnovice(a,b)
  out = zeros(size(a)+[0,1],'logical');
  for ind1 = 1:size(a,1)
    out(ind1,:) = add_binary_gnovice(a(ind1,:), b(ind1,:));
  end
end

function out = add_a_bunch_Sardar(a,b)
  out = zeros(size(a)+[0,1],'logical');
  for ind1 = 1:size(a,1)
    out(ind1,:) = add_binary_Sardar(a(ind1,:), b(ind1,:));
  end
end

function out = add_a_bunch_dato(a,b)
  out = zeros(size(a)+[0,1],'logical');
  for ind1 = 1:size(a,1)
    out(ind1,:) = add_binary_dato(a(ind1,:), b(ind1,:));
  end
end

function s = add_binary_gnovice(a, b)
  a = [0 a];
  b = [0 b];
  c = a&b;
  while any(c)
    b = xor(a, b);
    a = circshift(c, -1);
    c = a&b;
  end
  s = a+b;
end

function s = add_binary_Sardar(a,b)
  s = logical(str2double(num2cell(dec2bin(bin2dec(num2str(a)) +...
                                          bin2dec(num2str(b)), numel(a)+1))));
end

function s = add_binary_dato(a,b)
  m = length(a);
  s = zeros(m+1,1);
  n = length(a);
  c = 0;
  for ii = n:-1:1
    d = floor((a(ii)+b(ii)+c)/2);
    s(ii+1) = a(ii)+b(ii)+c-2*d;
    c = d;
  end
  s(1) = c;
  s = logical(s.');
end
</code>```

And the results with my x64 MATLAB R2017a @ Win10 are:

```<code>Sardar's method:    0.336414
Dev-iL's method:    0.061656
gnovice's method:   0.022031
dato's method:      0.002123
bi2de method:       0.000356
</code>```

So this should give us an idea which methods are faster (unless I messed the wrapper functions up greatly)...

The advantage of the MapN method would be noticeable if the computation of the sum was some other, costlier operation.

Body:
I would like to implement code which will add two integers by their binary representation.

For instance:

a = [1 1 1 0];

and

b = [1 0 1 1];

So I implemented the following algorithm:

function s=add_binary(a,b)
  m=length(a);
  s=zeros(m+1,0);
  n=length(a);
  c=0;
  for ii=n:-1:1
    d=floor((a(ii)+b(ii)+c)/2);
    s(ii)=a(ii)+b(ii)+c-2*d;
    c=d;
  end
  s(1)=c;
end

However, it returns this as a result:

s=add_binary(a,b)

s =

     1     0     0     1

Here, there should be an additional 1 on the left, such that it would read:

1 1 0 0 1

Where am I making a mistake?

Body:
This problem was discussed in a 2011 question on MATLAB Answers. I'd like to mention 2 more solutions:

If you have the Communications System Toolbox, you can use bi2de and de2bi:

de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb')

If the amount of "digits" in the input is known (and reasonable), one solution could be to store all possible input combinations in some data-structure, which would facilitate rapid access. One such example is the MapN class (though it can just as easily be done with regular numeric arrays). I will provide a small example to show this idea (including a benchmark):

function allResults = q43095156(allResults)
  if nargin == 0
  % Let's store all combinations of 8 binary digits:
  in = uint8(0:255);
  out = uint16(in)+uint16(in.');
  outB = logical(de2bi(out(:),'left-msb'));
  [in1,in2] = meshgrid(in,in);
  allResults = MapN(...
     num2cell([num2cell(in1(:),2),num2cell(in2(:),2)],2),...
     num2cell(outB,2));
  end
  benchmark(allResults);
end

function benchmark(allResults)
  rng(43095156);
  a = logical(randi([0 1],10,8,'uint8'));
  b = logical(randi([0 1],10,8,'uint8'));
  % Test:
  R{5} = de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb');
  R{4} = add_a_bunch_gnovice(a,b);
  R{3} = add_a_bunch_Sardar(a,b);
  R{2} = add_a_bunch_dato(a,b);
  R{1} = getFromMap(a, b, allResults);
  assert(isequal(R{:}));
  % Benchmark:
  a = logical(randi([0 1],1000,8,'uint8'));
  b = logical(randi([0 1],1000,8,'uint8'));
  fprintf(1,'\nSardar''s method:\t%f',timeit(@() add_a_bunch_Sardar(a, b) ));
  fprintf(1,'\nDev-iL''s method:\t%f',timeit(@() getFromMap(a, b, allResults) ));
  fprintf(1,'\ngnovice''s method:\t%f',timeit(@() add_a_bunch_gnovice(a, b) ));
  fprintf(1,'\ndato''s method:\t\t%f',timeit(@() add_a_bunch_dato(a, b) ));
  fprintf(1,'\nbi2de method:\t\t%f',timeit(@() de2bi(bi2de(a,'left-msb') + bi2de(b,'left-msb'),'left-msb')));
end

function out = getFromMap(a,b,map)
out = cell2mat(values(map, num2cell([ num2cell(bi2de(a,'left-msb'),2),...
                                      num2cell(bi2de(b,'left-msb'),2)],2)));
end

function out = add_a_bunch_gnovice(a,b)
  out = zeros(size(a)+[0,1],'logical');
  for ind1 = 1:size(a,1)
    out(ind1,:) = add_binary_gnovice(a(ind1,:), b(ind1,:));
  end
end

function out = add_a_bunch_Sardar(a,b)
  out = zeros(size(a)+[0,1],'logical');
  for ind1 = 1:size(a,1)
    out(ind1,:) = add_binary_Sardar(a(ind1,:), b(ind1,:));
  end
end

function out = add_a_bunch_dato(a,b)
  out = zeros(size(a)+[0,1],'logical');
  for ind1 = 1:size(a,1)
    out(ind1,:) = add_binary_dato(a(ind1,:), b(ind1,:));
  end
end

function s = add_binary_gnovice(a, b)
  a = [0 a];
  b = [0 b];
  c = a&b;
  while any(c)
    b = xor(a, b);
    a = circshift(c, -1);
    c = a&b;
  end
  s = a+b;
end

function s = add_binary_Sardar(a,b)
  s = logical(str2double(num2cell(dec2bin(bin2dec(num2str(a)) +...
                                          bin2dec(num2str(b)), numel(a)+1))));
end

function s = add_binary_dato(a,b)
  m = length(a);
  s = zeros(m+1,1);
  n = length(a);
  c = 0;
  for ii = n:-1:1
    d = floor((a(ii)+b(ii)+c)/2);
    s(ii+1) = a(ii)+b(ii)+c-2*d;
    c = d;
  end
  s(1) = c;
  s = logical(s.');
end

And the results with my x64 MATLAB R2017a @ Win10 are:

Sardar's method:    0.336414
Dev-iL's method:    0.061656
gnovice's method:   0.022031
dato's method:      0.002123
bi2de method:       0.000356

So this should give us an idea which methods are faster (unless I messed the wrapper functions up greatly)...

The advantage of the MapN method would be noticeable if the computation of the sum was some other, costlier operation.


问:
Realm Browser ask for encrypted key after update to Xcode 8.3
I'm using Realm as database in an app. Until I've updated Xcode to 8.3 version, I was able to use Realm Browser to read realm file directly from simulator (I didn't set any encryption key on Realm configuration).

But, since yesterday, when I upgraded Xcode, Realm Browser asks for an encryption key. I've open older realm files from the same project, but no those new database files created on run with Xcode 8.3.

Any idea about what is happening? Maybe something related whit the new filesystem used by Apple?

Thankyou.

答:
Realm 2.5 introduces new file format. Existing files will automatically be upgraded when they are opened. The Realm browser in AppStore doesn't support the new file format. You can use new version of browser that can be downloaded from GitHub until new version will be passed AppStore review.

https://github.com/realm/realm-browser-osx/releases/tag/v2.1.7


问:
Java array sorting in reverse! Need to reverse the reverse
Right now I have my array sorting (which is better than getting an error) except it is sorting in the reverse than what I want it to sort in.

```<code>   public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("\nSort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       String a, b = null;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i+1;
           for(int j=iPosMin; j<numRecords; j++)
           {
               a = sDeptArr[i];
               b = sDeptArr[iPosMin];
               if(a.compareTo(b) > 0)
               {
                   sTemp= sDeptArr[j];
                   sDeptArr[j] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[j];
                   iCourseNumArr[j] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[j];
                   iEnrollmentArr[j] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else if(sDeptArr[j].equals(sDeptArr[iPosMin]) && !(iCourseNumArr[j] < iCourseNumArr[iPosMin]))
               {
                   sTemp= sDeptArr[i];
                   sDeptArr[i] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[i];
                   iCourseNumArr[i] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[i];
                   iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else continue;
           }

       }
   }
</code>```

Again, no array lists or array.sorts. I need just to reverse how this is sorting but I have no idea how.

答:
just do a.compareTo(b) < 0 instead of the > 0

EDIT: I've figured out the problem. But since this is homework (thanks for being honest), I won't post my solution, but here are a few tips:

You are doing selection sort. The algorithm isn't as complicated as you made it. You only have to swap if the two elements you are checking are in the wrong order. I see you have 3 branches there, no need.

Take a look at when you are assigning a and b. Through the inner loop, where j is changing, a and b never change, because i and iPosMin stay the same. I hope that helps.

It's always good to break your algorithm down to discreet parts that you know works by extracting methods. You repeat the same swap code twice, but with different arguments for indices. Take that out and just make a:

-

```<code>// swaps the object at position i with position j in all arrays
private static void swap(String[] sDeptArr, int[] iCourseNumArr, int[] iEnrollmentArr, int i, int j)
</code>```

Then you'll see you're code get a lot cleaner.

Body:
Right now I have my array sorting (which is better than getting an error) except it is sorting in the reverse than what I want it to sort in.

   public static void sortDatabase(int numRecords, String[] sDeptArr,
              int[] iCourseNumArr, int[] iEnrollmentArr)
   {
       System.out.println("\nSort the database. \n");
       String sTemp = null;
       int iTemp = 0;
       int eTemp = 0;
       String a, b = null;
       for(int i=0; i<numRecords; i++)
       {
           int iPosMin = i+1;
           for(int j=iPosMin; j<numRecords; j++)
           {
               a = sDeptArr[i];
               b = sDeptArr[iPosMin];
               if(a.compareTo(b) > 0)
               {
                   sTemp= sDeptArr[j];
                   sDeptArr[j] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[j];
                   iCourseNumArr[j] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[j];
                   iEnrollmentArr[j] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else if(sDeptArr[j].equals(sDeptArr[iPosMin]) && !(iCourseNumArr[j] < iCourseNumArr[iPosMin]))
               {
                   sTemp= sDeptArr[i];
                   sDeptArr[i] = sDeptArr[iPosMin];
                   sDeptArr[iPosMin] = sTemp;
                   iTemp = iCourseNumArr[i];
                   iCourseNumArr[i] = iCourseNumArr[iPosMin];
                   iCourseNumArr[iPosMin] = iTemp;
                   eTemp = iEnrollmentArr[i];
                   iEnrollmentArr[i] = iEnrollmentArr[iPosMin];
                   iEnrollmentArr[iPosMin] = eTemp;
               }
               else continue;
           }

       }
   }

Again, no array lists or array.sorts. I need just to reverse how this is sorting but I have no idea how.

Body:
just do a.compareTo(b) < 0 instead of the > 0

EDIT: I've figured out the problem. But since this is homework (thanks for being honest), I won't post my solution, but here are a few tips:

You are doing selection sort. The algorithm isn't as complicated as you made it. You only have to swap if the two elements you are checking are in the wrong order. I see you have 3 branches there, no need.

Take a look at when you are assigning a and b. Through the inner loop, where j is changing, a and b never change, because i and iPosMin stay the same. I hope that helps.

It's always good to break your algorithm down to discreet parts that you know works by extracting methods. You repeat the same swap code twice, but with different arguments for indices. Take that out and just make a:

-

// swaps the object at position i with position j in all arrays
private static void swap(String[] sDeptArr, int[] iCourseNumArr, int[] iEnrollmentArr, int i, int j)

Then you'll see you're code get a lot cleaner.


问:
How to make database go to SQL Server instead of localDB?
I am able to log into SSMS under Windows Authentication and SQL Server Authentication. But I am not seeing the Database anywhere in the SQL Server Management Studio. In Visual Studio, it goes to the localDb even though I have changed the connection string to have the db created in my SSMS.

```<code><!--<add name="BookServiceContext" connectionString="Data Source=(localdb)\MSSQLLocalDB; Initial Catalog=BookServiceContext-20170328200803; Integrated Security=True; MultipleActiveResultSets=True; AttachDbFilename=|DataDirectory|BookServiceContext-20170328200803.mdf"
      providerName="System.Data.SqlClient" />-->
    <add name="BookServiceContext" connectionString="Data Source=AA5570LT;Initial Catalog=BookServiceContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />
</code>```

Sometimes, I can see the name BookServiceContext under Data Connections in VS Server Explorer, but when I click on the connection I get this error message

Cannot open database "BookServiceContext" requested by the login. The login failed.
  Login failed for user 'MLS\AAnwar'.

What can I do so that it goes to the right connection in my SSMS?

答: After working my head off with this issue for the past 2 days, finally have it working. All I had to do was set the Project as a "StartUp Project" in Solution Explorer and it fixed the issue. The database was created in the right Server with all the data. </p>

Body:
I am able to log into SSMS under Windows Authentication and SQL Server Authentication. But I am not seeing the Database anywhere in the SQL Server Management Studio. In Visual Studio, it goes to the localDb even though I have changed the connection string to have the db created in my SSMS.

    <add name="BookServiceContext" connectionString="Data Source=AA5570LT;Initial Catalog=BookServiceContext;Integrated Security=SSPI;" providerName="System.Data.SqlClient" />

Sometimes, I can see the name BookServiceContext under Data Connections in VS Server Explorer, but when I click on the connection I get this error message

Cannot open database "BookServiceContext" requested by the login. The login failed.
  Login failed for user 'MLS\AAnwar'.

What can I do so that it goes to the right connection in my SSMS?


问:
Return two sets of results from SQL query
My stored procedure is like this:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Product_Search]
(
    /* Optional Filters for Dynamic Search*/
   @ProductName NVARCHAR(200)=NULL,

   /*– Pagination Parameters */
   @PageNo INT = 1,
   @PageSize INT = 10,

   /*– Sorting Parameters */
   @SortColumn NVARCHAR(20) = 'ProductAddedDate',
   @SortOrder NVARCHAR(4)='ASC',
   @PostCodes NVARCHAR(400)=NULL
)
AS
BEGIN
    /*–Declaring Local Variables corresponding to parameters for modification */
    DECLARE
        @lPageNbr INT,
        @lPageSize INT,
        @lSortCol NVARCHAR(20),
        @lFirstRec INT,
        @lLastRec INT,
        @lTotalRows INT

    /*Setting Local Variables*/

    SET @lPageNbr = @PageNo
    SET @lPageSize = @PageSize
    SET @lSortCol = LTRIM(RTRIM(@SortColumn))

    SET @lFirstRec = ( @lPageNbr - 1 ) * @lPageSize
    SET @lLastRec = ( @lPageNbr * @lPageSize + 1 )
    SET @lTotalRows = @lFirstRec - @lLastRec + 1;

    WITH CTE_Results AS
    (
        SELECT ROW_NUMBER() OVER
            (
                ORDER BY
                    CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='ASC'
                        THEN ProductName
                    END ASC,
                    CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='DESC'
                         THEN ProductName
                    END DESC,
                     CASE WHEN (@lSortCol = 'Price' AND @SortOrder='ASC')
                              THEN Price
                    END ASC,
                    CASE WHEN @lSortCol = 'Price' AND @SortOrder='DESC'
                             THEN Price
                    END DESC
           ) AS ROWNUM,
            Count(*) over () AS TotalCount,
            Id as ProductId ,
            ProductName,
            ProductDescription,
            [Price] ,
            [FairName] ,
            [FairDescription] ,
            [StartDate],
            [EndDate]  ,
            [FairLogo] ,
            [ProductAddedDate],
            ProductCategory_Id,
            FairId,
            IsHeroItem,
            ProductSubCategoryId ,
            SubCategoryName,
            MainCategoryName
        FROM wf_view_Products
        WHERE
            (@ProductName is NULL OR ProductName like '%'+ @ProductName+ '%') AND
            (@PostCodes is NULL OR PostCode IN( SELECT CAST(Item AS INTEGER) FROM dbo.SplitString(@PostCodes, ',')))
    )
    SELECT ProductId,
        ROWNUM,
        ProductCategory_Id,
        IsHeroItem,
        ProductName,
        ProductDescription,
        [Price],
        [FairName],
        [FairDescription],
        [StartDate],
        [EndDate],
        [FairLogo],
        [ProductAddedDate],
        FairId
    FROM CTE_Results AS CPC
    WHERE ROWNUM > @lFirstRec
        AND ROWNUM < @lLastRec
    ORDER BY ROWNUM ASC

    SELECT ProductId
    FROM CTE_Results AS Categories
    WHERE 1 = 1
END
</code>```

When I remove this line everything works, else it throws an error:

Msg 208, Level 16, State 1, Procedure Product_Search, Line 65

  [Batch Start Line 2]

  Invalid object name 'CTE_Results'

Can anyone please let me know how I can solve this?

答:
As suggested in the comments you can use a temp table (or even a table variable if you prefer, but in this case you have to define the table's structure).

Here is your stored procedure edited to use a temp table:

```<code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Product_Search]
(
    /* Optional Filters for Dynamic Search*/
   @ProductName NVARCHAR(200)=NULL,

   /*– Pagination Parameters */
   @PageNo INT = 1,
   @PageSize INT = 10,

   /*– Sorting Parameters */
   @SortColumn NVARCHAR(20) = 'ProductAddedDate',
   @SortOrder NVARCHAR(4)='ASC',
   @PostCodes NVARCHAR(400)=NULL
)
AS
BEGIN
    /*–Declaring Local Variables corresponding to parameters for modification */
    DECLARE
        @lPageNbr INT,
        @lPageSize INT,
        @lSortCol NVARCHAR(20),
        @lFirstRec INT,
        @lLastRec INT,
        @lTotalRows INT

    /*Setting Local Variables*/

    SET @lPageNbr = @PageNo
    SET @lPageSize = @PageSize
    SET @lSortCol = LTRIM(RTRIM(@SortColumn))

    SET @lFirstRec = ( @lPageNbr - 1 ) * @lPageSize
    SET @lLastRec = ( @lPageNbr * @lPageSize + 1 )
    SET @lTotalRows = @lFirstRec - @lLastRec + 1;

    SELECT ROW_NUMBER() OVER
        (
            ORDER BY
                CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='ASC'
                    THEN ProductName
                END ASC,
                CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='DESC'
                     THEN ProductName
                END DESC,
                 CASE WHEN (@lSortCol = 'Price' AND @SortOrder='ASC')
                          THEN Price
                END ASC,
                CASE WHEN @lSortCol = 'Price' AND @SortOrder='DESC'
                         THEN Price
                END DESC
       ) AS ROWNUM,
        Count(*) over () AS TotalCount,
        Id as ProductId ,
        ProductName,
        ProductDescription,
        [Price] ,
        [FairName] ,
        [FairDescription] ,
        [StartDate],
        [EndDate]  ,
        [FairLogo] ,
        [ProductAddedDate],
        ProductCategory_Id,
        FairId,
        IsHeroItem,
        ProductSubCategoryId ,
        SubCategoryName,
        MainCategoryName
    INTO #tmpTable --create a temp table on the fly
    FROM wf_view_Products
    WHERE
        (@ProductName is NULL OR ProductName like '%'+ @ProductName+ '%') AND
        (@PostCodes is NULL OR PostCode IN( SELECT CAST(Item AS INTEGER) FROM dbo.SplitString(@PostCodes, ',')))

    SELECT ProductId,
        ROWNUM,
        ProductCategory_Id,
        IsHeroItem,
        ProductName,
        ProductDescription,
        [Price],
        [FairName],
        [FairDescription],
        [StartDate],
        [EndDate],
        [FairLogo],
        [ProductAddedDate],
        FairId
    FROM #tmpTable AS CPC --select from temp table  instead of CTE
    WHERE ROWNUM > @lFirstRec
        AND ROWNUM < @lLastRec
    ORDER BY ROWNUM ASC

    SELECT ProductId
    FROM #tmpTable AS Categories --select from temp table  instead of CTE
    WHERE 1 = 1
END
</code>```

Body:
My stored procedure is like this:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Product_Search]
(
    /* Optional Filters for Dynamic Search*/
   @ProductName NVARCHAR(200)=NULL,

   /*– Pagination Parameters */
   @PageNo INT = 1,
   @PageSize INT = 10,

   /*– Sorting Parameters */
   @SortColumn NVARCHAR(20) = 'ProductAddedDate',
   @SortOrder NVARCHAR(4)='ASC',
   @PostCodes NVARCHAR(400)=NULL
)
AS
BEGIN
    /*–Declaring Local Variables corresponding to parameters for modification */
    DECLARE
        @lPageNbr INT,
        @lPageSize INT,
        @lSortCol NVARCHAR(20),
        @lFirstRec INT,
        @lLastRec INT,
        @lTotalRows INT

    /*Setting Local Variables*/

    SET @lPageNbr = @PageNo
    SET @lPageSize = @PageSize
    SET @lSortCol = LTRIM(RTRIM(@SortColumn))

    SET @lFirstRec = ( @lPageNbr - 1 ) * @lPageSize
    SET @lLastRec = ( @lPageNbr * @lPageSize + 1 )
    SET @lTotalRows = @lFirstRec - @lLastRec + 1;

    WITH CTE_Results AS
    (
        SELECT ROW_NUMBER() OVER
            (
                ORDER BY
                    CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='ASC'
                        THEN ProductName
                    END ASC,
                    CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='DESC'
                         THEN ProductName
                    END DESC,
                     CASE WHEN (@lSortCol = 'Price' AND @SortOrder='ASC')
                              THEN Price
                    END ASC,
                    CASE WHEN @lSortCol = 'Price' AND @SortOrder='DESC'
                             THEN Price
                    END DESC
           ) AS ROWNUM,
            Count(*) over () AS TotalCount,
            Id as ProductId ,
            ProductName,
            ProductDescription,
            [Price] ,
            [FairName] ,
            [FairDescription] ,
            [StartDate],
            [EndDate]  ,
            [FairLogo] ,
            [ProductAddedDate],
            ProductCategory_Id,
            FairId,
            IsHeroItem,
            ProductSubCategoryId ,
            SubCategoryName,
            MainCategoryName
        FROM wf_view_Products
        WHERE
            (@ProductName is NULL OR ProductName like '%'+ @ProductName+ '%') AND
            (@PostCodes is NULL OR PostCode IN( SELECT CAST(Item AS INTEGER) FROM dbo.SplitString(@PostCodes, ',')))
    )
    SELECT ProductId,
        ROWNUM,
        ProductCategory_Id,
        IsHeroItem,
        ProductName,
        ProductDescription,
        [Price],
        [FairName],
        [FairDescription],
        [StartDate],
        [EndDate],
        [FairLogo],
        [ProductAddedDate],
        FairId
    FROM CTE_Results AS CPC
    WHERE ROWNUM > @lFirstRec
        AND ROWNUM < @lLastRec
    ORDER BY ROWNUM ASC

    SELECT ProductId
    FROM CTE_Results AS Categories
    WHERE 1 = 1
END

When I remove this line everything works, else it throws an error:

Msg 208, Level 16, State 1, Procedure Product_Search, Line 65

  [Batch Start Line 2]

  Invalid object name 'CTE_Results'

Can anyone please let me know how I can solve this?

Body:
As suggested in the comments you can use a temp table (or even a table variable if you prefer, but in this case you have to define the table's structure).

Here is your stored procedure edited to use a temp table:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[Product_Search]
(
    /* Optional Filters for Dynamic Search*/
   @ProductName NVARCHAR(200)=NULL,

   /*– Pagination Parameters */
   @PageNo INT = 1,
   @PageSize INT = 10,

   /*– Sorting Parameters */
   @SortColumn NVARCHAR(20) = 'ProductAddedDate',
   @SortOrder NVARCHAR(4)='ASC',
   @PostCodes NVARCHAR(400)=NULL
)
AS
BEGIN
    /*–Declaring Local Variables corresponding to parameters for modification */
    DECLARE
        @lPageNbr INT,
        @lPageSize INT,
        @lSortCol NVARCHAR(20),
        @lFirstRec INT,
        @lLastRec INT,
        @lTotalRows INT

    /*Setting Local Variables*/

    SET @lPageNbr = @PageNo
    SET @lPageSize = @PageSize
    SET @lSortCol = LTRIM(RTRIM(@SortColumn))

    SET @lFirstRec = ( @lPageNbr - 1 ) * @lPageSize
    SET @lLastRec = ( @lPageNbr * @lPageSize + 1 )
    SET @lTotalRows = @lFirstRec - @lLastRec + 1;

    SELECT ROW_NUMBER() OVER
        (
            ORDER BY
                CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='ASC'
                    THEN ProductName
                END ASC,
                CASE WHEN @lSortCol = 'ProductAddedDate' AND @SortOrder='DESC'
                     THEN ProductName
                END DESC,
                 CASE WHEN (@lSortCol = 'Price' AND @SortOrder='ASC')
                          THEN Price
                END ASC,
                CASE WHEN @lSortCol = 'Price' AND @SortOrder='DESC'
                         THEN Price
                END DESC
       ) AS ROWNUM,
        Count(*) over () AS TotalCount,
        Id as ProductId ,
        ProductName,
        ProductDescription,
        [Price] ,
        [FairName] ,
        [FairDescription] ,
        [StartDate],
        [EndDate]  ,
        [FairLogo] ,
        [ProductAddedDate],
        ProductCategory_Id,
        FairId,
        IsHeroItem,
        ProductSubCategoryId ,
        SubCategoryName,
        MainCategoryName
    INTO #tmpTable --create a temp table on the fly
    FROM wf_view_Products
    WHERE
        (@ProductName is NULL OR ProductName like '%'+ @ProductName+ '%') AND
        (@PostCodes is NULL OR PostCode IN( SELECT CAST(Item AS INTEGER) FROM dbo.SplitString(@PostCodes, ',')))

    SELECT ProductId,
        ROWNUM,
        ProductCategory_Id,
        IsHeroItem,
        ProductName,
        ProductDescription,
        [Price],
        [FairName],
        [FairDescription],
        [StartDate],
        [EndDate],
        [FairLogo],
        [ProductAddedDate],
        FairId
    FROM #tmpTable AS CPC --select from temp table  instead of CTE
    WHERE ROWNUM > @lFirstRec
        AND ROWNUM < @lLastRec
    ORDER BY ROWNUM ASC

    SELECT ProductId
    FROM #tmpTable AS Categories --select from temp table  instead of CTE
    WHERE 1 = 1
END


问:
How to build an Angular2 type script with spring boot back end in STS
I am learning angular 2 currently and trying to hosted in springboot java application.

I created a separate project using angular cli , then I created spring starter project with web only.

Next I imported the angular cli project inside /src/main/resources/static directory.

when I opened the browser , I was not able to see the basic index.html.

Then I removed all the imported files and imported only the content of the  directory , which is the resulting compiled ES5 java script after transpiling the type script files in  directory, this time it worked.

My questions are:-

1) What is the best practice , to use the GUI under /src/main/statis or create /src/main/public or /src/main/webapp ?

2) Does spring understand only js and not ts ( java script and not type script)?

3) Do I need a maven plugin for typescript and if so how to tell maven bundle the compiled js with the spring war while excluding the rest directories and files

4) How to include the testing unit / e2e with maven build

I searched for step by step guide for ANgular 2 and spring boot but could not find one. It would be helpful to many if some guide like this exist.

Many thanks for your support guys.

答: I shared a project on github that integrates Angular 2 With spring boot. Just need to follow the step on readme or check commit history. You can access here Angular 2 with spring boot</p>


问:
Super() in abstract class
I have the following program :

```<code>public abstract class geometricFigure {
    private int dim1, dim2;

    public geometricFigure(int dim1, int dim2) {
        super();
        this.dim1 = dim1;
        this.dim2 = dim2;
    }

    public geometricFigure() {
        this.dim1 = 0;
        this.dim2 = 0;
    }
}
</code>```

I am struggling to understand, what does the super() method in the parameterized constructor do. I can see here that this abstract class doesn't extend any class and I have difficulties into understanding what super() method from what superclass does it call.

Btw. This class is extended by two other classes called Echilateral Triangle and Circle.

```<code>public class echilateralTriangle extends geometricFigure {
    public echilateralTriangle() {
        super(1, 1);
    }

    public echilateralTriangle(int dim1, int dim2) {
        super(dim1, dim2);
    }
}
</code>```

Circle class:

```<code>public class Circle extends geometricFigure {
    public Circle() {
        super(1, 1);
    }

    public Circle(int dim1, int dim2) {
        super(dim1, dim2);
    }
}
</code>```

答: super calls the parent class' constructor with the arguments passed to it. In this case, super() calls the parent's no-arg constructor. A class that doesn't explicitly declare its parent implicitly extends Object, so here super() will call Object's default constructor, which it would also do implicitly had the call been omitted. So it's not wrong, just redundant.

Title: Super() in abstract class

Body:
I have the following program :

public abstract class geometricFigure {
    private int dim1, dim2;

    public geometricFigure(int dim1, int dim2) {
        super();
        this.dim1 = dim1;
        this.dim2 = dim2;
    }

    public geometricFigure() {
        this.dim1 = 0;
        this.dim2 = 0;
    }
}

I am struggling to understand, what does the super() method in the parameterized constructor do. I can see here that this abstract class doesn't extend any class and I have difficulties into understanding what super() method from what superclass does it call.

Btw. This class is extended by two other classes called Echilateral Triangle and Circle.

public class echilateralTriangle extends geometricFigure {
    public echilateralTriangle() {
        super(1, 1);
    }

    public echilateralTriangle(int dim1, int dim2) {
        super(dim1, dim2);
    }
}

Circle class:

public class Circle extends geometricFigure {
    public Circle() {
        super(1, 1);
    }

    public Circle(int dim1, int dim2) {
        super(dim1, dim2);
    }
}


问:
Using failFast with closure map breaks "parallel" step
Not sure if it's my limited knowledge of Groovy or a quirk in Pipeline parallel step. I can't make it accept failFast if I use map instead of passing each closure individually:

```<code>def map = [:]
map['spam'] = {
    node {
        echo 'spam'
    }
}
map['eggs'] = {
    node {
        echo 'eggs'
    }
}
parallel map // Works.
parallel spam: map['spam'], eggs: map['eggs'], failFast: true // Works.
parallel map, failFast: true // Fails with exception.
</code>```

The exception with failFast is:

```<code>java.lang.IllegalArgumentException: Expected named arguments but got [{failFast=true}, {spam=org.jenkinsci.plugins.workflow.cps.CpsClosure2@51a382ad, eggs=org.jenkinsci.plugins.workflow.cps.CpsClosure2@718cb50d}]
    at org.jenkinsci.plugins.workflow.cps.DSL.parseArgs(DSL.java:276)
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:111)
</code>```

答:
It helps a little if you add the optional syntax in. The second option is passing a new Map while the third option is passing your original Map and an additional named parameter. Honestly I'm not sure what it thinks is going on.

```<code>parallel(map)
parallel([
    spam: map['spam'],
    eggs: map['eggs'],
    failFast: true
])
parallel map, failFast: true
</code>```

In any case I think the simplest thing would be this:

```<code>def map = [
    spam: {
        node {
            echo 'spam'
        }
    },
    eggs: {
        node {
            echo 'eggs'
        }
    },
    failFast: true
]
parallel map
</code>```

or...

```<code>parallel ([
    spam: {
        node {
            echo 'spam'
        }
    },
    eggs: {
        node {
            echo 'eggs'
        }
    },
    failFast: true
])
</code>```

Body:
Not sure if it's my limited knowledge of Groovy or a quirk in Pipeline parallel step. I can't make it accept failFast if I use map instead of passing each closure individually:

def map = [:]
map['spam'] = {
    node {
        echo 'spam'
    }
}
map['eggs'] = {
    node {
        echo 'eggs'
    }
}
parallel map // Works.
parallel spam: map['spam'], eggs: map['eggs'], failFast: true // Works.
parallel map, failFast: true // Fails with exception.

The exception with failFast is:

java.lang.IllegalArgumentException: Expected named arguments but got [{failFast=true}, {spam=org.jenkinsci.plugins.workflow.cps.CpsClosure2@51a382ad, eggs=org.jenkinsci.plugins.workflow.cps.CpsClosure2@718cb50d}]
    at org.jenkinsci.plugins.workflow.cps.DSL.parseArgs(DSL.java:276)
    at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:111)

Body:
It helps a little if you add the optional syntax in. The second option is passing a new Map while the third option is passing your original Map and an additional named parameter. Honestly I'm not sure what it thinks is going on.

parallel(map)
parallel([
    spam: map['spam'],
    eggs: map['eggs'],
    failFast: true
])
parallel map, failFast: true

In any case I think the simplest thing would be this:

def map = [
    spam: {
        node {
            echo 'spam'
        }
    },
    eggs: {
        node {
            echo 'eggs'
        }
    },
    failFast: true
]
parallel map

or...

parallel ([
    spam: {
        node {
            echo 'spam'
        }
    },
    eggs: {
        node {
            echo 'eggs'
        }
    },
    failFast: true
])


答: Hmm... I wonder what would happen of you altered the line that reads if(a.compareTo(b) > 0)?

Title: Java array sorting in reverse! Need to reverse the reverse


问:
Pass bash loop variable through pipe to AWK
I have the following bash script:

```<code>for file in *.gz; do
    zgrep @ $file | awk '{split($0,a,":");
    print $file"\t@RID\tT1:"a[1]"\tT2:"a[2]"\tT3:"a[3]}' > out.csv;
done
</code>```

I want to create an output csv/tbi file that has the file name placed into the first column of the zgrep output piped through awk.

The error is:

"awk: illegal field $(), name "file"  input record number 1, file

  source line number 2"

I am expecting to get this:

Column headers:
(these don't need to be in the actual output file I just put it here for clarity's sake since I can't find how to separate with tabs on stackoverflow):

filename | RID | T1 | T2 | T3

output row:

FILENAME.gz @RID    T1:text1      T2:text2  T3:text3

... more rows here...

If I remove the $file in the print command it will work (needless to say it omits the filename).  I have tried the following option inside the awk call and outside but to no avail:

```<code>-v i=$file
</code>```

Any suggestions or workarounds would be appreciated.

答:
```<code>for file in *.gz; do
    zgrep @ "$file" |
    awk -F':' -v OFS='\t' -v file="$file" '{
        print file, "@RID", "T1:" $1, "T2:" $2, "T3:" $3
    }'
done > out.csv
</code>```

Body:
I have the following bash script:

for file in *.gz; do
    zgrep @ $file | awk '{split($0,a,":");
    print $file"\t@RID\tT1:"a[1]"\tT2:"a[2]"\tT3:"a[3]}' > out.csv;
done

I want to create an output csv/tbi file that has the file name placed into the first column of the zgrep output piped through awk.

The error is:

"awk: illegal field $(), name "file"  input record number 1, file

  source line number 2"

I am expecting to get this:

Column headers:
(these don't need to be in the actual output file I just put it here for clarity's sake since I can't find how to separate with tabs on stackoverflow):

filename | RID | T1 | T2 | T3

output row:

FILENAME.gz @RID    T1:text1      T2:text2  T3:text3

... more rows here...

If I remove the $file in the print command it will work (needless to say it omits the filename).  I have tried the following option inside the awk call and outside but to no avail:

-v i=$file

Any suggestions or workarounds would be appreciated.


问:
Using cout with basic_string<unsigned char>
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

```<code>#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}
</code>```

This doesn't compile with

```<code>error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')
</code>```

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?

答:
The global object std::cout is of type std::ostream which is an alias for std::basic_ostream<char>. The relevant operator is std::basic_string::operator<< which requires that the std::basic_string<CharT> and the std::basic_ostream<CharT> share the same type CharT. In your example, you are using std::basic_string<unsigned char> and std::basic_ostream<char> which is not supported, since unsigned char and char are distinct types. Note that signed char and unsigned char are always distinct from char.

char - type for character representation which can be most efficiently processed on the target system (has the same representation and alignment as either signed char or unsigned char, but is always a distinct type). [...] Link.

Body:
cout works with string (a.k.a. basic_string<char>) and all number types (int, char, unsigned char, double, etc.). However it cannot handle basic_string<unsigned char>.

#include <iostream>
#include <string>
int main()
{
    std::basic_string<unsigned char> zzz(3, 'z');
    std::cout << zzz << std::endl;
    return 0;
}

This doesn't compile with

error: invalid operands to binary expression ('ostream' (aka 'basic_ostream<char>') and 'std::basic_string<unsigned char>')

I would expect this to behave the same way as string. Is there a reason why ostream doesn't handle std::basic_string<unsigned char>?