问:
Spark Yarn Memory configuration
I have a spark application that keeps failing on error:

"Diagnostics: Container [pid=29328,containerID=container_e42_1512395822750_0026_02_000001] is running beyond physical memory limits. Current usage: 1.5 GB of 1.5 GB physical memory used; 2.3 GB of 3.1 GB virtual memory used. Killing container."

I saw lots of different parameters that was suggested to change to increase the physical memory. Can I please have the some explanation for the following parameters?

mapreduce.map.memory.mb (currently set to 0 so suppose to take the default which is 1GB so why we see it as 1.5 GB, changing it also dint effect the number)

mapreduce.reduce.memory.mb (currently set to 0 so suppose to take the default which is 1GB so why we see it as 1.5 GB, changing it also dint effect the number)

mapreduce.map.java.opts/mapreduce.reduce.java.opts set to 80% form the previous number

yarn.scheduler.minimum-allocation-mb=1GB (when changing this then I see the effect on the max physical memory, but for the value 1 GB it still 1.5G)

yarn.app.mapreduce.am.resource.mb/spark.yarn.executor.memoryOverhead can't find at all in configuration.

We are defining YARN (running with yarn-cluster deployment mode) using cloudera CDH 5.12.1.

答:
```<code>spark.driver.memory
spark.executor.memory
</code>```

These control the base amount of memory spark will try to allocate for it's driver and for all the executors.  These are probably the ones you want to increase if you are running out of memory.

```<code>// options before Spark 2.3.0
spark.yarn.driver.memoryOverhead
spark.yarn.executor.memoryOverhead

// options after Spark 2.3.0
spark.driver.memoryOverhead
spark.executor.memoryOverhead
</code>```

This value is an additional amount of memory to request when you are running Spark on yarn.  It is intended to account extra RAM needed for the yarn container that is hosting your Spark Executors.

```<code>yarn.scheduler.minimum-allocation-mb
yarn.scheduler.maximum-allocation-mb
</code>```

When Spark goes to ask Yarn to reserve a block of RAM for an executor, it will ask a value of the base memory plus the overhead memory.  However, Yarn may not give it back one of exactly that size.  These parameters control the smallest container size and the largest container size that YARN will grant.  If you are only using the cluster for one job, I find it easiest to set these to very small and very large values and then using the spark memory settings mentions above to set the true container size.

```<code>mapreduce.map.memory.mb
mapreduce.map.memory.mb
mapreduce.map.java.opts/mapreduce.reduce.java.opts
</code>```

I don't think these have any bearing on your Spark/Yarn job.

ContentLicense: CC BY-SA 4.0

Title: Spark Yarn Memory configuration

Body:
spark.driver.memory
spark.executor.memory

These control the base amount of memory spark will try to allocate for it's driver and for all the executors.  These are probably the ones you want to increase if you are running out of memory.

// options before Spark 2.3.0
spark.yarn.driver.memoryOverhead
spark.yarn.executor.memoryOverhead

// options after Spark 2.3.0
spark.driver.memoryOverhead
spark.executor.memoryOverhead

This value is an additional amount of memory to request when you are running Spark on yarn.  It is intended to account extra RAM needed for the yarn container that is hosting your Spark Executors.

yarn.scheduler.minimum-allocation-mb
yarn.scheduler.maximum-allocation-mb

When Spark goes to ask Yarn to reserve a block of RAM for an executor, it will ask a value of the base memory plus the overhead memory.  However, Yarn may not give it back one of exactly that size.  These parameters control the smallest container size and the largest container size that YARN will grant.  If you are only using the cluster for one job, I find it easiest to set these to very small and very large values and then using the spark memory settings mentions above to set the true container size.

mapreduce.map.memory.mb
mapreduce.map.memory.mb
mapreduce.map.java.opts/mapreduce.reduce.java.opts

I don't think these have any bearing on your Spark/Yarn job.


来源: stackexchange

问:
Vectorise a code to transform a vector into a matrix
I have a vector A of dimension Nx1 in MATLAB, e.g.

```<code>N = 5;
A = [1
     2
     3
     4
     5];
</code>```

I want to construct a matrix B of dimension (N-1) x N such that:

for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.

In the example above,

```<code>B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]
</code>```

This code does what I want:

```<code> B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end
</code>```

But I want to vectorise it. Any help?

答:
Here's a simple option:</p>

```<code>[r, ~] = find(~eye(N));
B = reshape(A(r), N-1, N)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a vector A of dimension Nx1 in MATLAB, e.g.

N = 5;
A = [1
     2
     3
     4
     5];

I want to construct a matrix B of dimension (N-1) x N such that:

for i=1,...,N, B(:,i) contains the rows 1,2,...,i-1,i+1,...,N of A.

In the example above,

B = [2 1 1 1 1
     3 3 2 2 2
     4 4 4 3 3
     5 5 5 5 4]

This code does what I want:

 B=zeros(N-1,N);
 for i=1:N
     if i>1 && i<N
         B(:,i)=[A(1:i-1); A(i+1:end)];
     elseif i==1
         B(:,i)=A(i+1:end);
     elseif i==N
         B(:,i)=A(1:i-1);
     end
 end

But I want to vectorise it. Any help?

Body:
Here's a simple option:

[r, ~] = find(~eye(N));
B = reshape(A(r), N-1, N)


问:
VBA Error Handling Not working
I am writing a vba program to refresh power queries for a number of reports based on a user saying which reports to refresh via a form with checkboxes.

This part of the code refreshes the power query and I want it to capture the error if the refresh isn't successful. It will update a control table "Not Updated" if it wasn't updated and then I want it to resume next.

For some reason the "On Error Goto Error" isn't triggering the error line. It is still throwing the error and stopping the code run.

Any help would be greatly appreciated!

```<code>For Each cell In
wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
    If cell.Value = True Then
        cell.Offset(, 1).Value = Now()
        cell.Offset(, 2).Value = frmSetting.tbStartDate
        cell.Offset(, 3).Value = frmSetting.tbEnddate

        strCurrWS = cell.Offset(0, -1)
        ThisWorkbook.Sheets(strCurrWS).Activate
        Application.StatusBar = "Updating tab " & strCurrWS

            For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                qt.Refresh BackgroundQuery:=False
            Next qt

            For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                On Error GoTo Error
                lo.QueryTable.Refresh BackgroundQuery:=False
            Next lo
    Else
 Error:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
    cell.Offset(, 6).Value = "Permission Error. Check Credentials"
    Err.Clear
    End If

    End If
Next cell

Set qt = Nothing
Set wks = Nothing
</code>```

答:
I think you want to avoid having the error handling as part of the normal flow.  I'm not sure of the logic you want but if you want to resume back in the For Each lo... loop replaced Resume Top with Resume Next

```<code>Sub a()

    For Each cell In wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
Top:

        If cell.Value = True Then
            cell.Offset(, 1).Value = Now()
            cell.Offset(, 2).Value = frmSetting.tbStartDate
            cell.Offset(, 3).Value = frmSetting.tbEnddate

            strCurrWS = cell.Offset(0, -1)
            ThisWorkbook.Sheets(strCurrWS).Activate
            Application.StatusBar = "Updating tab " & strCurrWS

                For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                    qt.Refresh BackgroundQuery:=False
                Next qt

                For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                    On Error GoTo ErrorCatch
                    lo.QueryTable.Refresh BackgroundQuery:=False
                Next lo
        Else
            cell.Offset(, 4).Value = "Not Updated"
        End If
    Next cell

    Set qt = Nothing
    Set wks = Nothing
    Exit Sub
ErrorCatch:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
        cell.Offset(, 6).Value = "Permission Error. Check Credentials"
    End If
    Resume Top
