问:
Bezier curve by control points is not working
I'm trying to make Bezier curve by control point.
I have some examples and followed it. But it did not work.
It shows the line is going to (0, 0) points during working.
I still don't get it why.

Here's the code in the C++ language, using OpenGL.

```<code>#define _CRT_SECURE_NO_WARNINGS

#include <Windows.h>

#include <gl/glut.h>
#include <gl/GLU.h>
#include <gl/GL.h>

#include <math.h>

#define CTRL_COUNT 100

void display();
void init();
float getNextBezierPointX(float t);
float getNextBezierPointY(float t);
void drawline();

int ctrlPointsCount;
int ctrlPointsX[CTRL_COUNT], ctrlPointsY[CTRL_COUNT];
int X1[20] = { 10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105 };
int Y1[20] = { 50,60,40,70,40,60,35,80,45,55,30,60,40,60,40,55,35,70,40,50 };

void main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(500, 300);
    glutCreateWindow("Bezier");

    glutDisplayFunc(display);
    init();
    glutMainLoop();
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 0.0, 0.0);

    ctrlPointsCount = 20;

    for (int i = 0; i < 20; i++) {
        ctrlPointsX[i] = X1[i];
        ctrlPointsY[i] = Y1[i];
    }

    drawline();

    glFlush();
}

void init() {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glColor3f(1.0, 0.0, 0.0);
    glPointSize(8.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 128.0, 0.0, 96.0);
}

float getNextBezierPointX(float t) {
    float x = 0.0;
    int c;

    for (int i = 0; i < ctrlPointsCount; i ++) {
        if (i == 0 || i == ctrlPointsCount - 1)
            c = 1;
        else
            c = ctrlPointsCount - 1;

        x = x + c * pow(t, i) * pow(1 - t, ctrlPointsCount - 1 - i) * ctrlPointsX[i];
    }

    return x;
}

float getNextBezierPointY(float t) {
    float y = 0.0;
    int c;

    for (int i = 0; i < ctrlPointsCount; i ++) {
        if (i == 0 || i == ctrlPointsCount - 1)
            c = 1;
        else
            c = ctrlPointsCount - 1;
        y = y + c * pow(t, i) * pow(1 - t, ctrlPointsCount - 1 - i) * ctrlPointsY[i];
    }

    return y;
}

void drawline() {
    float x, y;

    for (int i = 0; i < 20; i++) {
        glBegin(GL_POINTS);
        glVertex2i(ctrlPointsX[i], ctrlPointsY[i]);
        glEnd();
        glFlush();
    }

    float oldX = ctrlPointsX[0], oldY = ctrlPointsY[0];

    for (double t = 0.0; t <= 1.0; t += 0.01) {
        x = getNextBezierPointX(t);
        y = getNextBezierPointY(t);

        glColor3f(1.0, 1.0, 1.0);

        glBegin(GL_LINES);
        glVertex2f(oldX, oldY);
        glVertex2f(x, y);
        glEnd();

        glFlush();

        oldX = x;
        oldY = y;
    }

}
</code>```

答:
For a bezier curve like this you have to calculate Bernstein polynomials:

```<code>double factorial(int n)
{
    double x = 1.0;
    for (int i = 1; i <= n; i++)
      x *= (double)i;
    return x;
}

double Ni(int n, int i)
{
    double a1 = factorial(n);
    double a2 = factorial(i);
    double a3 = factorial(n - i);
    double ni =  a1/ (a2 * a3);
    return ni;
}

double Bernstein(int n, int i, double t)
{
    double ti = (t == 0.0 && i == 0) ? 1.0 : pow(t, i); /* t^i */
    double tni = (n == i && t == 1.0) ? 1.0 : pow((1 - t), (n - i)); /* (1 - t)^i */
    double basis = Ni(n, i) * ti * tni; //Bernstein basis
    return basis;
}
</code>```

The code to create the curve may look like this:

```<code>struct vec2
{
  double x, y;
};

vec2 getBezierPoint(float t, int n, int x[], int y[] )
{
    vec2 pt{ 0.0, 0.0 };
    for (int i = 0; i < n; i ++) {
        double b = Bernstein( n - 1, i, t );
        pt.x += b * x[i];
        pt.y += b * y[i];
    }
    return pt;
}

float oldX = ctrlPointsX[0], oldY = ctrlPointsY[0];
for (double t = 0.0; t <= 1.0; t += 0.01)
{
    vec2 pt = getBezierPoint( t, ctrlPointsCount, ctrlPointsX, ctrlPointsY );

    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    glVertex2f(oldX, oldY);
    glVertex2f((float)pt.x, (float)pt.y);
    glEnd();
    glFlush();

    oldX = (float)pt.x;  oldY = (float)pt.y;
}
</code>```

An other solution is provided in the answer to the Stack Overflow question How do I implement a Bézier curve in C++?:

```<code>#include <vector>

vec2 getBezierPoint2( float t, int n, int x[], int y[] )
{
    std::vector<double> tmpx( n ), tmpy( n );
    for ( int i=0; i<n; ++ i )
    {
      tmpx[i] = x[i];
      tmpy[i] = y[i];
    }
    int i = n - 1;
    while (i > 0)
    {
        for (int k = 0; k < i; k++)
        {
            tmpx[k] = tmpx[k] + t * ( tmpx[k+1] - tmpx[k] );
            tmpy[k] = tmpy[k] + t * ( tmpy[k+1] - tmpy[k] );
        }
        i--;
    }
    return { tmpx[0], tmpy[0] };
}
</code>```

But may be the result is not what you expect it to be, because you create a Higher-order Bézier curve which results in a very flat curve:

Maybe you want to connect any number of points with square bezier curves: Quadratic Bézier Curve: Calculate Points

Body:
I'm trying to make Bezier curve by control point.
I have some examples and followed it. But it did not work.
It shows the line is going to (0, 0) points during working.
I still don't get it why.

Here's the code in the C++ language, using OpenGL.

#define _CRT_SECURE_NO_WARNINGS

#include <Windows.h>

#include <gl/glut.h>
#include <gl/GLU.h>
#include <gl/GL.h>

#include <math.h>

#define CTRL_COUNT 100

void display();
void init();
float getNextBezierPointX(float t);
float getNextBezierPointY(float t);
void drawline();