End Sub
</code>```

Title: VBA Error Handling Not working

Body:
I am writing a vba program to refresh power queries for a number of reports based on a user saying which reports to refresh via a form with checkboxes.

This part of the code refreshes the power query and I want it to capture the error if the refresh isn't successful. It will update a control table "Not Updated" if it wasn't updated and then I want it to resume next.

For some reason the "On Error Goto Error" isn't triggering the error line. It is still throwing the error and stopping the code run.

Any help would be greatly appreciated!

For Each cell In
wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
    If cell.Value = True Then
        cell.Offset(, 1).Value = Now()
        cell.Offset(, 2).Value = frmSetting.tbStartDate
        cell.Offset(, 3).Value = frmSetting.tbEnddate

        strCurrWS = cell.Offset(0, -1)
        ThisWorkbook.Sheets(strCurrWS).Activate
        Application.StatusBar = "Updating tab " & strCurrWS

            For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                qt.Refresh BackgroundQuery:=False
            Next qt

            For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                On Error GoTo Error
                lo.QueryTable.Refresh BackgroundQuery:=False
            Next lo
    Else
 Error:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
    cell.Offset(, 6).Value = "Permission Error. Check Credentials"
    Err.Clear
    End If

    End If
Next cell

Set qt = Nothing
Set wks = Nothing

Body:
I think you want to avoid having the error handling as part of the normal flow.  I'm not sure of the logic you want but if you want to resume back in the For Each lo... loop replaced Resume Top with Resume Next

Sub a()

    For Each cell In wsConfig.ListObjects("tblReportstoRun").ListColumns(2).DataBodyRange
Top:

        If cell.Value = True Then
            cell.Offset(, 1).Value = Now()
            cell.Offset(, 2).Value = frmSetting.tbStartDate
            cell.Offset(, 3).Value = frmSetting.tbEnddate

            strCurrWS = cell.Offset(0, -1)
            ThisWorkbook.Sheets(strCurrWS).Activate
            Application.StatusBar = "Updating tab " & strCurrWS

                For Each qt In ThisWorkbook.Sheets(strCurrWS).QueryTables
                    qt.Refresh BackgroundQuery:=False
                Next qt

                For Each lo In ThisWorkbook.Sheets(strCurrWS).ListObjects
                    On Error GoTo ErrorCatch
                    lo.QueryTable.Refresh BackgroundQuery:=False
                Next lo
        Else
            cell.Offset(, 4).Value = "Not Updated"
        End If
    Next cell

    Set qt = Nothing
    Set wks = Nothing
    Exit Sub
ErrorCatch:
    cell.Offset(, 4).Value = "Not Updated"
    If InStr(Err.Description, "Permission Error") Then
        cell.Offset(, 6).Value = "Permission Error. Check Credentials"
    End If
    Resume Top
End Sub


问:
How to make session variables unique per every php-script instance?
Well, let's say I have a php-script, that has some select box, and I want to store the selected value in session array. Till now I assigned the value to my session array using the following construction:

```<code>$_SESSION[SCRIPT_NAME]['filter_data']
</code>```

SCRIPT_NAME is a constant where I put script name, this is to make session variable unique per every php-script. Everything is fine till the moment when user opens the same script in two or more tabs to work simultaneously. In this case variables mixes and things go wrong...

May be you have any ideas how to make session variable absolutely unique per every script instance? Or any advice how to achieve functionality different way?

I now, I can pass my variables in URL, but I don't like this option. I want to use session and I want every script of my web-application remember users' choices during the whole user login session

答:
```<code> <?php
        //Start session
        session_start();
        //Check whether the session variable SESS_MEMBER_ID is present or not
        if (!isset($_SESSION['id']) || ($_SESSION['id'] == '')) {
            header("location: index.php");
            exit();
        }

        $session_id=$_SESSION['id'];
        ?>
</code>```

and file connection

```<code> <?php

 class DbConnector {

 var $theQuery;
 var $link;

 function DbConnector(){

    // Get the main settings from the array we just loaded
    $host = 'localhost';
    $db = '';
    $user = 'root';
    $pass = '';

    // Connect to the database
    $this->link = mysql_connect($host, $user, $pass);
    mysql_select_db($db);
    register_shutdown_function(array(&$this, 'close'));

}

   //*** Function: query, Purpose: Execute a database query ***
function query($query) {

    $this->theQuery = $query;
    return mysql_query($query, $this->link);

}

//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {

    return mysql_fetch_array($result);

}

//*** Function: close, Purpose: Close the connection ***
function close() {

    mysql_close($this->link);

}

}

?>
</code>```

Body:
Well, let's say I have a php-script, that has some select box, and I want to store the selected value in session array. Till now I assigned the value to my session array using the following construction:

$_SESSION[SCRIPT_NAME]['filter_data']

SCRIPT_NAME is a constant where I put script name, this is to make session variable unique per every php-script. Everything is fine till the moment when user opens the same script in two or more tabs to work simultaneously. In this case variables mixes and things go wrong...

May be you have any ideas how to make session variable absolutely unique per every script instance? Or any advice how to achieve functionality different way?

I now, I can pass my variables in URL, but I don't like this option. I want to use session and I want every script of my web-application remember users' choices during the whole user login session

Body:
 <?php
        //Start session
        session_start();
        //Check whether the session variable SESS_MEMBER_ID is present or not
        if (!isset($_SESSION['id']) || ($_SESSION['id'] == '')) {
            header("location: index.php");
            exit();
        }

        $session_id=$_SESSION['id'];
        ?>

and file connection

 <?php

 class DbConnector {

 var $theQuery;
 var $link;

 function DbConnector(){

    // Get the main settings from the array we just loaded
    $host = 'localhost';
    $db = '';
    $user = 'root';
    $pass = '';

    // Connect to the database
    $this->link = mysql_connect($host, $user, $pass);
    mysql_select_db($db);
    register_shutdown_function(array(&$this, 'close'));

}

   //*** Function: query, Purpose: Execute a database query ***
function query($query) {

    $this->theQuery = $query;
    return mysql_query($query, $this->link);

}

//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {

    return mysql_fetch_array($result);

}

//*** Function: close, Purpose: Close the connection ***
function close() {

    mysql_close($this->link);

}

}

?>


问:
Remove box-shadow from Angular Material <mat-chip>

Is there any way to remove the box-shadow from mat-chips in Angular Material?

```<code><mat-chip-list>
    <mat-chip>Papadum</mat-chip>
</mat-chip-list>
</code>```

The chips appear to have a CSS style for the box-shadow, but disabling this style or overriding it doesn't work.

```<code>transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1);
</code>```

I suspect there must be a simple way to disable this shadow, but I can't figure it out.

答:
Adding the following CSS with !important did the trick:</p>

```<code>mat-chip {
    transition: none !important;
    box-shadow: none !important;
}
</code>```

Body:
Is there any way to remove the box-shadow from mat-chips in Angular Material?

<mat-chip-list>
    <mat-chip>Papadum</mat-chip>
</mat-chip-list>

The chips appear to have a CSS style for the box-shadow, but disabling this style or overriding it doesn't work.

transition: box-shadow 280ms cubic-bezier(.4, 0, .2, 1);

I suspect there must be a simple way to disable this shadow, but I can't figure it out.

Body:
Adding the following CSS with !important did the trick:

mat-chip {
    transition: none !important;
    box-shadow: none !important;
}


问:
How to handle synchronous errors with async await?
I've been getting some unhandled rejections in my app, but I was pretty certain that all of my code is correctly wrapped with error handling. After digging around I found that async/await is not behaving as I expected. Basically my async function throws a sync error and that error is then getting treated as an uncaught exception. This happens even when I wrap my code in a try catch explicitly, but not when I await a sync method which throws an error.

So here's my test code:

```<code>function test() {
  async function one() {
    try {
      await three();
    } catch (error) {
      console.log('caught', new Error().stack);
      return error;
    }
  }
  async function three() {
    try {
      throw new Error();
    } catch (e) {
      console.log('caught', new Error().stack);
      return Promise.reject(e);
    }
  }

  one().then(function (result) {
    console.log({result});
  }).catch(error => console.log({ error }));
}

process.on('unhandledRejection', (e) => console.log('not caught', e.stack));

test();
</code>```

Here's the output I see in the console:

```<code>not caught Error
    at three$ (imports/access-control/execute-handler.js:25:13)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:299:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:117:21)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at invoke (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:155:20)
    at /Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:198:11
    at callInvokeWithMethodAndArg (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:197:16)
    at AsyncIterator.enqueue (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:220:13)
    at AsyncIterator.prototype.(anonymous function) [as next] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:117:21)
caught Error
    at one$ (imports/access-control/execute-handler.js:11:29)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:299:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as throw] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:117:21)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at invoke (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:155:20)
    at /Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:167:13
    at /Users/joshuaohlman/.meteor/packages/promise/.0.8.9.ghfed++os+web.browser+web.cordova/npm/node_modules/meteor-promise/fiber_pool.js:32:39
{ result: [Error] }
(STDERR) [Error] [Function]
</code>```

So my question is, is this expected behavior?

If so, how can I nicely wrap my async functions so that they catch both synchronous and asynchronous errors in a way that allows me to handle them my self or pass them on as rejections.

I'm using babel to compile my code (this particular bit of code runs in node though I also run my code in the browser).

If it's interesting, here's the compiled version of my code:

```<code>                                                                                //
function test() {                                                                                // 6
  function one() {                                                                                // 7
    return _regenerator2.default.async(function () {                                                                   // 7
      function one$(_context) {                                                                                // 7
        while (1) {                                                                                // 7
          switch (_context.prev = _context.next) {                                                                     // 7
            case 0:                                                                                // 7
              _context.prev = 0;                                                                                // 7
              _context.next = 3;                                                                                // 7
              return _regenerator2.default.awrap(three());                                                             // 7
                                                                                //
            case 3:                                                                                // 7
              _context.next = 9;                                                                                // 7
              break;                                                                                // 7
                                                                                //
            case 5:                                                                                // 7
              _context.prev = 5;                                                                                // 7
              _context.t0 = _context["catch"](0);                                                                      // 7
              console.log('caught', new Error().stack);                                                                // 11
              return _context.abrupt("return", _context.t0);                                                           // 7
                                                                                //
            case 9:                                                                                // 7
            case "end":                                                                                // 7
              return _context.stop();                                                                                // 7
          }                                                                                // 7
        }                                                                                // 7
      }                                                                                // 7
                                                                                //
      return one$;                                                                                // 7
    }(), null, this, [[0, 5]]);                                                                                // 7
  }                                                                                // 7
                                                                                //
  function two() {                                                                                // 15
    return _regenerator2.default.async(function () {                                                                   // 15
      function two$(_context2) {                                                                                // 15
        while (1) {                                                                                // 15
          switch (_context2.prev = _context2.next) {                                                                   // 15
            case 0:                                                                                // 15
              _context2.prev = 0;                                                                                // 15
              _context2.next = 3;                                                                                // 15
              return _regenerator2.default.awrap(three());                                                             // 15
                                                                                //
            case 3:                                                                                // 15
              _context2.next = 9;                                                                                // 15
              break;                                                                                // 15
                                                                                //
            case 5:                                                                                // 15
              _context2.prev = 5;                                                                                // 15
              _context2.t0 = _context2["catch"](0);                                                                    // 15
              console.log('caught', new Error().stack);                                                                // 19
              return _context2.abrupt("return", _context2.t0);                                                         // 15
                                                                                //
            case 9:                                                                                // 15
            case "end":                                                                                // 15
              return _context2.stop();                                                                                // 15
          }                                                                                // 15
        }                                                                                // 15
      }                                                                                // 15
                                                                                //
      return two$;                                                                                // 15
    }(), null, this, [[0, 5]]);                                                                                // 15
  }                                                                                // 15
                                                                                //
  function three() {                                                                                // 23
    return _regenerator2.default.async(function () {                                                                   // 23
      function three$(_context3) {                                                                                // 23
        while (1) {                                                                                // 23
          switch (_context3.prev = _context3.next) {                                                                   // 23
            case 0:                                                                                // 23
              _context3.prev = 0;                                                                                // 23
              throw new Error();                                                                                // 23
                                                                                //
            case 4:                                                                                // 23
              _context3.prev = 4;                                                                                // 23
              _context3.t0 = _context3["catch"](0);                                                                    // 23
              console.log('caught', new Error().stack);                                                                // 27
              return _context3.abrupt("return", Promise.reject(_context3.t0));                                         // 23
                                                                                //
            case 8:                                                                                // 23
            case "end":                                                                                // 23
              return _context3.stop();                                                                                // 23
          }                                                                                // 23
        }                                                                                // 23
      }                                                                                // 23
                                                                                //
      return three$;                                                                                // 23
    }(), null, this, [[0, 4]]);                                                                                // 23
  }                                                                                // 23
                                                                                //
  one().then(function (result) {                                                                                // 32
    console.log({                                                                                // 33
      result: result                                                                                // 33
    });                                                                                // 33
  }).catch(function (error) {                                                                                // 34
    return console.log({                                                                                // 34
      error: error                                                                                // 34
    });                                                                                // 34
  });                                                                                // 34
}                                                                                // 35
                                                                                //