int ctrlPointsCount;
int ctrlPointsX[CTRL_COUNT], ctrlPointsY[CTRL_COUNT];
int X1[20] = { 10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100,105 };
int Y1[20] = { 50,60,40,70,40,60,35,80,45,55,30,60,40,60,40,55,35,70,40,50 };

void main(int argc, char *argv[]) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(500, 300);
    glutCreateWindow("Bezier");

    glutDisplayFunc(display);
    init();
    glutMainLoop();
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 0.0, 0.0);

    ctrlPointsCount = 20;

    for (int i = 0; i < 20; i++) {
        ctrlPointsX[i] = X1[i];
        ctrlPointsY[i] = Y1[i];
    }

    drawline();

    glFlush();
}

void init() {
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glColor3f(1.0, 0.0, 0.0);
    glPointSize(8.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0.0, 128.0, 0.0, 96.0);
}

float getNextBezierPointX(float t) {
    float x = 0.0;
    int c;

    for (int i = 0; i < ctrlPointsCount; i ++) {
        if (i == 0 || i == ctrlPointsCount - 1)
            c = 1;
        else
            c = ctrlPointsCount - 1;

        x = x + c * pow(t, i) * pow(1 - t, ctrlPointsCount - 1 - i) * ctrlPointsX[i];
    }

    return x;
}

float getNextBezierPointY(float t) {
    float y = 0.0;
    int c;

    for (int i = 0; i < ctrlPointsCount; i ++) {
        if (i == 0 || i == ctrlPointsCount - 1)
            c = 1;
        else
            c = ctrlPointsCount - 1;
        y = y + c * pow(t, i) * pow(1 - t, ctrlPointsCount - 1 - i) * ctrlPointsY[i];
    }

    return y;
}

void drawline() {
    float x, y;

    for (int i = 0; i < 20; i++) {
        glBegin(GL_POINTS);
        glVertex2i(ctrlPointsX[i], ctrlPointsY[i]);
        glEnd();
        glFlush();
    }

    float oldX = ctrlPointsX[0], oldY = ctrlPointsY[0];

    for (double t = 0.0; t <= 1.0; t += 0.01) {
        x = getNextBezierPointX(t);
        y = getNextBezierPointY(t);

        glColor3f(1.0, 1.0, 1.0);

        glBegin(GL_LINES);
        glVertex2f(oldX, oldY);
        glVertex2f(x, y);
        glEnd();

        glFlush();

        oldX = x;
        oldY = y;
    }

}

Body:
For a bezier curve like this you have to calculate Bernstein polynomials:

double factorial(int n)
{
    double x = 1.0;
    for (int i = 1; i <= n; i++)
      x *= (double)i;
    return x;
}

double Ni(int n, int i)
{
    double a1 = factorial(n);
    double a2 = factorial(i);
    double a3 = factorial(n - i);
    double ni =  a1/ (a2 * a3);
    return ni;
}

double Bernstein(int n, int i, double t)
{
    double ti = (t == 0.0 && i == 0) ? 1.0 : pow(t, i); /* t^i */
    double tni = (n == i && t == 1.0) ? 1.0 : pow((1 - t), (n - i)); /* (1 - t)^i */
    double basis = Ni(n, i) * ti * tni; //Bernstein basis
    return basis;
}

The code to create the curve may look like this:

struct vec2
{
  double x, y;
};

vec2 getBezierPoint(float t, int n, int x[], int y[] )
{
    vec2 pt{ 0.0, 0.0 };
    for (int i = 0; i < n; i ++) {
        double b = Bernstein( n - 1, i, t );
        pt.x += b * x[i];
        pt.y += b * y[i];
    }
    return pt;
}

float oldX = ctrlPointsX[0], oldY = ctrlPointsY[0];
for (double t = 0.0; t <= 1.0; t += 0.01)
{
    vec2 pt = getBezierPoint( t, ctrlPointsCount, ctrlPointsX, ctrlPointsY );

    glColor3f(1.0, 1.0, 1.0);
    glBegin(GL_LINES);
    glVertex2f(oldX, oldY);
    glVertex2f((float)pt.x, (float)pt.y);
    glEnd();
    glFlush();

    oldX = (float)pt.x;  oldY = (float)pt.y;
}

An other solution is provided in the answer to the Stack Overflow question How do I implement a Bézier curve in C++?:

#include <vector>

vec2 getBezierPoint2( float t, int n, int x[], int y[] )
{
    std::vector<double> tmpx( n ), tmpy( n );
    for ( int i=0; i<n; ++ i )
    {
      tmpx[i] = x[i];
      tmpy[i] = y[i];
    }
    int i = n - 1;
    while (i > 0)
    {
        for (int k = 0; k < i; k++)
        {
            tmpx[k] = tmpx[k] + t * ( tmpx[k+1] - tmpx[k] );
            tmpy[k] = tmpy[k] + t * ( tmpy[k+1] - tmpy[k] );
        }
        i--;
    }
    return { tmpx[0], tmpy[0] };
}

But may be the result is not what you expect it to be, because you create a Higher-order Bézier curve which results in a very flat curve:

Maybe you want to connect any number of points with square bezier curves: Quadratic Bézier Curve: Calculate Points


来源: stackexchange

问:
How to evaluate a JavaScript function from a text input

I have an in-browser particle engine running in THREE.js. I want to add animation functionality, so I have a text input that will contain code, which should be called from my "animate" function which updates the position and other information of the particle emitters.
https://i.imgur.com/vguWZAq.jpg

```<code>function animate() {

    time = Date.now();

    runCustomAnimateScript();

    for(var i = 0; i < emitters.length; i++){
        emitters[i].updateParticles(deltaTime);
    }

    render();

    requestAnimationFrame( animate );
}

function runCustomAnimateScript(){
    //Filled from text input after updateCustomAnimateScript is called
    //Called from within animate (which is run every frame)
}

function updateCustomAnimateScript(){
    //Parse document.querySelectorAll("textarea[name='customAnimateScript']").value
    //into a script, and enter it into runCustomAnimateScript
}
</code>```

Currently I have no way to turn this text input into an executable JavaScript function. I'm surprised that nobody has tried to do this before, or at least posted about it?

答:
The old way you evaluate arbitrary code is by using the eval() method.

A better way is to use Components.utils.evalInSandbox, but the support may be limited.