process.on('unhandledRejection', function (e) {                                                                        // 37
  return console.log('not caught', e.stack);                                                                           // 37
});                                                                                // 37
test();
</code>```

Update

I can't reproduce this issue using the latest version of regenerator so assuming this is a bug in my version of regenerator or babel or something related to my environment.

Update

Lance Whatley points out that it's incorrect to return a promise from an async function, I'm not sure if that's the case, however the behavior that I'm definitely not expecting is that the console log statement inside of the three() catch clause is never called.

答: Turns out this was a bug and updating my package versions fixed it. I'll leave this question an answer up since it took me an amazingly long time to discover the issue and fix it and there's a lot of confusion surrounding the correct behavior of async/await with try/catch blocks.</p>

Body:
I've been getting some unhandled rejections in my app, but I was pretty certain that all of my code is correctly wrapped with error handling. After digging around I found that async/await is not behaving as I expected. Basically my async function throws a sync error and that error is then getting treated as an uncaught exception. This happens even when I wrap my code in a try catch explicitly, but not when I await a sync method which throws an error.

So here's my test code:

function test() {
  async function one() {
    try {
      await three();
    } catch (error) {
      console.log('caught', new Error().stack);
      return error;
    }
  }
  async function three() {
    try {
      throw new Error();
    } catch (e) {
      console.log('caught', new Error().stack);
      return Promise.reject(e);
    }
  }

  one().then(function (result) {
    console.log({result});
  }).catch(error => console.log({ error }));
}

process.on('unhandledRejection', (e) => console.log('not caught', e.stack));

test();

Here's the output I see in the console:

not caught Error
    at three$ (imports/access-control/execute-handler.js:25:13)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:299:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as next] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:117:21)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at invoke (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:155:20)
    at /Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:198:11
    at callInvokeWithMethodAndArg (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:197:16)
    at AsyncIterator.enqueue (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:220:13)
    at AsyncIterator.prototype.(anonymous function) [as next] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:117:21)
caught Error
    at one$ (imports/access-control/execute-handler.js:11:29)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at GeneratorFunctionPrototype.invoke [as _invoke] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:299:22)
    at GeneratorFunctionPrototype.prototype.(anonymous function) [as throw] (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:117:21)
    at tryCatch (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:65:40)
    at invoke (/Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:155:20)
    at /Users/joshuaohlman/Development/Xolvio/xspecs/modules/web-app/node_modules/regenerator-runtime/runtime.js:167:13
    at /Users/joshuaohlman/.meteor/packages/promise/.0.8.9.ghfed++os+web.browser+web.cordova/npm/node_modules/meteor-promise/fiber_pool.js:32:39
{ result: [Error] }
(STDERR) [Error] [Function]

So my question is, is this expected behavior?

If so, how can I nicely wrap my async functions so that they catch both synchronous and asynchronous errors in a way that allows me to handle them my self or pass them on as rejections.

I'm using babel to compile my code (this particular bit of code runs in node though I also run my code in the browser).

If it's interesting, here's the compiled version of my code:

                                                                                //
function test() {                                                                                // 6
  function one() {                                                                                // 7
    return _regenerator2.default.async(function () {                                                                   // 7
      function one$(_context) {                                                                                // 7
        while (1) {                                                                                // 7
          switch (_context.prev = _context.next) {                                                                     // 7
            case 0:                                                                                // 7
              _context.prev = 0;                                                                                // 7
              _context.next = 3;                                                                                // 7
              return _regenerator2.default.awrap(three());                                                             // 7
                                                                                //
            case 3:                                                                                // 7
              _context.next = 9;                                                                                // 7
              break;                                                                                // 7
                                                                                //
            case 5:                                                                                // 7
              _context.prev = 5;                                                                                // 7
              _context.t0 = _context["catch"](0);                                                                      // 7
              console.log('caught', new Error().stack);                                                                // 11
              return _context.abrupt("return", _context.t0);                                                           // 7
                                                                                //
            case 9:                                                                                // 7
            case "end":                                                                                // 7
              return _context.stop();                                                                                // 7
          }                                                                                // 7
        }                                                                                // 7
      }                                                                                // 7
                                                                                //
      return one$;                                                                                // 7
    }(), null, this, [[0, 5]]);                                                                                // 7
  }                                                                                // 7
                                                                                //
  function two() {                                                                                // 15
    return _regenerator2.default.async(function () {                                                                   // 15
      function two$(_context2) {                                                                                // 15
        while (1) {                                                                                // 15
          switch (_context2.prev = _context2.next) {                                                                   // 15
            case 0:                                                                                // 15
              _context2.prev = 0;                                                                                // 15
              _context2.next = 3;                                                                                // 15
              return _regenerator2.default.awrap(three());                                                             // 15
                                                                                //
            case 3:                                                                                // 15
              _context2.next = 9;                                                                                // 15
              break;                                                                                // 15
                                                                                //
            case 5:                                                                                // 15
              _context2.prev = 5;                                                                                // 15
              _context2.t0 = _context2["catch"](0);                                                                    // 15
              console.log('caught', new Error().stack);                                                                // 19
              return _context2.abrupt("return", _context2.t0);                                                         // 15
                                                                                //
            case 9:                                                                                // 15
            case "end":                                                                                // 15
              return _context2.stop();                                                                                // 15
          }                                                                                // 15
        }                                                                                // 15
      }                                                                                // 15
                                                                                //
      return two$;                                                                                // 15
    }(), null, this, [[0, 5]]);                                                                                // 15
  }                                                                                // 15
                                                                                //
  function three() {                                                                                // 23
    return _regenerator2.default.async(function () {                                                                   // 23
      function three$(_context3) {                                                                                // 23
        while (1) {                                                                                // 23
          switch (_context3.prev = _context3.next) {                                                                   // 23
            case 0:                                                                                // 23
              _context3.prev = 0;                                                                                // 23
              throw new Error();                                                                                // 23
                                                                                //
            case 4:                                                                                // 23
              _context3.prev = 4;                                                                                // 23
              _context3.t0 = _context3["catch"](0);                                                                    // 23
              console.log('caught', new Error().stack);                                                                // 27
              return _context3.abrupt("return", Promise.reject(_context3.t0));                                         // 23
                                                                                //
            case 8:                                                                                // 23
            case "end":                                                                                // 23
              return _context3.stop();                                                                                // 23
          }                                                                                // 23
        }                                                                                // 23
      }                                                                                // 23
                                                                                //
      return three$;                                                                                // 23
    }(), null, this, [[0, 4]]);                                                                                // 23
  }                                                                                // 23
                                                                                //
  one().then(function (result) {                                                                                // 32
    console.log({                                                                                // 33
      result: result                                                                                // 33
    });                                                                                // 33
  }).catch(function (error) {                                                                                // 34
    return console.log({                                                                                // 34
      error: error                                                                                // 34
    });                                                                                // 34
  });                                                                                // 34
}                                                                                // 35
                                                                                //
process.on('unhandledRejection', function (e) {                                                                        // 37
  return console.log('not caught', e.stack);                                                                           // 37
});                                                                                // 37
test();

Update

I can't reproduce this issue using the latest version of regenerator so assuming this is a bug in my version of regenerator or babel or something related to my environment.

Update

Lance Whatley points out that it's incorrect to return a promise from an async function, I'm not sure if that's the case, however the behavior that I'm definitely not expecting is that the console log statement inside of the three() catch clause is never called.


问:
cant update data using ionic and firebase on childe node structure
I have problem for updating data with ionic firebase using this code,this code just make it a new data not rewrite the previous data  .
here is the code :

```<code>updateLaporan()
      {
        this.id =this.fire.auth.currentUser.uid;
        this.db.object('/laporan/'+ this.id+ this.uid).set({
          porsiKarbohidrat : this.porsiKarbohidrat.value,
          porsiProteinHewani : this.porsiProteinHewani.value,
          porsiProteinNabati : this.porsiProteinNabati.value,
          porsiLemak : this.porsiLemak.value,

         })

         this.alert("Sukses")
      }
</code>```

this is the capture of my database:
firebase structure
this is what will be happen if i use that code
This is what will be happen if i use the code

答:
You need a / in between your id's to go deeper

```<code>this.db.object('/laporan/'+ this.id+'/'+ this.uid).update()
</code>```

use .update instead .set or everything under current node will be rewrite.

Body:
I have problem for updating data with ionic firebase using this code,this code just make it a new data not rewrite the previous data  .
here is the code :

updateLaporan()
      {
        this.id =this.fire.auth.currentUser.uid;
        this.db.object('/laporan/'+ this.id+ this.uid).set({
          porsiKarbohidrat : this.porsiKarbohidrat.value,
          porsiProteinHewani : this.porsiProteinHewani.value,
          porsiProteinNabati : this.porsiProteinNabati.value,
          porsiLemak : this.porsiLemak.value,

         })

         this.alert("Sukses")
      }

this is the capture of my database:
firebase structure
this is what will be happen if i use that code
This is what will be happen if i use the code

Body:
You need a / in between your id's to go deeper

this.db.object('/laporan/'+ this.id+'/'+ this.uid).update()

use .update instead .set or everything under current node will be rewrite.


问:
Trying to get a Java function to return an array based on a string parameter passed to it
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

```<code>String[]names = initial(department)
</code>```

Departments is the name of the department being passed to the function. In the function I have:

```<code>public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }
</code>```

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

答:
I would recommend this little change, to make the code more readable and not abuse the return:</p>

```<code>public static String[] initial (String responsibleDepartment) {
    String[] names = null;

    if (responsibleDepartment.equals("Accounts Receivable")) {
        names = new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
     }

    if (responsibleDepartment.equals("Customer Service")) {
        names = new String[] {"Mary Wexler", "Turd Ferguson"};
     }

    return names;
}
</code>```

Body:
Here's what I am trying to do; I am trying to write a small program that uses a function to get an array containing the members of a department based on the department selected. There are about 40 departments, and each department has 1 to 4 members. So this what I did, but I can't seem to resolve to a variable:

From main:

String[]names = initial(department)

Departments is the name of the department being passed to the function. In the function I have:

public static String[] initial (String responsibleDepartment) {

    if (responsibleDepartment.equals("Accounts Receivable")) {
        String[] assignInitial = {"Mike Davis", "Ben Jones", "Ann Smith"}
     }

    if (responsibleDepartment.equals("Customer Service")) {
        String[] assignInitial = {"Mary Wexler", "Turd Ferguson"}
     }

   // and 38 more if statements with the rest of the departments. Finally I have:
        return assignInitial;
        }

So the way it stands, "assignInitial cannot be resolved to a variable" (that's what it says by the return statement.) If I try to initialize the variable before the first "if" statement, and then remove the initialization of String[] next to the assignInitial in the first "if" statement, then it says "Array constants can only be used in initializers." I am sure there is a better way to do this, but I can't seem to make any headway with what I am found online. Any takers?

Thank you much!
-The Munch

Body:
I would recommend this little change, to make the code more readable and not abuse the return:

public static String[] initial (String responsibleDepartment) {
    String[] names = null;

    if (responsibleDepartment.equals("Accounts Receivable")) {
        names = new String[] {"Mike Davis", "Ben Jones", "Ann Smith"};
     }

    if (responsibleDepartment.equals("Customer Service")) {
        names = new String[] {"Mary Wexler", "Turd Ferguson"};
     }

    return names;
}


问:
Is it bad practice to declare the AppDelegate class as 'final' in swift?
Right now, I'm trying to use a class from Git called Insomnia to prevent the device from locking while it is charging. The project is here if you're curious. For the example code, it has me doing this:

```<code>final class AppDelegate: UIResponder, UIApplicationDelegate {
      private let insomnia = Insomnia(mode: .whenCharging)
      //app delegate code
 }
</code>```

As you can see, it has you declare the AppDelegate as final so that the insomnia variable isn't deallocated, which would stop it from working. However, I wasn't sure, is this bad practice to declare my AppDelegate as final? Or will this cause issues for my app? If it is bad practice, is there a better way of making sure insomnia isn't deallocated?

答:
You say:

As you can see, it has you declare the AppDelegate as final so that the insomnia variable isn't deallocated ...

That’s not what final does. It merely says that the class cannot be subclassed (which is not likely to ever be relevant in the case of an app delegate). The final keyword also permits some optimizations (where if you had code calling any of these methods, it could use static dispatch instead of dynamic dispatch) that are unlikely to have any observable effect in this scenario.

Bottom line, you do not have to use final in this context.

"Best practice" would be to use final where you need to, namely where the class really cannot or should not be subclassed or where you really need the performance difference that static dispatch offers.

In answer to your question whether this is an acceptable place to declare insomnia, yes it is (but no final needed). The AppDelegate is not released while the app is running and it's where we generally put "app lifecycle" related code.

Body:
Right now, I'm trying to use a class from Git called Insomnia to prevent the device from locking while it is charging. The project is here if you're curious. For the example code, it has me doing this:

final class AppDelegate: UIResponder, UIApplicationDelegate {
      private let insomnia = Insomnia(mode: .whenCharging)
      //app delegate code
 }

As you can see, it has you declare the AppDelegate as final so that the insomnia variable isn't deallocated, which would stop it from working. However, I wasn't sure, is this bad practice to declare my AppDelegate as final? Or will this cause issues for my app? If it is bad practice, is there a better way of making sure insomnia isn't deallocated?


问:
How do i reverse each character in a string?
```<code>class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}
</code>```

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

答:
Use a StringBuilder to reverse each word in your String : </p>

```<code> String input = "Let's take LeetCode contest";

    String[] split = input.split(" +");
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < split.length; i++) {

        output.append(new StringBuilder(split[i]).reverse());
        if(i<input.length()-1)
        output.append(" ");
    }

    System.out.println(output);
</code>```

Body:
class Solution {
public String reverseWords(String s) {
    int count = 0;
    int current = 0;
    StringBuilder build = new StringBuilder();
    for(int i = 0; i< s.length(); i++){
        count++;
        current = count;
        if(s.charAt(i) == ' '){
            while(current > 0){
                build.append(s.charAt(current - 1));
                current--;
            }
            build.append(s.charAt(i));
        }

    }
    return build.toString();
}
}

I am having trouble understanding why this doesn't work. I went through the
entire code a couple of times but there seems to be an issue.

Input :          "Let's take LeetCode contest"
my answer:       " s'teL  ekat s'teL  edoCteeL ekat s'teL "
correct answer:  "s'teL ekat edoCteeL tsetnoc"
whats going on?

Body:
Use a StringBuilder to reverse each word in your String :

 String input = "Let's take LeetCode contest";

    String[] split = input.split(" +");
    StringBuilder output = new StringBuilder();
    for (int i = 0; i < split.length; i++) {

        output.append(new StringBuilder(split[i]).reverse());
        if(i<input.length()-1)
        output.append(" ");
    }

    System.out.println(output);


问:
Cocoa : Multiline NSTextFieldCell in a NSOutlineView
I am developing a Cocoa application.

I have a NSOutlineView displaying custom cells ( cells inherits from NSTextFieldCell). The problem I am facing to is that the cell text is only displayed on one line... how can I have a multiline textField ???

Thanks for reading ;)

答:
Configure your table column's dataCell to wrap instead of scroll with -[NSCell setWraps:]

Implement -[NSObject outlineView: heightOfRowByItem:] in your outline view delegate.

Use -[NSCell cellSizeForBounds:] to find the height of the cell for a specific width. For cellSizeForBounds:, you can pass a really tall rectangle that's the width of your column, and it will return a smaller rectangle that is the right height for the text to fit in that width.

ContentLicense: CC BY-SA 2.5


问:
Query with GROUP BY and ORDER BY not working when multiple columns in SELECT are chosen
I'm updating an old website and one of the queries isn't working anymore:

```<code>SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

```<code>SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2
</code>```

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

```<code>SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

```<code>SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
</code>```

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

```<code>Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by
</code>```

答:
The reason it didn't work is because you need to use one of the selection criteria in the GROUP BY and the ORDER BY. So if you wanted to group by col1, you would need to do this:

```<code>SELECT col1, col2, col3
   FROM tbl
   WHERE
      col1 IS NULL
   GROUP BY col1
   ORDER BY col1
;
</code>```

Without selecting that field, you are basically saying "Hey go get me every phone number in California" Then after you get that you say "Now order them by first name and group them by last name" and DBMS says "but... I don't have any of that"

Body:
I'm updating an old website and one of the queries isn't working anymore:

SELECT * FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

I noticed if I dropped the GROUP BY it works, but the result set doesn't match the original:

SELECT * FROM tbl WHERE col1 IS NULL ORDER BY col2

So I tried reading up on GROUP BY in the docs to see what might be the issue, and it seemed to suggest not using * to select all the fields, but explicitly using the column name so I tried it with just the column that was being ordered and grouped:

SELECT col2 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Which works but after looking through the code the query requires 2 columns in the query so whoever added * was overdoing it, but if I add that column produces an error, similarly adding a third column produces the same error:

SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2
SELECT col1, col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2 ORDER BY col2

Can anyone tell me why this last query doesn't work?  I can't decipher why from the docs, but this is the minimum query required to get the result set I need.

Running the query in Adminer I get this error

Error in query (1055): Expression #2 of SELECT list is not in GROUP BY
clause and contains nonaggregated column 'name.table.column'
which is not functionally dependent on columns in GROUP BY clause; this is
incompatible with sql_mode=only_full_group_by

Body:
The reason it didn't work is because you need to use one of the selection criteria in the GROUP BY and the ORDER BY. So if you wanted to group by col1, you would need to do this:

SELECT col1, col2, col3
   FROM tbl
   WHERE
      col1 IS NULL
   GROUP BY col1
   ORDER BY col1
;

Without selecting that field, you are basically saying "Hey go get me every phone number in California" Then after you get that you say "Now order them by first name and group them by last name" and DBMS says "but... I don't have any of that"


问:
Overridden RabbitSourceConfiguration (app starters) does not work with Spring Cloud Edgware
I'm testing an upgrade of my Spring Cloud DataFlow services from Spring Cloud Dalston.SR4/Spring Boot 1.5.9 to Spring Cloud Edgware/Spring Boot 1.5.9. Some of my services extend source (or sink) components from the app starters. I've found this does not work with Spring Cloud Edgware.

For example, I have overridden org.springframework.cloud.stream.app.rabbit.source.RabbitSourceConfiguration and bound my app to my overridden version. This has previously worked with Spring Cloud versions going back almost a year.

With Edgware, I get the following (whether the app is run standalone or within dataflow):

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field channels in org.springframework.cloud.stream.app.rabbit.source.RabbitSourceConfiguration required a bean of type 'org.springframework.cloud.stream.messaging.Source' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.cloud.stream.messaging.Source' in your configuration.
</code>```

I get the same behaviour with the 1.3.0.RELEASE and 1.2.0.RELEASE of spring-cloud-starter-stream-rabbit.

I override RabbitSourceConfiguration so I can set a header mapper on the AmqpInboundChannelAdapter, and also to perform a connectivity test prior to starting up the container.

My subclass is bound to the Spring Boot application with @EnableBinding(HeaderMapperRabbitSourceConfiguration.class). A cutdown version of my subclass is:

```<code>public class HeaderMapperRabbitSourceConfiguration extends RabbitSourceConfiguration {

    public HeaderMapperRabbitSourceConfiguration(final MyHealthCheck healthCheck,
                                                 final MyAppConfig config) {
        // ...
    }

    @Bean
    @Override
    public AmqpInboundChannelAdapter adapter() {
        final AmqpInboundChannelAdapter adapter = super.adapter();
        adapter.setHeaderMapper(new NotificationHeaderMapper(config));

        return adapter;
    }

    @Bean
    @Override
    public SimpleMessageListenerContainer container() {
        if (config.performConnectivityCheckOnStartup()) {

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Attempting connectivity with ...");
            }
            final Health health = healthCheck.health();
            if (health.getStatus() == Status.DOWN) {
                LOGGER.error("Unable to connect .....");
                throw new UnableToLoginException("Unable to connect ...");
            } else if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Connectivity established with ...");
            }
        }

        return super.container();
    }
}
</code>```

答:
You really should never do stuff like healthCheck.health(); within a @Bean definition. The application context is not yet fully baked or started; it may, or may not, work depending on the order that beans are created.

If you want to prevent the app from starting, add a bean that implements SmartLifecycle, put the bean in a late phase (high value) so it's started after everything else. Then put your code in start(). autStartup must be true.