```<code>function runCustomAnimateScript(){
   const sandbox = new Components.utils.Sandbox("http://www.your-url.com/");
   let result = Components.utils.evalInSandbox(document.querySelectorAll("textarea[name='customAnimateScript']").value , sandbox);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an in-browser particle engine running in THREE.js. I want to add animation functionality, so I have a text input that will contain code, which should be called from my "animate" function which updates the position and other information of the particle emitters.
https://i.imgur.com/vguWZAq.jpg

function animate() {

    time = Date.now();

    runCustomAnimateScript();

    for(var i = 0; i < emitters.length; i++){
        emitters[i].updateParticles(deltaTime);
    }

    render();

    requestAnimationFrame( animate );
}

function runCustomAnimateScript(){
    //Filled from text input after updateCustomAnimateScript is called
    //Called from within animate (which is run every frame)
}

function updateCustomAnimateScript(){
    //Parse document.querySelectorAll("textarea[name='customAnimateScript']").value
    //into a script, and enter it into runCustomAnimateScript
}

Currently I have no way to turn this text input into an executable JavaScript function. I'm surprised that nobody has tried to do this before, or at least posted about it?

Body:
The old way you evaluate arbitrary code is by using the eval() method.

A better way is to use Components.utils.evalInSandbox, but the support may be limited.

function runCustomAnimateScript(){
   const sandbox = new Components.utils.Sandbox("http://www.your-url.com/");
   let result = Components.utils.evalInSandbox(document.querySelectorAll("textarea[name='customAnimateScript']").value , sandbox);
}


问:
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.

答:
The problem is in three() async function. Instead of return Promise.reject(e) in your catch block, you can either not use a try/catch in the three function, and let any calling method handle errors, or if you must use try/catch in three() (for example, if you want to log the output as it appears you're currently doing before throwing the error to the calling function), throw the same exception again after logging.

An example of redefining three() to behave this way would be the following, which only changes the last line in your catch block:

```<code>// Rejects this async function, so the calling function will act as if the promise was rejected
async function three() {
  try {
    throw new Error();
  } catch (e) {
    console.log('caught', new Error().stack);
    throw e;
  }
}
</code>```

or

```<code>// Defines a function that returns a promise that's instantly rejected, so your calling method can handle the rejection
async function three() {
  throw new Error()
}
</code>```

The last throw e; effectively rejects the promise in your calling function which behaves as expected. Running return Promise.reject(e) does NOT reject the calling async function, but instead returns a Promise rejection object as if it's resolved in your parent function.

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.

Body:
The problem is in three() async function. Instead of return Promise.reject(e) in your catch block, you can either not use a try/catch in the three function, and let any calling method handle errors, or if you must use try/catch in three() (for example, if you want to log the output as it appears you're currently doing before throwing the error to the calling function), throw the same exception again after logging.

An example of redefining three() to behave this way would be the following, which only changes the last line in your catch block:

// Rejects this async function, so the calling function will act as if the promise was rejected
async function three() {
  try {
    throw new Error();
  } catch (e) {
    console.log('caught', new Error().stack);
    throw e;
  }
}

or

// Defines a function that returns a promise that's instantly rejected, so your calling method can handle the rejection
async function three() {
  throw new Error()
}

The last throw e; effectively rejects the promise in your calling function which behaves as expected. Running return Promise.reject(e) does NOT reject the calling async function, but instead returns a Promise rejection object as if it's resolved in your parent function.


问:
How to deploy a Google Cloud Function to an endpoint like /a/b
I've two simple functions, one triggered by the endpoint /root and another triggered by the endpoint /root/workflow.

I use the following command to deploy /root:
gcloud beta functions deploy root --stage-bucket ... --trigger-hhtp

How can I deploy the second function with the endpoint /root/workflow?

答:
Definitively, it's not possible to do it. Function names can only contain numbers, letters and hyphens.

From Google Cloud Platform: "Name must start with a letter followed by up to 47 letters, numbers, or hyphens, and cannot end with a hyphen".

If a proper API is needed and you would like a serverless solution, then Google App Engine should be used. Also Google Compute Engine and Google Kubernetes Engine can have proper API definitions.

Google Endpoints is the gateway powering the three solutions mentioned above.


问:
How can I load an image from my json file in angular 4?
I want to load an image from my json file in my angular 4 project. I had declared the path of my images in my json file. But instead of showing the images, the html template shows the path string directly of the images. I stored my images in the assets folder in my angular project

Html and json file is below

    <collapsible-list [type]="'expandable'">
      <collapsible-list-item>
        <collapsible-header class="waves-effect">

              {{ menu.Name }}

        </collapsible-header>
        <collapsible-body [expanded]="true">

                {{ setMenuItems.FoodItem.SetMenuImages }}

             Price: {{ menu.Price }} BDT

        </collapsible-body>
      </collapsible-list-item>
    </collapsible-list>

```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    {
      "Name": "Set Menu A",
      "Price": "199",
      "Id": "1",
      "SetMenuImage": "'assets/set-menu-a.jpg'",
      "SetMenuItems": [
        {
          "FoodItem":
          {
            "Id": "1",
            "Name": "Fried Rice",
            "Price": "99"
          },
          "FoodItemId": "1",
          "Id": "1",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "3",
            "Name": "Chicken Fry",
            "Price": "80"
          },
          "FoodItemId": "3",
          "Id": "2",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "2",
            "Name": "CocaCola",
            "Price": "30"
          },
          "FoodItemId": "2",
          "Id": "3",
          "Quantity": "2",
          "SetMenuId": "1"
        }

      ]
    }</code>```

答:
As commented by @stojevskimilan , you can bind the src attribute of an image tag with any variable containing the address of the image :

Template :

```<code><img [src]="variableInComponent">
</code>```

Body:
I want to load an image from my json file in my angular 4 project. I had declared the path of my images in my json file. But instead of showing the images, the html template shows the path string directly of the images. I stored my images in the assets folder in my angular project

Html and json file is below

    <collapsible-list [type]="'expandable'">
      <collapsible-list-item>
        <collapsible-header class="waves-effect">

              {{ menu.Name }}

        </collapsible-header>
        <collapsible-body [expanded]="true">

                {{ setMenuItems.FoodItem.SetMenuImages }}

             Price: {{ menu.Price }} BDT

        </collapsible-body>
      </collapsible-list-item>
    </collapsible-list>

    {
      "Name": "Set Menu A",
      "Price": "199",
      "Id": "1",
      "SetMenuImage": "'assets/set-menu-a.jpg'",
      "SetMenuItems": [
        {
          "FoodItem":
          {
            "Id": "1",
            "Name": "Fried Rice",
            "Price": "99"
          },
          "FoodItemId": "1",
          "Id": "1",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "3",
            "Name": "Chicken Fry",
            "Price": "80"
          },
          "FoodItemId": "3",
          "Id": "2",
          "Quantity": "1",
          "SetMenuId": "1"
        },
        {
          "FoodItem":
          {
            "Id": "2",
            "Name": "CocaCola",
            "Price": "30"
          },
          "FoodItemId": "2",
          "Id": "3",
          "Quantity": "2",
          "SetMenuId": "1"
        }

      ]
    }

Body:
As commented by @stojevskimilan , you can bind the src attribute of an image tag with any variable containing the address of the image :

Template :

<img [src]="variableInComponent">


问:
ADD a column to SQL table
I am trying to add a column to this query in SQL as below-</p>

答:
You don't need a subquery, you just need another condition on your JOIN, like so:

```<code>SELECT DISTINCT
    h.tradingitemid
    ,h.securityid
    ,h.currencyId
    ,CUSIP = hs.holdingsymbol
FROM cpr..holding_tbl h
INNER JOIN cpr..HoldingSymbol_tbl hs ON h.holdingid = hs.holdingId AND hs.holdingsymboltypeid = 2
WHERE h.userCompanyId = 10;
</code>```

ContentLicense: CC BY-SA 4.0

Title: ADD a column to SQL table

Body:
You don't need a subquery, you just need another condition on your JOIN, like so:

SELECT DISTINCT
    h.tradingitemid
    ,h.securityid
    ,h.currencyId
    ,CUSIP = hs.holdingsymbol
FROM cpr..holding_tbl h
INNER JOIN cpr..HoldingSymbol_tbl hs ON h.holdingid = hs.holdingId AND hs.holdingsymboltypeid = 2
WHERE h.userCompanyId = 10;


问:
JavaScript ReferenceError: x is not defined
I am trying to build a webpage to display some images and when clicked with pop-up a modal with thumbnail images at the bottom. I referenced w3Schools to create this and modified it a bit but now recieve a ReferenceError: currentImg is not defined in the console. When I click on an image the modal pops up but the image does not change when the arrows are clicked. Requesting help to understand the error and how to fix it. Please find below my code.

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showImgs(slideIndex);

function plusImg(n) {
  showImgs(slideIndex += n);
}

function plusImg(n) {
  showImgs(slideIndex = n);
}

function showImgs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > x.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = x.length;
  }
  alert(x.length)
  for (i = 0; i < x.length; i++) {
    alert(i)
    x[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
  }
  x[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " w3-opacity-off";
  captionText.innerHTML = dots[slideIndex - 1].alt;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.s4 img {
  height: 413px;
  width: 319px;
  margin: 0px;
  cursor: pointer;
}

#myModal span {
  cursor: pointer;
}

.w3-content {
  max-width: 1200px;
}

.w3-content .mySlides {
  width: 100%;
}

.w3-content .w3-col {
  padding: 5px;
}

.demo {
  width: 100%;
}</code>```

  <title>Commander, Carrier Strike Group ELEVEN (CCSG 11) Fact Sheet</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />

      ×

Page 1

            <
            >

```

答:
You have 2 functions with name plusImg.
Just rename second one to currentImg</p>

```<code>function plusImg(n) {
  showImgs(slideIndex += n);
}

function plusImg(n) {
  showImgs(slideIndex = n);
}
</code>```

Body:
I am trying to build a webpage to display some images and when clicked with pop-up a modal with thumbnail images at the bottom. I referenced w3Schools to create this and modified it a bit but now recieve a ReferenceError: currentImg is not defined in the console. When I click on an image the modal pops up but the image does not change when the arrows are clicked. Requesting help to understand the error and how to fix it. Please find below my code.

function openModal() {
  document.getElementById('myModal').style.display = "block";
}

function closeModal() {
  document.getElementById('myModal').style.display = "none";
}

var slideIndex = 1;
showImgs(slideIndex);

function plusImg(n) {
  showImgs(slideIndex += n);
}

function plusImg(n) {
  showImgs(slideIndex = n);
}

function showImgs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  var captionText = document.getElementById("caption");
  if (n > x.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = x.length;
  }
  alert(x.length)
  for (i = 0; i < x.length; i++) {
    alert(i)
    x[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" w3-opacity-off", "");
  }
  x[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " w3-opacity-off";
  captionText.innerHTML = dots[slideIndex - 1].alt;
}

.s4 img {
  height: 413px;
  width: 319px;
  margin: 0px;
  cursor: pointer;
}

#myModal span {
  cursor: pointer;
}

.w3-content {
  max-width: 1200px;
}

.w3-content .mySlides {
  width: 100%;
}

.w3-content .w3-col {
  padding: 5px;
}

.demo {
  width: 100%;
}

  <title>Commander, Carrier Strike Group ELEVEN (CCSG 11) Fact Sheet</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />

      ×

Page 1

            <
            >

Body:
You have 2 functions with name plusImg.
Just rename second one to currentImg

function plusImg(n) {
  showImgs(slideIndex += n);
}

function plusImg(n) {
  showImgs(slideIndex = n);
}


问:
obj == null vs null == obj
I have always used to check for null like

```<code>if(null==obj)
</code>```

When I compiled my code and looked into .class file after decompiling, I could see that my code got changed to

```<code>if(obj==null)
</code>```

I know in java null==obj and obj==nulldoesn't matter. But I'm curious to know why compiler changed it?

答:
Both are same in Java, as only boolean expressions can be inside an if. This is just a coding style preference by programmer and team agreement how to write.

The null != a is an old practice in programming languages like Java, C++ (called as Yoda Conditions).

As it is valid to write if (a = null) and accidentally assign null to the a so writing null first is a guard to stop this accident from happening.

Most programmers use a == null just because it looks more simpler for human to understand. Probably this might be the reason why compiler/decompiler put them in such order, maybe there is another reason...

Title: obj == null vs null == obj

Body:
I have always used to check for null like

if(null==obj)

When I compiled my code and looked into .class file after decompiling, I could see that my code got changed to

if(obj==null)

I know in java null==obj and obj==nulldoesn't matter. But I'm curious to know why compiler changed it?


问:
R – How to calculate combinations of pairs?
From a number of items (n), how do I compute all possible combinations of pairs in R? I can calculate the number of possible combinations with (n-1)*(n-3)*(n-5)*…, but how to get the combinations themselves?

For example, I have

```<code>x <- c("A", "B", "C", "D")
</code>```

That would make 4-1=3 combinations of pairs, so I want to have something like

```<code>("AB","CD")
("AC","BD")
("AD","BC")
</code>```

Thanks a lot!

答:
For that you can use either combn or expand.grid

```<code>x <- c("A","B","C","D")