In this case, it's being run before the stream infrastructure has created the channel.

Some ordering might have changed from the earlier release but, in any case, performing activity like this in a @Bean definition is dangerous.

You just happened to be lucky before.

EDIT

I just noticed your @EnableBinding is wrong; it should be Source.class. I can't see how that would ever have worked - that's what creates the bean for the channels field of type Source.

This works fine for me after updating stream and the binder to 1.3.0.RELEASE...

```<code>@Configuration
public class MySource extends RabbitSourceConfiguration {

    @Bean
    @Override
    public AmqpInboundChannelAdapter adapter() {
        AmqpInboundChannelAdapter adapter = super.adapter();
        adapter.setHeaderMapper(new MyMapper());
        return adapter;
    }

}
</code>```

and

```<code>@SpringBootApplication
@EnableBinding(Source.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
</code>```

If that doesn't work, please edit the question to show your POM.

Body:
I'm testing an upgrade of my Spring Cloud DataFlow services from Spring Cloud Dalston.SR4/Spring Boot 1.5.9 to Spring Cloud Edgware/Spring Boot 1.5.9. Some of my services extend source (or sink) components from the app starters. I've found this does not work with Spring Cloud Edgware.

For example, I have overridden org.springframework.cloud.stream.app.rabbit.source.RabbitSourceConfiguration and bound my app to my overridden version. This has previously worked with Spring Cloud versions going back almost a year.

With Edgware, I get the following (whether the app is run standalone or within dataflow):

***************************
APPLICATION FAILED TO START
***************************

Description:

Field channels in org.springframework.cloud.stream.app.rabbit.source.RabbitSourceConfiguration required a bean of type 'org.springframework.cloud.stream.messaging.Source' that could not be found.

Action:

Consider defining a bean of type 'org.springframework.cloud.stream.messaging.Source' in your configuration.

I get the same behaviour with the 1.3.0.RELEASE and 1.2.0.RELEASE of spring-cloud-starter-stream-rabbit.

I override RabbitSourceConfiguration so I can set a header mapper on the AmqpInboundChannelAdapter, and also to perform a connectivity test prior to starting up the container.

My subclass is bound to the Spring Boot application with @EnableBinding(HeaderMapperRabbitSourceConfiguration.class). A cutdown version of my subclass is:

public class HeaderMapperRabbitSourceConfiguration extends RabbitSourceConfiguration {

    public HeaderMapperRabbitSourceConfiguration(final MyHealthCheck healthCheck,
                                                 final MyAppConfig config) {
        // ...
    }

    @Bean
    @Override
    public AmqpInboundChannelAdapter adapter() {
        final AmqpInboundChannelAdapter adapter = super.adapter();
        adapter.setHeaderMapper(new NotificationHeaderMapper(config));

        return adapter;
    }

    @Bean
    @Override
    public SimpleMessageListenerContainer container() {
        if (config.performConnectivityCheckOnStartup()) {

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Attempting connectivity with ...");
            }
            final Health health = healthCheck.health();
            if (health.getStatus() == Status.DOWN) {
                LOGGER.error("Unable to connect .....");
                throw new UnableToLoginException("Unable to connect ...");
            } else if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Connectivity established with ...");
            }
        }

        return super.container();
    }
}

Body:
You really should never do stuff like healthCheck.health(); within a @Bean definition. The application context is not yet fully baked or started; it may, or may not, work depending on the order that beans are created.

If you want to prevent the app from starting, add a bean that implements SmartLifecycle, put the bean in a late phase (high value) so it's started after everything else. Then put your code in start(). autStartup must be true.

In this case, it's being run before the stream infrastructure has created the channel.

Some ordering might have changed from the earlier release but, in any case, performing activity like this in a @Bean definition is dangerous.

You just happened to be lucky before.

EDIT

I just noticed your @EnableBinding is wrong; it should be Source.class. I can't see how that would ever have worked - that's what creates the bean for the channels field of type Source.

This works fine for me after updating stream and the binder to 1.3.0.RELEASE...

@Configuration
public class MySource extends RabbitSourceConfiguration {

    @Bean
    @Override
    public AmqpInboundChannelAdapter adapter() {
        AmqpInboundChannelAdapter adapter = super.adapter();
        adapter.setHeaderMapper(new MyMapper());
        return adapter;
    }

}

and

@SpringBootApplication
@EnableBinding(Source.class)
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

If that doesn't work, please edit the question to show your POM.


问:
How to correct flow warning: destructuring (Missing annotation)
I'm writing a small React Native app and I'm trying to use Flow, but I can't really get a proper tutorial about it anywhere.

I keep getting the error: destructuring (Missing annotation) about the ({ station }) in the 1st line of this code:

```<code>const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
</code>```

station is a json response and code and label are strings inside that json.

How do I fix the error/warning?

答:
I tried your example and got No errors!, because Flow doesn't require type annotations on private functions.

If instead I add an export like this:

```<code>// @flow
export const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
  return code + label;
};
</code>```

I get the following error. (Which I assume is close enough to what you are seeing.)

```<code>Error: 41443242.js:2
  2: export const StationDetail = ({ station }) => {
                                   ^^^^^^^^^^^ destructuring. Missing annotation

Found 1 error
</code>```

You can solve that in at least two ways. The better way is to add a type annotation for the function argument. For example:

```<code>export const StationDetail =
  ({ station }: { station: { code: number, label: string } }) =>
</code>```

or

```<code>export const StationDetail =
  ({ station }: {| station: {| code: string, label: string |} |}) =>
</code>```

or even

```<code>type Code = 1 | 2 | 3 | 4 | 5 | 6;
type Radio ={|
  station: {| code: Code, label: string |},
  signalStrength: number,
  volume: number,
  isMuted: bool,
|};
export const StationDetail = ({ station }: Radio) =>
  ...
</code>```

if you want to make sure the StationDetail is always called with a proper Radio object even though the current implementation only looks at the station field.

The other alternative is to change the first comment to // @flow weak and let Flow infer the argument type on it's own. That is Less Good™ because it makes it easier to accidentally change your public API and makes your actual intentions less clear.

Body:
I'm writing a small React Native app and I'm trying to use Flow, but I can't really get a proper tutorial about it anywhere.

I keep getting the error: destructuring (Missing annotation) about the ({ station }) in the 1st line of this code:

const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;

station is a json response and code and label are strings inside that json.

How do I fix the error/warning?

Body:
I tried your example and got No errors!, because Flow doesn't require type annotations on private functions.

If instead I add an export like this:

// @flow
export const StationDetail = ({ station }) => {
  const {
    code,
    label,
  } = station;
  return code + label;
};

I get the following error. (Which I assume is close enough to what you are seeing.)