expand.grid(x, x) # generates both way combinations

   Var1 Var2
1     A    A
2     B    A
3     C    A
4     D    A
5     A    B
6     B    B
7     C    B
8     D    B
9     A    C
10    B    C
11    C    C
12    D    C
13    A    D
14    B    D
15    C    D
16    D    D

t(combn(x, 2)) # order does not matter

     [,1] [,2]
[1,] "A"  "B"
[2,] "A"  "C"
[3,] "A"  "D"
[4,] "B"  "C"
[5,] "B"  "D"
[6,] "C"  "D"
</code>```

Body:
From a number of items (n), how do I compute all possible combinations of pairs in R? I can calculate the number of possible combinations with (n-1)*(n-3)*(n-5)*…, but how to get the combinations themselves?

For example, I have

x <- c("A", "B", "C", "D")

That would make 4-1=3 combinations of pairs, so I want to have something like

("AB","CD")
("AC","BD")
("AD","BC")

Thanks a lot!

Body:
For that you can use either combn or expand.grid

x <- c("A","B","C","D")

expand.grid(x, x) # generates both way combinations

   Var1 Var2
1     A    A
2     B    A
3     C    A
4     D    A
5     A    B
6     B    B
7     C    B
8     D    B
9     A    C
10    B    C
11    C    C
12    D    C
13    A    D
14    B    D
15    C    D
16    D    D

t(combn(x, 2)) # order does not matter

     [,1] [,2]
[1,] "A"  "B"
[2,] "A"  "C"
[3,] "A"  "D"
[4,] "B"  "C"
[5,] "B"  "D"
[6,] "C"  "D"


问:
LINQ over WCF Service (DomainService)
I have a simple DomainService:

```<code>[EnableClientAccess]
public class DomainService1 : IDomainService1
{
    [Query(IsComposable = true)]
    public IEnumerable<int> GetCollection(int from, int count)
    {
        const int max = 100000;
        int[] _collection;

        _collection = new int[max];

        for (int i = 0; i < max; i++)
        {
            _collection[i] = i;
        }

        return _collection.Skip(from).Take(count);
    }
}
</code>```

On client side I have generated proxy: client

I need comose LINQ query on client side and perform it on server side and throught service return query result.

When I do:

```<code>var res1 = client.GetCollection(100, 20).Skip(5).Take(5);
</code>```

than client.GetCollection(100, 20) in performed on server side and Skip(5) and Take(5)
on client side.

When i do:

```<code>var res2 = client.GetCollection(100, 90000).Skip(10).Take(10);
</code>```

it throw exception:

The underlying connection was closed: The connection was closed unexpectedly.

I think that this is due, that client.GetCollection(100, 90000) return large resultset.

Is a way get better information about reason why server fault?
And it possible perform query from client on server? I think so, because this allows LinqToEntitiesDomainService. But i cannot use EF, because i have access only to list of object stroed in memory.

Thank you.

JPo

答:
The exception is almost certainly due to the large dataset, so you can try upping the maximum buffer/message sizes in the <binding> config, eg:

```<code><binding name="MyServiceBinding" maxReceivedMessageSize="6291456" maxBufferSize="6291456">
    <readerQuotas maxArrayLength="6291456" maxStringContentLength="6291456"/>
</binding>
</code>```

Make sure you add those to the bindings in both the client and the server's config.

As for getting the additional client-defined parts of the query to execute on the server, you might need to make the return value an IQueryable<int> instead.

ContentLicense: CC BY-SA 2.5

Title: LINQ over WCF Service (DomainService)

Body:
I have a simple DomainService:

[EnableClientAccess]
public class DomainService1 : IDomainService1
{
    [Query(IsComposable = true)]
    public IEnumerable<int> GetCollection(int from, int count)
    {
        const int max = 100000;
        int[] _collection;

        _collection = new int[max];

        for (int i = 0; i < max; i++)
        {
            _collection[i] = i;
        }

        return _collection.Skip(from).Take(count);
    }
}

On client side I have generated proxy: client

I need comose LINQ query on client side and perform it on server side and throught service return query result.

When I do:

var res1 = client.GetCollection(100, 20).Skip(5).Take(5);

than client.GetCollection(100, 20) in performed on server side and Skip(5) and Take(5)
on client side.

When i do:

var res2 = client.GetCollection(100, 90000).Skip(10).Take(10);

it throw exception:

The underlying connection was closed: The connection was closed unexpectedly.

I think that this is due, that client.GetCollection(100, 90000) return large resultset.

Is a way get better information about reason why server fault?
And it possible perform query from client on server? I think so, because this allows LinqToEntitiesDomainService. But i cannot use EF, because i have access only to list of object stroed in memory.

Thank you.

JPo

Body:
The exception is almost certainly due to the large dataset, so you can try upping the maximum buffer/message sizes in the <binding> config, eg:

<binding name="MyServiceBinding" maxReceivedMessageSize="6291456" maxBufferSize="6291456">
    <readerQuotas maxArrayLength="6291456" maxStringContentLength="6291456"/>
</binding>

Make sure you add those to the bindings in both the client and the server's config.

As for getting the additional client-defined parts of the query to execute on the server, you might need to make the return value an IQueryable<int> instead.


问:
Websphere extendedDocumentRoot how to restrict by security role
We are using Websphere 8.5.5 Traditional

I have added an extended document root to Websphere's ibm-web-ext.xml file and set file sharing to true.

```<code><fileServingAttribute name="extendedDocumentRoot" value="C:/extdocroot"/>
<enable-file-serving value="true"/>
</code>```

inside the extended document root folder (C:/extdocroot) is a folder called pdfs. I would like to restrict the pdfs folder to only users who have logged in and have a particular role of 'school'.

the URL to serve up the pdf's is https://domain-name:9080/context-path/pdf/pdf-name.pdf
I added a security constraint in the web.xml file

```<code><security-constraint>
    <display-name>school PDFs</display-name>
    <web-resource-collection>
       <web-resource-name>School PDFs</web-resource-name>
       <url-pattern>/pdf/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
       <role-name>school</role-name>
    </auth-constraint>
</security-constraint>
</code>```

No matter what role a user is logged in as the PDF's will get served by the the server. Websphere is ignoring the security constraint for the URL that serves up PDF's from the extended document root. Is it possible to constrain these PDF's by the roles a logged in user has.

Note: My company has asked me to try and put these files outside of the ear file and also have Websphere secure the files using user's role. I was also instructed not to use the Apache HTTP Server to host these files since it is in the DMZ.

答:
I have found that this was a bug in Websphere 8.5.5.11.  After upgrading to 8.5.5.12 I was able to add security constraints in the web.xml for folders that were in the extended document root.

I have also tested this in Websphere 9.0.0.5 and everything worked as it should.

Body:
We are using Websphere 8.5.5 Traditional

I have added an extended document root to Websphere's ibm-web-ext.xml file and set file sharing to true.

<fileServingAttribute name="extendedDocumentRoot" value="C:/extdocroot"/>
<enable-file-serving value="true"/>

inside the extended document root folder (C:/extdocroot) is a folder called pdfs. I would like to restrict the pdfs folder to only users who have logged in and have a particular role of 'school'.

the URL to serve up the pdf's is https://domain-name:9080/context-path/pdf/pdf-name.pdf
I added a security constraint in the web.xml file

<security-constraint>
    <display-name>school PDFs</display-name>
    <web-resource-collection>
       <web-resource-name>School PDFs</web-resource-name>
       <url-pattern>/pdf/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
       <role-name>school</role-name>
    </auth-constraint>
</security-constraint>

No matter what role a user is logged in as the PDF's will get served by the the server. Websphere is ignoring the security constraint for the URL that serves up PDF's from the extended document root. Is it possible to constrain these PDF's by the roles a logged in user has.

Note: My company has asked me to try and put these files outside of the ear file and also have Websphere secure the files using user's role. I was also instructed not to use the Apache HTTP Server to host these files since it is in the DMZ.


问:
PHP while command missing first entry

I am trying to use the while loop to print multiple entries from a MySQL database. Everywhere I do this it is missing the first item on the list and only manages to print from the second one on. </p>

```<code><?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>View</title>
        <link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">
    </head>
    <body>
        <div class="header">
            <h2>Results.</h2>
            <form action="watch.php" method='POST'><table>
                <?php
                    if($result->num_rows > 0){
                        while($row = $result->fetch_assoc()){
                            $vid = $row['vid'];
                            $source = "uploads/".$row['file_name'];
                            echo "<tr><td>".$row['vid']."</td>
<td>".$row['file_name']."</td>";
                            echo "<td><a href=watch.php?
source=$source>Play</a></td></tr>";
                        }
                    }else{
                    echo "0 results";
                    }
                ?>
                </table></form>
            <a href="profile.php"><button class="button-block">Home</button></a>
        </div>
    </body>