Error: 41443242.js:2
  2: export const StationDetail = ({ station }) => {
                                   ^^^^^^^^^^^ destructuring. Missing annotation

Found 1 error

You can solve that in at least two ways. The better way is to add a type annotation for the function argument. For example:

export const StationDetail =
  ({ station }: { station: { code: number, label: string } }) =>

or

export const StationDetail =
  ({ station }: {| station: {| code: string, label: string |} |}) =>

or even

type Code = 1 | 2 | 3 | 4 | 5 | 6;
type Radio ={|
  station: {| code: Code, label: string |},
  signalStrength: number,
  volume: number,
  isMuted: bool,
|};
export const StationDetail = ({ station }: Radio) =>
  ...

if you want to make sure the StationDetail is always called with a proper Radio object even though the current implementation only looks at the station field.

The other alternative is to change the first comment to // @flow weak and let Flow infer the argument type on it's own. That is Less Good™ because it makes it easier to accidentally change your public API and makes your actual intentions less clear.


答:
try this </p>

```<code>SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2, col3 ORDER BY col2, col3
</code>```

Title: Query with GROUP BY and ORDER BY not working when multiple columns in SELECT are chosen

Body:
try this

SELECT col2, col3 FROM tbl WHERE col1 IS NULL GROUP BY col2, col3 ORDER BY col2, col3


问:
diagonal lines from the top right trying to draw on a UIView
I've got a tablet called a Slate that I can process x,y points from. I can pass these x,y points to my "drawShape" function, the equivalent of a touchesMoved function. I have a custom UIView class designed for this purpose with 4 main functions. The first three are touchesbegan/moved/ended and there is a drawRect.

Here's the source to the UIView subclass...

```<code>//
//  DrawingLayerView.m
//
//
//  Created by Monica Kachlon on 12/3/17.
//

#import "DrawingLayerView.h"
#include "UIBezierPath+Interpolation.h"

@interface StrokeA : NSObject

@property (assign, nonatomic) CGPoint startPoint;

- (id)initWithStartPoint:(CGPoint)point;

@property (strong, nonatomic) NSMutableArray * points;

@end

@implementation StrokeA

- (id)initWithStartPoint:(CGPoint)point {
    self = [super init];
    self.startPoint = point;
    self.points = [NSMutableArray array];

    return self;
}

@end

@implementation DrawingLayerView

NSMutableArray * strokes;
NSMutableArray * points;

StrokeA * currentStroke;
UIBezierPath * currentPath;
UIBezierPath *path;
UIBezierPath *pathTwo;

UIBezierPath *Newpath;
CAShapeLayer * currentLayer;

- (void) noodlez
{
path = [UIBezierPath bezierPath];

   currentPath = [UIBezierPath bezierPath];

    pathTwo = [UIBezierPath bezierPath];

    Newpath = [UIBezierPath bezierPath];
     strokes = [NSMutableArray array];
     points = [NSMutableArray array];

}
- (void)startTouch: (CGPoint)point
{

    currentStroke = [[StrokeA alloc] initWithStartPoint:point];
    [strokes addObject:currentStroke];
}

- (UIBezierPath *)createPath {
    UIBezierPath * bezierPath = [UIBezierPath bezierPath];
    for (StrokeA * stroke in strokes) {
        [bezierPath moveToPoint:stroke.startPoint];
        for (NSValue * value in stroke.points) {
            [bezierPath addLineToPoint:[value CGPointValue]];
        }
    }
    return bezierPath;
}

- (void)endTouch: (CGPoint)point
{

    [points removeAllObjects];
    [self setNeedsDisplay];
}
- (void)drawShape: (CGPoint)point
{
    if (!currentStroke) {
        [self startTouch:point];
    }
    [currentStroke.points addObject:[NSValue valueWithCGPoint:point]];
    pathTwo = [self createPath];

    [self setNeedsDisplay];

}

- (void)drawRect:(CGRect)rect {
    [[UIColor blackColor] setStroke];
    [pathTwo stroke];
}

@end
</code>```

And here's the screenshot.

I tried writing "Ok?" Just to illustrate the issue.

答: Despite the fact that the code is lacking some detail and the question is poorly worded, the screenshot is clearly showing that the initial point for the path is (0,0) in each case. Dump the points in the paths out to the console and you'll see it. Figure out how those (0,0)'s are getting in there and you'll solve the problem.</p>

Body:
I've got a tablet called a Slate that I can process x,y points from. I can pass these x,y points to my "drawShape" function, the equivalent of a touchesMoved function. I have a custom UIView class designed for this purpose with 4 main functions. The first three are touchesbegan/moved/ended and there is a drawRect.

Here's the source to the UIView subclass...

//
//  DrawingLayerView.m
//
//
//  Created by Monica Kachlon on 12/3/17.
//

#import "DrawingLayerView.h"
#include "UIBezierPath+Interpolation.h"

@interface StrokeA : NSObject

@property (assign, nonatomic) CGPoint startPoint;

- (id)initWithStartPoint:(CGPoint)point;

@property (strong, nonatomic) NSMutableArray * points;

@end

@implementation StrokeA

- (id)initWithStartPoint:(CGPoint)point {
    self = [super init];
    self.startPoint = point;
    self.points = [NSMutableArray array];

    return self;
}

@end

@implementation DrawingLayerView

NSMutableArray * strokes;
NSMutableArray * points;

StrokeA * currentStroke;
UIBezierPath * currentPath;
UIBezierPath *path;
UIBezierPath *pathTwo;

UIBezierPath *Newpath;
CAShapeLayer * currentLayer;

- (void) noodlez
{
path = [UIBezierPath bezierPath];

   currentPath = [UIBezierPath bezierPath];

    pathTwo = [UIBezierPath bezierPath];

    Newpath = [UIBezierPath bezierPath];
     strokes = [NSMutableArray array];
     points = [NSMutableArray array];

}
- (void)startTouch: (CGPoint)point
{

    currentStroke = [[StrokeA alloc] initWithStartPoint:point];
    [strokes addObject:currentStroke];
}

- (UIBezierPath *)createPath {
    UIBezierPath * bezierPath = [UIBezierPath bezierPath];
    for (StrokeA * stroke in strokes) {
        [bezierPath moveToPoint:stroke.startPoint];
        for (NSValue * value in stroke.points) {
            [bezierPath addLineToPoint:[value CGPointValue]];
        }
    }
    return bezierPath;
}

- (void)endTouch: (CGPoint)point
{

    [points removeAllObjects];
    [self setNeedsDisplay];
}
- (void)drawShape: (CGPoint)point
{
    if (!currentStroke) {
        [self startTouch:point];
    }
    [currentStroke.points addObject:[NSValue valueWithCGPoint:point]];
    pathTwo = [self createPath];

    [self setNeedsDisplay];

}

- (void)drawRect:(CGRect)rect {
    [[UIColor blackColor] setStroke];
    [pathTwo stroke];
}

@end

And here's the screenshot.

I tried writing "Ok?" Just to illustrate the issue.


问:
Welcome message not visibile in Webchat,but work in Emulator
```<code>IConversationUpdateActivity update = message;
        using (var scope = Microsoft.Bot.Builder.Dialogs.Internals.DialogModule.BeginLifetimeScope(Conversation.Container, message))
        {
            var client = scope.Resolve<IConnectorClient>();
            if (update.MembersAdded.Any())
            {
                foreach (var newMember in update.MembersAdded)
                {
                    if (newMember.Id != message.Recipient.Id)
                    {
                        var reply = message.CreateReply();
                        reply.Text = $"Welcome {newMember.Name}!";
                        client.Conversations.ReplyToActivityAsync(reply);
                    }
                }
            }
        }
</code>```

I'm new to ChatBot development using Microsoft BotFramework.

I have register and deployed a simple bot that was working fine with emulator (i.e bot says welcome to my simple bot),but when i used WebChat no welcome greeting was displayed,instead when user type Hi or any text after that the greeting message is displayed.
had gone to various tutorial and solution but not getting the exact cause. i'm using Microsoft.Bot.Builder v3.12

答:
I just tested your code and got the same behavior. The odd part is that there seems to only be one conversation update for when the bot joins, rather than one for the bot and one for the user. I am looking into this.  The following code is working if you would like to give it a try:</p>

```<code>IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity;
if (iConversationUpdated != null)
{
    ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl));

    foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty<ChannelAccount>())
    {
        // if the bot is added, then
        if (member.Id == iConversationUpdated.Recipient.Id)
        {
            var reply = ((Activity)iConversationUpdated).CreateReply(
                $"Hi! I'm Botty McBotface and this is a welcome message");
            connector.Conversations.ReplyToActivityAsync(reply);
        }
    }
}
</code>```

Body:
IConversationUpdateActivity update = message;
        using (var scope = Microsoft.Bot.Builder.Dialogs.Internals.DialogModule.BeginLifetimeScope(Conversation.Container, message))
        {
            var client = scope.Resolve<IConnectorClient>();
            if (update.MembersAdded.Any())
            {
                foreach (var newMember in update.MembersAdded)
                {
                    if (newMember.Id != message.Recipient.Id)
                    {
                        var reply = message.CreateReply();
                        reply.Text = $"Welcome {newMember.Name}!";
                        client.Conversations.ReplyToActivityAsync(reply);
                    }
                }
            }
        }

I'm new to ChatBot development using Microsoft BotFramework.

I have register and deployed a simple bot that was working fine with emulator (i.e bot says welcome to my simple bot),but when i used WebChat no welcome greeting was displayed,instead when user type Hi or any text after that the greeting message is displayed.
had gone to various tutorial and solution but not getting the exact cause. i'm using Microsoft.Bot.Builder v3.12

Body:
I just tested your code and got the same behavior. The odd part is that there seems to only be one conversation update for when the bot joins, rather than one for the bot and one for the user. I am looking into this.  The following code is working if you would like to give it a try:

IConversationUpdateActivity iConversationUpdated = message as IConversationUpdateActivity;
if (iConversationUpdated != null)
{
    ConnectorClient connector = new ConnectorClient(new System.Uri(message.ServiceUrl));

    foreach (var member in iConversationUpdated.MembersAdded ?? System.Array.Empty<ChannelAccount>())
    {
        // if the bot is added, then
        if (member.Id == iConversationUpdated.Recipient.Id)
        {
            var reply = ((Activity)iConversationUpdated).CreateReply(
                $"Hi! I'm Botty McBotface and this is a welcome message");
            connector.Conversations.ReplyToActivityAsync(reply);
        }
    }
}


问:
return statement in a function as class
I am confused about the return statement in a function that serves as a class. See the example code below:

```<code><html>
<body>

<script type="text/javascript">
function test() {
    this.abc = 'def';
    return 3;
}

var mytest = new test();

document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc);

</script>

</body>
</html>
</code>```

The code out put: [object Object], object, def.

Here is my question. I wrote 'return 3' in the test() function. Is this statement ignored when 'new test()' is called?

Thanks.

答:
The new operator instantiates and returns an object. Here are some examples with its output:

```<code>(...)
var mytest = test();
document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc);
// 3, number, undefined
</code>```

Or:

```<code>function test() {
    this.abc = 'def';
    this.getvalue = function(){
        return 3;
    }
}
var mytest = new test();
document.write(mytest.getvalue() + ', ' + (typeof mytest) + ', ' + mytest.abc);
// 3, object, def
</code>```

Title: return statement in a function as class

Body:
I am confused about the return statement in a function that serves as a class. See the example code below:

The code out put: [object Object], object, def.

Here is my question. I wrote 'return 3' in the test() function. Is this statement ignored when 'new test()' is called?

Thanks.

Body:
The new operator instantiates and returns an object. Here are some examples with its output:

(...)
var mytest = test();
document.write(mytest + ', ' + (typeof mytest) + ', ' + mytest.abc);
// 3, number, undefined

Or:

function test() {
    this.abc = 'def';
    this.getvalue = function(){
        return 3;
    }
}
var mytest = new test();
document.write(mytest.getvalue() + ', ' + (typeof mytest) + ', ' + mytest.abc);
// 3, object, def


问:
Bubble sorting in dynamic array of objects in C++
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.

I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.

The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.

I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.

I should print the names of cities sorted by their lengths.

Code:

```<code>class City{
private: char *name;
         double width;
         double length;
         double height;
public:void Output();
    City();
    ~City();
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }

};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <=strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}
void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width <<" deg"<< endl;;
    cout << " Length is: " << length << " deg"<<endl;
    cout << " Height is: " << height <<" m"<<endl;
    return;
}
City::~City()
{
    cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}

int main()
{
    //City town;

    //town.Input();
    //town.Output();
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;
    double *Lengths = new double[n];
    for (int j = 0; j < n; j++)
    {
        Lengths[j] = mA[j].GetLength();

    }
int k = 0;//counter
    double max = Lengths[0];
    for (int j = 1; j < n; j++)
    {
        if (Lengths[j - 1] >Lengths[j])
        {
            max = Lengths[j - 1];
            Lengths[j - 1] = Lengths[j];
            Lengths[j] = max;
        }
    }

    for (int j = 0; j < n; j++)//cycle for output
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}
</code>```

答:
I'm not entirely sure of what you're asking.

However, from what I can tell your main issue is that you can't sort because you're trying to compare two private variables from two objects.

If the objects are placed into an Array of type city, you can bubblesort by length however you would be required to use the getters in order to reference the variables that are private during sorting.

For example (not exact syntax)

```<code>if(cityArray[0].getLength() < cityArray[1].getLength())
{
 //Do Something
}
</code>```

Body:
I have class City with following private data: name of city, width,length and height of the city. I have to make dynamic array, which is inserted by constructor by default- City(),when the programs starts.Then the program uses method output() and prints inserted array of cities.

I should use bubble sort to sort the cities by their length. And when this is done, the program should show the sorted cities in increasing lengths.

The problem is that my data are in private(in public everything works excellent but principle of capsulation is violated!) so I can't do bubble sort.

I tried to do another dynamic array of type double double Lengths[n], which content is lengths of first array. Then I do sorting, but program prints only sorted lengths and this is not my goal.

I should print the names of cities sorted by their lengths.

Code:

class City{
private: char *name;
         double width;
         double length;
         double height;
public:void Output();
    City();
    ~City();
    double GetLength()
    {
        return length;
    }
    double GetWidth(){ return width; }
    double GetHeight(){ return height; }
    char GetName(){ return *name; }

};
City::City()
{
    char ime[20];
    cout << "Name= ";
    cin >> ime;
    name = new char[strlen(ime) + 1];
    for (int i = 0; i <=strlen(ime); i++)
        name[i] = ime[i];

    cout << "Width= ";
    cin >> width;
    cout << "Length= ";
    cin >> length;
    cout << "Height= ";
    cin >> height;
}
void City::Output()
{
    cout << "Name is: " << name << endl;
    cout << " Width is: " << width <<" deg"<< endl;;
    cout << " Length is: " << length << " deg"<<endl;
    cout << " Height is: " << height <<" m"<<endl;
    return;
}
City::~City()
{
    cout << " " << endl;
cout << "Destructor of City!" << endl;
delete[] name;
}

int main()
{
    //City town;

    //town.Input();
    //town.Output();
    int n;
    City *mA;
    cout << "Input number of cities: " << endl;
    cin >> n;
    mA = new City[n];
    for (int j = 0; j < n; j++)
    {
        mA[j].Output();
    }
    cout << "Cities from west to east, sorted by their length" << endl;
    double *Lengths = new double[n];
    for (int j = 0; j < n; j++)
    {
        Lengths[j] = mA[j].GetLength();

    }
int k = 0;//counter
    double max = Lengths[0];
    for (int j = 1; j < n; j++)
    {
        if (Lengths[j - 1] >Lengths[j])
        {
            max = Lengths[j - 1];
            Lengths[j - 1] = Lengths[j];
            Lengths[j] = max;
        }
    }

    for (int j = 0; j < n; j++)//cycle for output
    {
        mA[j].Output();
    }

    delete[]mA;
    return 0;

}

Body:
I'm not entirely sure of what you're asking.

However, from what I can tell your main issue is that you can't sort because you're trying to compare two private variables from two objects.

If the objects are placed into an Array of type city, you can bubblesort by length however you would be required to use the getters in order to reference the variables that are private during sorting.

For example (not exact syntax)

if(cityArray[0].getLength() < cityArray[1].getLength())
{
 //Do Something
}


问:
A wstring wrapper to std::runtime_error exception?
Supposing I have these functions defined somewhere:

```<code>std::string ws_to_s(const wchar_t*);
std::string ws_to_s(const std::wstring&);
std::wstring s_to_ws(const char*);
</code>```

I wrote this class:

```<code>class runtime_error_w : public std::runtime_error {
public:
  runtime_error_w() = default;

  runtime_error_w(const wchar_t* what_arg)
    : runtime_error(ws_to_s(what_arg)) { }

  runtime_error_w(const std::wstring& what_arg)
    : runtime_error(ws_to_s(what_arg)) { }

  virtual const std::wstring what_w() const noexcept {
    return ws_to_s(what());
  }
};
</code>```

So far this worked for me, but is there any problem with this approach?

Notice that what_w() returns a std::string object, not a const char*.

答: Based on the comments below the question, I agree that it's a bad idea to use this class, because of a potential bad_alloc raising when constructing wstring.

Body:
Supposing I have these functions defined somewhere:

std::string ws_to_s(const wchar_t*);
std::string ws_to_s(const std::wstring&);
std::wstring s_to_ws(const char*);

I wrote this class:

class runtime_error_w : public std::runtime_error {
public:
  runtime_error_w() = default;

  runtime_error_w(const wchar_t* what_arg)
    : runtime_error(ws_to_s(what_arg)) { }

  runtime_error_w(const std::wstring& what_arg)
    : runtime_error(ws_to_s(what_arg)) { }

  virtual const std::wstring what_w() const noexcept {
    return ws_to_s(what());
  }
};

So far this worked for me, but is there any problem with this approach?

Notice that what_w() returns a std::string object, not a const char*.