</code>```

<p>

I'd like it to print all matching criteria.

I'm getting only the entries after the first one. </p>

答:
You missed a "}" at the end of your while loop, that might be a problem.. I also changed your >=1 of your num_rows conditions to > 0. Try this:</p>

```<code>if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $vid = $row['vid'];
        $source = "uploads/" . $row['file_name'];
        $htmlRow  = "<tr>\n";
        $htmlRow .= "<td>" . $row['vid'] . "</td>\n";
        $htmlRow .= "<td>" . $row['file_name'] . "</td>\n";
        $htmlRow .= "<td>" . $row['vid'] . "</td>\n";
        $htmlRow .= "<td><a href=\"watch.php?source=" . $source . "\">Play</a></td>\n";
        $htmlRow .= "</tr>\n";
        echo $htmlRow;
    }
}
</code>```

Title: PHP while command missing first entry

Body:
I am trying to use the while loop to print multiple entries from a MySQL database. Everywhere I do this it is missing the first item on the list and only manages to print from the second one on.

<?php
require 'db.php';
$udate = $mysqli->escape_string($_POST['date']);
$result = $mysqli->query("SELECT * FROM videos WHERE date='$udate'");
$user = $result->fetch_assoc();
$_SESSION['file_name'] = $user['file_name'];
?>
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>View</title>
        <link rel="stylesheet" type="text/css" href="css/nominatorstyle.css">

Results.

            <form action="watch.php" method='POST'>

                <?php
                    if($result->num_rows > 0){
                        while($row = $result->fetch_assoc()){
                            $vid = $row['vid'];
                            $source = "uploads/".$row['file_name'];
                            echo "
".$row['vid']."
".$row['file_name']."	";
                            echo "Play
";
                        }
                    }else{
                    echo "0 results";
                    }
                ?>

</form>
            <button class="button-block">Home</button>

I'd like it to print all matching criteria.

I'm getting only the entries after the first one.

Body:
You missed a "}" at the end of your while loop, that might be a problem.. I also changed your >=1 of your num_rows conditions to > 0. Try this:

if($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $vid = $row['vid'];
        $source = "uploads/" . $row['file_name'];
        $htmlRow  = "<tr>\n";
        $htmlRow .= "<td>" . $row['vid'] . "</td>\n";
        $htmlRow .= "<td>" . $row['file_name'] . "</td>\n";
        $htmlRow .= "<td>" . $row['vid'] . "</td>\n";
        $htmlRow .= "<td><a href=\"watch.php?source=" . $source . "\">Play</a></td>\n";
        $htmlRow .= "</tr>\n";
        echo $htmlRow;
    }
}


问:
The device GattServer stops advertising after connecting to it
This is the link to the GATT Server sample for Android Things on GitHub:

https://github.com/androidthings/sample-bluetooth-le-gattserver

Setting up the server on RPi-3 is easy enough.

What I do not understand is why the GATT server stops advertising once you have connected to then disconnected from the device (BLE connect).

```<code>...gattserver I/GattServerActivity: BluetoothDevice CONNECTED: 67:2F:1A:B4:1F:86
...gattserver D/BluetoothGattServer: onConnectionUpdated() - Device=67:2F:1A:B4:1F:86 interval=6 latency=0 timeout=2000 status=0
...gattserver D/BluetoothGattServer: onConnectionUpdated() - Device=67:2F:1A:B4:1F:86 interval=39 latency=0 timeout=2000 status=0
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver D/GattServerActivity: Config descriptor read
...gattserver I/GattServerActivity: Read LocalTimeInfo
...gattserver D/BluetoothGattServer: onServerConnectionState() - status=0 serverIf=5 device=67:2F:1A:B4:1F:86
...gattserver I/GattServerActivity: BluetoothDevice DISCONNECTED: 67:2F:1A:B4:1F:86
...gattserver I/GattServerActivity: No subscribers registered
</code>```

The above is what shows in the LogCat for the device.
First line shows that my phone was able to connect to the device.
(using this free and excellent app: https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp )

When connected I can read it's characteristics (Read CurrentType, Read LocalTimeInfo etc.)

When disconnecting the phone/app from the device the GattServerActivity states that I disconnected with grace and keeps on running...

But trying to scan for devices from the phone/app again reveals that the GATT Server on the RPi has gone zombie...

No errors in the LogCat (not in app, not in system)...

Thoughts anyone?

答: The issue seems to be that the GATT server doesn't start advertising again on disconnection? You should be able to add a new line here to start advertising again.</p>

Body:
This is the link to the GATT Server sample for Android Things on GitHub:

https://github.com/androidthings/sample-bluetooth-le-gattserver

Setting up the server on RPi-3 is easy enough.

What I do not understand is why the GATT server stops advertising once you have connected to then disconnected from the device (BLE connect).

...gattserver I/GattServerActivity: BluetoothDevice CONNECTED: 67:2F:1A:B4:1F:86
...gattserver D/BluetoothGattServer: onConnectionUpdated() - Device=67:2F:1A:B4:1F:86 interval=6 latency=0 timeout=2000 status=0
...gattserver D/BluetoothGattServer: onConnectionUpdated() - Device=67:2F:1A:B4:1F:86 interval=39 latency=0 timeout=2000 status=0
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver I/GattServerActivity: Read CurrentTime
...gattserver D/GattServerActivity: Config descriptor read
...gattserver I/GattServerActivity: Read LocalTimeInfo
...gattserver D/BluetoothGattServer: onServerConnectionState() - status=0 serverIf=5 device=67:2F:1A:B4:1F:86
...gattserver I/GattServerActivity: BluetoothDevice DISCONNECTED: 67:2F:1A:B4:1F:86
...gattserver I/GattServerActivity: No subscribers registered

The above is what shows in the LogCat for the device.
First line shows that my phone was able to connect to the device.
(using this free and excellent app: https://play.google.com/store/apps/details?id=no.nordicsemi.android.mcp )

When connected I can read it's characteristics (Read CurrentType, Read LocalTimeInfo etc.)

When disconnecting the phone/app from the device the GattServerActivity states that I disconnected with grace and keeps on running...

But trying to scan for devices from the phone/app again reveals that the GATT Server on the RPi has gone zombie...

No errors in the LogCat (not in app, not in system)...

Thoughts anyone?


问:
rails - REGEX for email validation
I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

```<code>def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end
</code>```

Problem with the above is XXX_XXX@Xxx.com does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

答:
Here's an email regex that I've been using for a while:

```<code>\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b
</code>```

It's from here

Title: rails - REGEX for email validation

Body:
I'm looking for a regex to validate an email to learn if it's valid or not.. I have the following:

def is_a_valid_email?(email)
    email_regex = %r{
      ^ # Start of string
      [0-9a-z] # First character
      [0-9a-z.+]+ # Middle characters
      [0-9a-z] # Last character
      @ # Separating @ character
      [0-9a-z] # Domain name begin
      [0-9a-z.-]+ # Domain name middle
      [0-9a-z] # Domain name end
      $ # End of string
    }xi # Case insensitive

    (email =~ email_regex)
end

Problem with the above is XXX_XXX@Xxx.com does not return as valid when it should be. Any thoughts or suggestions for a better regex?

Thanks

Body:
Here's an email regex that I've been using for a while:

\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b

It's from here


问:
Find 2D array max and min
This is the original prompt:

Find the maximum value and minimum value in milesTracker. Assign the maximum value to maxMiles, and the minimum value to minMiles. Sample output for the given program:

```<code>Min miles: -10
Max miles: 40
</code>```

Here is my code:

```<code>import java.util.Scanner;

public class ArraysKeyValue {
  public static void main (String [] args) {
    final int NUM_ROWS = 2;
    final int NUM_COLS = 2;
    int [][] milesTracker = new int[NUM_ROWS][NUM_COLS];
    int i = 0;
    int j = 0;
    int maxMiles = 0;
    int minMiles = 0;

    milesTracker[0][0] = -10;
    milesTracker[0][1] = 20;
    milesTracker[1][0] = 30;
    milesTracker[1][1] = 40;

    for(i=0;i<NUM_ROWS;++i) {

       for(j=0;j<NUM_COLS;++j) {

          if (milesTracker[i][j]<minMiles){
              minMiles = milesTracker[i][j];
          }
          else if (milesTracker[i][j] > maxMiles){
              maxMiles = milesTracker[i][j];
          }
       }
    }

    System.out.println("Min miles: " + minMiles);
    System.out.println("Max miles: " + maxMiles);
  }
}
</code>```

Here is the output:

```<code>  Testing with milesTracker = {{-10, 20}, {30, 40}}
</code>```

Your output:

```<code>Min miles: -10
Max miles: 40

   Testing with milesTracker = {{73, 0}}
</code>```

Your output:

```<code>Min miles: 0
Max miles: 73

✖   Testing with milesTracker = {{-5}, {-93}, {-259}}
</code>```

Expected output:

```<code>Min miles: -259
Max miles: -5
</code>```

Your output:

```<code>Min miles: -259
Max miles: 0
</code>```

Why is the last test failing?

答:
The answer of @Filkolev is  really good, but you can be even shorter: </p>

```<code>//The solution requires students to initialize max_miles (or maxMiles) or and min_miles (or minMiles) before writing their nested for loop.
maxMiles = milesTracker[0][0];
minMiles = milesTracker[0][0];

//loops
for (i = 0; i <NUM_ROWS; ++i) {
    for (j = 0; j < NUM_COLS; ++j) {
        if (milesTracker[i][j] > maxMiles) {
            maxMiles = milesTracker[i][j];
        }
        else {
            minMiles = milesTracker[i][j];
        }
    }
}
</code>```

Title: Find 2D array max and min

Body:
This is the original prompt:

Find the maximum value and minimum value in milesTracker. Assign the maximum value to maxMiles, and the minimum value to minMiles. Sample output for the given program:

Min miles: -10
Max miles: 40

Here is my code:

import java.util.Scanner;

public class ArraysKeyValue {
  public static void main (String [] args) {
    final int NUM_ROWS = 2;
    final int NUM_COLS = 2;
    int [][] milesTracker = new int[NUM_ROWS][NUM_COLS];
    int i = 0;
    int j = 0;
    int maxMiles = 0;
    int minMiles = 0;

    milesTracker[0][0] = -10;
    milesTracker[0][1] = 20;
    milesTracker[1][0] = 30;
    milesTracker[1][1] = 40;

    for(i=0;i<NUM_ROWS;++i) {

       for(j=0;j<NUM_COLS;++j) {

          if (milesTracker[i][j]<minMiles){
              minMiles = milesTracker[i][j];
          }
          else if (milesTracker[i][j] > maxMiles){
              maxMiles = milesTracker[i][j];
          }
       }
    }

    System.out.println("Min miles: " + minMiles);
    System.out.println("Max miles: " + maxMiles);
  }
}

Here is the output:

  Testing with milesTracker = {{-10, 20}, {30, 40}}

Your output:

Min miles: -10
Max miles: 40

   Testing with milesTracker = {{73, 0}}

Your output:

Min miles: 0
Max miles: 73

✖   Testing with milesTracker = {{-5}, {-93}, {-259}}

Expected output:

Min miles: -259
Max miles: -5

Your output:

Min miles: -259
Max miles: 0

Why is the last test failing?

Body:
The answer of @Filkolev is  really good, but you can be even shorter:

//The solution requires students to initialize max_miles (or maxMiles) or and min_miles (or minMiles) before writing their nested for loop.
maxMiles = milesTracker[0][0];
minMiles = milesTracker[0][0];

//loops
for (i = 0; i <NUM_ROWS; ++i) {
    for (j = 0; j < NUM_COLS; ++j) {
        if (milesTracker[i][j] > maxMiles) {
            maxMiles = milesTracker[i][j];
        }
        else {
            minMiles = milesTracker[i][j];
        }
    }
}


问:
how to manipulate string column of numbers separated by dots using t-sql
I have a column of nvarchar(255) type that represents software version
numbers:

```<code>  VersionNumber
 ---------------

    1.0.0.505
    1.0.0.506
    1.0.0.507
    1.0.0.508
    1.0.0.509
    1.0.1.2
</code>```

I need to extract the maximum version number (the min version number in the example above is 1.0.0.505 and the max version number is 1.0.1.2, values arranged from the smallest to the highest).

in order to explain exactly what i need - if i could use imperative programming language i think i would do something like that to detect the max version number:

lets say version number is d.c.b.a.

i would separate each version number to four different variables: a b
c d

that i will sum each series.

a will be summed by tens

b will be summed by hundreds

c will be summed by thousands

d will be summed by milions

than the maximum total sum of each Max(a+b+c+d) will be the max version.

but what is the technic to achieve something like that in sql?

答:
try this </p>

```<code>select max(replace(version,'.','')) from yourtable
</code>```

Body:
I have a column of nvarchar(255) type that represents software version
numbers:

  VersionNumber
 ---------------

    1.0.0.505
    1.0.0.506
    1.0.0.507
    1.0.0.508
    1.0.0.509
    1.0.1.2

I need to extract the maximum version number (the min version number in the example above is 1.0.0.505 and the max version number is 1.0.1.2, values arranged from the smallest to the highest).

in order to explain exactly what i need - if i could use imperative programming language i think i would do something like that to detect the max version number:

lets say version number is d.c.b.a.

i would separate each version number to four different variables: a b
c d

that i will sum each series.

a will be summed by tens

b will be summed by hundreds

c will be summed by thousands

d will be summed by milions

than the maximum total sum of each Max(a+b+c+d) will be the max version.

but what is the technic to achieve something like that in sql?

Body:
try this

select max(replace(version,'.','')) from yourtable


问:
How does a router use the routing table to choose the outgoing line?
How does a router know which is the best line on which to send packets. I mean, the routing table most often does not contain the entry for the destination network number of the IP packet. It only knows the destinations adjacent to it or nearby. It does not know if the address exists or not. Say I make a request for stackoverflow.com to my LAN proxy. Next it sends the request to a router. How is it that the packet is transported all the way to a server in the US using an optimal path seeing that that router knows only nearby addresses?
Thank you in advance...</p>

答:
A router has a list of IP address/netmask pairs for each interface.  Anything that is destined for that network will be sent directly on that network.

Anything farther away will be listed under a "next-hop" router.  Your router will forward the packet to the next-hop router, using the appropriate local interface.

If the router doesn't have a map for the given destination, it will instead be sent to the default "next-hop".  This is the default for your local computer or for a home router/firewall combination.


问:
How to get count by combining more than 2 tables in mysql
i have a table 'A' with status column, it can have 4 values. In table A i have table 'B's id, table B have table 'C's id. I want to get the status count FROM table 'A' by joining all these columns. The status column in table A is a foreign  key from table 'D'. Table 'D' having status like 1-agreed, 2-not agreed etc</p>

答:
The question is missing some information that might be helpful.  Particularly, what exactly you are wanting to count. (i.e. are you just trying to count ALL rows, or are you trying to count the number of rows in table A that have each status).  I'll put together an answer that assumes that latter.

I'll also just assume that "id" is the primary key of its own table, and that id will be the id from other tables inside a table.

```<code>select A.statusField, count(*)
from A
join B on (A.Bid = B.id)
join C on (B.Cid = C.id)
group by A.statusField
</code>```

Hope that helps.

Body:
The question is missing some information that might be helpful.  Particularly, what exactly you are wanting to count. (i.e. are you just trying to count ALL rows, or are you trying to count the number of rows in table A that have each status).  I'll put together an answer that assumes that latter.

I'll also just assume that "id" is the primary key of its own table, and that id will be the id from other tables inside a table.

select A.statusField, count(*)
from A
join B on (A.Bid = B.id)
join C on (B.Cid = C.id)
group by A.statusField

Hope that helps.