问:
FabricJS on('object:selected') doesn't trigger consistently for lines
I am currently  building a simple line drawing tool using FabricJs and canvas.

DRAW mode:  Draw lines using the mouse

DELETE mode:  Click anywhere a line to delete it. Using the fabric js   on('object:selected')

My issue is that DELETE mode is inconsistent,
Clicking on the top half deletes the line, clicking on the bottom half doesn't do anything.

Am I missing something? I have tried everything.

Thanks for the help.

EDIT: ADDED snippet

var isDrawing = true;
var canvas = new fabric.Canvas('a', {
  selection: false
});

var grid = 30;

// create grid
//line
var line, isDown;

function createGrid(board) {
  for (var i = 0; i < (600 / grid); i++) {
    board.add(new fabric.Line([i * grid, 0, i * grid, 600], {
      stroke: '#000',
      selectable: false
    }));
    board.add(new fabric.Line([0, i * grid, 600, i * grid], {
      stroke: '#000',
      selectable: false
    }))
  }
}
//create grids
createGrid(canvas);

//Button Toggle

$("#draw").click(function() {
  isDrawing = true;
  DrawLine(canvas);
});
$("#erase").click(function() {
  isDrawing = false;
  EraseLine(canvas);
});

function DrawLine(board) {

  // add objects
  board.on('mouse:down', function(o) {

    isDown = true;
    var pointer = board.getPointer(o.e);
    var points = [Math.round(pointer.x / grid) * grid, Math.round(pointer.y / grid) * grid, pointer.x, pointer.y];
    line = new fabric.Line(points, {
      strokeWidth: 5,
      strokeDashArray: [5, 10],
      strokeLineCap: 'round',
      fill: '#005E7A',
      stroke: '#005E7A',
      originX: 'center',
      originY: 'center',
      hasControls: 'false',
      hasRotatingPoint: 'false',
      padding: 50,
      ///perPixelTargetFind: true,
      lockMovementX: true,
      lockMovementY: true,

    });
    line.setOptions({
      'selectable': false
    });
    board.add(line);
  });

  board.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = board.getPointer(o.e);
    line.set({
      x2: pointer.x,
      y2: pointer.y
    });
    board.renderAll();
  });

  board.on('mouse:up', function(o) {
    var pointer = board.getPointer(o.e);
    isDown = false;
    line.set({
      x2: Math.round(pointer.x / grid) * grid,
      y2: Math.round(pointer.y / grid) * grid
    });
    board.renderAll();
  });

}

function EraseLine(board) {

  board.off();

  line.setOptions({
    'selectable': true
  });
  var eraseHandler = function(o) {
    console.log(o);

    board.remove(o.target);

  };

  board.on('object:selected', eraseHandler);
  board.renderAll();

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
  border: 2px solid #ccc;
  padding-left: 0;
}

.boards {
  display: inline;
  padding-left: 0;
}

.boards canvas {
  list-style: none;
  display: inline-block;
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
}</code>```

Fabric Js On selected mode

  <canvas id="a" width="120" height="240"></canvas>

  <button id="draw">
        Draw MOde
        </button>
  <button id="erase">
       Erase Mode
        </button>```

答:
var isDrawing = true;
var canvas = new fabric.Canvas('a', {
  selection: false
});

var grid = 30;

// create grid
//line
var line, isDown;

function createGrid(board) {
  for (var i = 0; i < (600 / grid); i++) {
    board.add(new fabric.Line([i * grid, 0, i * grid, 600], {
      stroke: '#000',
      selectable: false
    }));
    board.add(new fabric.Line([0, i * grid, 600, i * grid], {
      stroke: '#000',
      selectable: false
    }))
  }
}
//create grids
createGrid(canvas);

//Button Toggle

$("#draw").click(function() {
  isDrawing = true;
  DrawLine(canvas);
});
$("#erase").click(function() {
  isDrawing = false;
  EraseLine(canvas);
});

function DrawLine(board) {
  canvas.forEachObject(function(obj){
   obj.selectable = false;
  })
  // add objects
  board.on('mouse:down', function(o) {

    isDown = true;
    var pointer = board.getPointer(o.e);
    var points = [Math.round(pointer.x / grid) * grid, Math.round(pointer.y / grid) * grid, pointer.x, pointer.y];
    line = new fabric.Line(points, {
      strokeWidth: 5,
      strokeDashArray: [5, 10],
      strokeLineCap: 'round',
      fill: '#005E7A',
      stroke: '#005E7A',
      originX: 'center',
      originY: 'center',
      hasControls: 'false',
      hasRotatingPoint: 'false',
      padding: 50,
      ///perPixelTargetFind: true,
      lockMovementX: true,
      lockMovementY: true,
      selectable: false

    });
    board.add(line);
  });

  board.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = board.getPointer(o.e);
    line.set({
      x2: pointer.x,
      y2: pointer.y
    });
    board.renderAll();
  });

  board.on('mouse:up', function(o) {
    var pointer = board.getPointer(o.e);
    isDown = false;
    line.set({
      x2: Math.round(pointer.x / grid) * grid,
      y2: Math.round(pointer.y / grid) * grid
    });
    line.setCoords();
    board.renderAll();
  });

}

function EraseLine(board) {

  board.off();

  line.setOptions({
    'selectable': true
  });
  canvas.forEachObject(function(obj){
   obj.selectable = true;
  })
  canvas.renderAll();
  var eraseHandler = function(o) {
    board.remove(o.target);
  };

  board.on('object:selected', eraseHandler);

}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
  border: 2px solid #ccc;
  padding-left: 0;
}

.boards {
  display: inline;
  padding-left: 0;
}

.boards canvas {
  list-style: none;
  display: inline-block;
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
}</code>```

Fabric Js On selected mode

  <canvas id="a" width="120" height="240"></canvas>

  <button id="draw">
        Draw MOde
        </button>
  <button id="erase">
       Erase Mode
        </button>```

use line.setCoords(); to set coordinate after setting line points.

Body:
I am currently  building a simple line drawing tool using FabricJs and canvas.

DRAW mode:  Draw lines using the mouse

DELETE mode:  Click anywhere a line to delete it. Using the fabric js   on('object:selected')

My issue is that DELETE mode is inconsistent,
Clicking on the top half deletes the line, clicking on the bottom half doesn't do anything.

Am I missing something? I have tried everything.

Thanks for the help.

EDIT: ADDED snippet

var isDrawing = true;
var canvas = new fabric.Canvas('a', {
  selection: false
});

var grid = 30;

// create grid
//line
var line, isDown;

function createGrid(board) {
  for (var i = 0; i < (600 / grid); i++) {
    board.add(new fabric.Line([i * grid, 0, i * grid, 600], {
      stroke: '#000',
      selectable: false
    }));
    board.add(new fabric.Line([0, i * grid, 600, i * grid], {
      stroke: '#000',
      selectable: false
    }))
  }
}
//create grids
createGrid(canvas);

//Button Toggle

$("#draw").click(function() {
  isDrawing = true;
  DrawLine(canvas);
});
$("#erase").click(function() {
  isDrawing = false;
  EraseLine(canvas);
});

function DrawLine(board) {

  // add objects
  board.on('mouse:down', function(o) {

    isDown = true;
    var pointer = board.getPointer(o.e);
    var points = [Math.round(pointer.x / grid) * grid, Math.round(pointer.y / grid) * grid, pointer.x, pointer.y];
    line = new fabric.Line(points, {
      strokeWidth: 5,
      strokeDashArray: [5, 10],
      strokeLineCap: 'round',
      fill: '#005E7A',
      stroke: '#005E7A',
      originX: 'center',
      originY: 'center',
      hasControls: 'false',
      hasRotatingPoint: 'false',
      padding: 50,
      ///perPixelTargetFind: true,
      lockMovementX: true,
      lockMovementY: true,

    });
    line.setOptions({
      'selectable': false
    });
    board.add(line);
  });

  board.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = board.getPointer(o.e);
    line.set({
      x2: pointer.x,
      y2: pointer.y
    });
    board.renderAll();
  });

  board.on('mouse:up', function(o) {
    var pointer = board.getPointer(o.e);
    isDown = false;
    line.set({
      x2: Math.round(pointer.x / grid) * grid,
      y2: Math.round(pointer.y / grid) * grid
    });
    board.renderAll();
  });

}

function EraseLine(board) {

  board.off();

  line.setOptions({
    'selectable': true
  });
  var eraseHandler = function(o) {
    console.log(o);

    board.remove(o.target);

  };

  board.on('object:selected', eraseHandler);
  board.renderAll();

}

canvas {
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
  border: 2px solid #ccc;
  padding-left: 0;
}

.boards {
  display: inline;
  padding-left: 0;
}

.boards canvas {
  list-style: none;
  display: inline-block;
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
}

Fabric Js On selected mode

  <canvas id="a" width="120" height="240"></canvas>

  <button id="draw">
        Draw MOde
        </button>
  <button id="erase">
       Erase Mode
        </button>

Body:
var isDrawing = true;
var canvas = new fabric.Canvas('a', {
  selection: false
});

var grid = 30;

// create grid
//line
var line, isDown;

function createGrid(board) {
  for (var i = 0; i < (600 / grid); i++) {
    board.add(new fabric.Line([i * grid, 0, i * grid, 600], {
      stroke: '#000',
      selectable: false
    }));
    board.add(new fabric.Line([0, i * grid, 600, i * grid], {
      stroke: '#000',
      selectable: false
    }))
  }
}
//create grids
createGrid(canvas);

//Button Toggle

$("#draw").click(function() {
  isDrawing = true;
  DrawLine(canvas);
});
$("#erase").click(function() {
  isDrawing = false;
  EraseLine(canvas);
});

function DrawLine(board) {
  canvas.forEachObject(function(obj){
   obj.selectable = false;
  })
  // add objects
  board.on('mouse:down', function(o) {

    isDown = true;
    var pointer = board.getPointer(o.e);
    var points = [Math.round(pointer.x / grid) * grid, Math.round(pointer.y / grid) * grid, pointer.x, pointer.y];
    line = new fabric.Line(points, {
      strokeWidth: 5,
      strokeDashArray: [5, 10],
      strokeLineCap: 'round',
      fill: '#005E7A',
      stroke: '#005E7A',
      originX: 'center',
      originY: 'center',
      hasControls: 'false',
      hasRotatingPoint: 'false',
      padding: 50,
      ///perPixelTargetFind: true,
      lockMovementX: true,
      lockMovementY: true,
      selectable: false

    });
    board.add(line);
  });

  board.on('mouse:move', function(o) {
    if (!isDown) return;
    var pointer = board.getPointer(o.e);
    line.set({
      x2: pointer.x,
      y2: pointer.y
    });
    board.renderAll();
  });

  board.on('mouse:up', function(o) {
    var pointer = board.getPointer(o.e);
    isDown = false;
    line.set({
      x2: Math.round(pointer.x / grid) * grid,
      y2: Math.round(pointer.y / grid) * grid
    });
    line.setCoords();
    board.renderAll();
  });

}

function EraseLine(board) {

  board.off();

  line.setOptions({
    'selectable': true
  });
  canvas.forEachObject(function(obj){
   obj.selectable = true;
  })
  canvas.renderAll();
  var eraseHandler = function(o) {
    board.remove(o.target);
  };

  board.on('object:selected', eraseHandler);

}

canvas {
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
  border: 2px solid #ccc;
  padding-left: 0;
}

.boards {
  display: inline;
  padding-left: 0;
}

.boards canvas {
  list-style: none;
  display: inline-block;
  background-color: transparent;
  margin: 3px;
  width: 120px;
  height: 240px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type='text/javascript' src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.js"></script>
<h1>Fabric Js On selected mode </h1>
<div class="boards">
  <canvas id="a" width="120" height="240"></canvas>
  <br>
  <button id="draw">
        Draw MOde
        </button>
  <button id="erase">
       Erase Mode
        </button>

use line.setCoords(); to set coordinate after setting line points.


来源: stackexchange

问:
How do I allow access to the docker container on an EC2 instance
I have a build process that looks like this:

1. Code Pushed to BitBucket which is picked up by BitBucker Pipelines

```<code>image: node:8.2.1
pipelines:
  default:
    - step:
        name: Push Server to AWS Repository
        script:
          - docker login -u AWS -p $AWS_ECR_LOGIN https://$AWS_ECR_URL
          - docker build -t dev .
          - docker tag dev:latest $AWS_ECR_URL/dev:latest
          - docker push $AWS_ECR_URL/dev:latest

options:
  docker: true
</code>```

2. BitBucket Pipelines Builds the Docker Image from the Dockerfile in the repo and pushes it to Amazon ECR

```<code># BUILD DEV IMAGE and TEST
FROM node:8.2.1 as builder
COPY ./ /user/src/app
WORKDIR /user/src/app
RUN npm install -g grunt-cli --quiet
RUN npm install --quiet
RUN grunt build
# RUN npm test:build

# BUILD APP IMAGE
FROM node:8.2.1
COPY --from=builder /user/src/app/dist /user/src/app/
WORKDIR /user/src/app
RUN npm install -g mongodb-migrations --quiet
RUN npm install --only=prod --quiet
EXPOSE 5000
CMD npm start
</code>```

3. Jenkins job watches for the new images in ECR and remotely triggers an EC2 instance to pull and restart the docker image

```<code>let dockerApi = new Docker({
    host: DockerIpAddress,
    port: process.env.DOCKER_PORT || 2375,
    version: 'v1.32' // required when Docker >= v1.13, https://docs.docker.com/engine/api/version-history/
});

dockerApi.createContainer({
    Image: IMAGE_NAME,
    AttachStdout: true,
    AttachStderr: true,
    Tty: true,
    Env: [`NODE_ENV=${ENV}`],
    ExposedPorts: {
        "5000/tcp": {},
    },
    HostConfig:{
        PortBindings: {
            "5000/tcp": [{
                "HostPort": "5000"
            }],
        },
    },
})
</code>```

Problem

Up until this point - everything is working! My docker container is running on the ec2 instance. What's not working is that I can't receive any connections. Even from ssh'd into the ec2 instance, curl http://localhost:5000 won't work. Accessing the ec2 instance from a browser via the public ip or public host doesn't work either.

IP Tables

```<code>Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             ip-172-17-0-2.ec2.internal  tcp dpt:5000

Chain DOCKER-ISOLATION (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere
</code>```

Sysctl

```<code>$ sysctl net.ipv4.conf.all.forwarding
net.ipv4.conf.all.forwarding = 1
</code>```

Node Server in Docker Last Line of Output

```<code>Server running at: http://localhost:5000
</code>```

答:
Check that the Dockerfile you're using for creating the image runs a script which expose the server in 0.0.0.0 and not in localhost.

You should be opening 0.0.0.0:5000->5000 and not run in localhost!!

Hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I have a build process that looks like this:

1. Code Pushed to BitBucket which is picked up by BitBucker Pipelines

image: node:8.2.1
pipelines:
  default:
    - step:
        name: Push Server to AWS Repository
        script:
          - docker login -u AWS -p $AWS_ECR_LOGIN https://$AWS_ECR_URL
          - docker build -t dev .
          - docker tag dev:latest $AWS_ECR_URL/dev:latest
          - docker push $AWS_ECR_URL/dev:latest

options:
  docker: true

2. BitBucket Pipelines Builds the Docker Image from the Dockerfile in the repo and pushes it to Amazon ECR

# BUILD DEV IMAGE and TEST
FROM node:8.2.1 as builder
COPY ./ /user/src/app
WORKDIR /user/src/app
RUN npm install -g grunt-cli --quiet
RUN npm install --quiet
RUN grunt build
# RUN npm test:build

# BUILD APP IMAGE
FROM node:8.2.1
COPY --from=builder /user/src/app/dist /user/src/app/
WORKDIR /user/src/app
RUN npm install -g mongodb-migrations --quiet
RUN npm install --only=prod --quiet
EXPOSE 5000
CMD npm start

3. Jenkins job watches for the new images in ECR and remotely triggers an EC2 instance to pull and restart the docker image

let dockerApi = new Docker({
    host: DockerIpAddress,
    port: process.env.DOCKER_PORT || 2375,
    version: 'v1.32' // required when Docker >= v1.13, https://docs.docker.com/engine/api/version-history/
});

dockerApi.createContainer({
    Image: IMAGE_NAME,
    AttachStdout: true,
    AttachStderr: true,
    Tty: true,
    Env: [`NODE_ENV=${ENV}`],
    ExposedPorts: {
        "5000/tcp": {},
    },
    HostConfig:{
        PortBindings: {
            "5000/tcp": [{
                "HostPort": "5000"
            }],
        },
    },
})

Problem

Up until this point - everything is working! My docker container is running on the ec2 instance. What's not working is that I can't receive any connections. Even from ssh'd into the ec2 instance, curl http://localhost:5000 won't work. Accessing the ec2 instance from a browser via the public ip or public host doesn't work either.

IP Tables

Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy DROP)
target     prot opt source               destination
DOCKER-ISOLATION  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             ip-172-17-0-2.ec2.internal  tcp dpt:5000

Chain DOCKER-ISOLATION (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

Sysctl

$ sysctl net.ipv4.conf.all.forwarding
net.ipv4.conf.all.forwarding = 1

Node Server in Docker Last Line of Output

Server running at: http://localhost:5000


问:
Excluding query result with in and not in
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

```<code>SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate
</code>```

Results:

```<code>CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000
</code>```

答:
You can use a combination of IN and NOT EXISTS.

If I use your example output, for example:

```<code>--Your sample output
DECLARE @Person TABLE (BusinessEntityID int, FirstName varchar(100), LastName varchar(100))
DECLARE @Sales TABLE (OrderID int IDENTITY(1,1),CustomerID int, OrderDate date)

INSERT INTO @Person VALUES (11001, 'Amber', 'Young'),(11017, 'Chloe', 'Clark')
                          ,(11018, 'Joe', 'Mehta')

INSERT INTO @Sales (CustomerID, OrderDate)
VALUES (11001, '2014-03-26'),(11001, '2013-06-18'),(11001, '2011-06-18')
      ,(11017, '2014-03-16'),(11017, '2013-06-03'),(11017, '2011-06-14')
      ,(11001, '2014-05-12'),(11001, '2013-06-18'),(11001, '2011-06-17')

SELECT DISTINCT S.CustomerID, P.LastName, P.FirstName
  FROM @Sales S INNER JOIN @Person P ON S.CustomerID = P.BusinessEntityID
 WHERE YEAR(S.OrderDate) IN (2011, 2014)
   AND NOT EXISTS (SELECT *
                     FROM @Sales S2
                    WHERE S2.CustomerID = S.CustomerID
                      AND YEAR(S.OrderDate) IN (2012, 2013)
                  )
</code>```

Produces output:

```<code>CustomerID  LastName    FirstName   OrderDate
11001       Young       Amber       2011-06-17
11001       Young       Amber       2011-06-18
11001       Young       Amber       2014-03-26
11001       Young       Amber       2014-05-12
11017       Clark       Chloe       2011-06-14
11017       Clark       Chloe       2014-03-16
</code>```

Body:
I have two tables:

Person (BusinessEntityID, FirstName, LastName)

Sales (OrderID, CustomerID, OrderDate)

I want to list people that made orders both in 2011 and 2014 but never made orders in 2012 and 2013

I would expect this query to work, but it is still listing orders in 2013

SELECT
    s.CustomerID,p.LastName,p.FirstName, s.OrderDate
FROM
    Sales.SalesOrderHeader s,Person.Person p
WHERE
    s.CustomerID = p.BusinessEntityID
    AND s.CustomerID IN (SELECT CustomerID
                         FROM Sales.SalesOrderHeader
                         WHERE YEAR(OrderDate) IN (2011, 2014)
                         GROUP BY CustomerID
                         HAVING COUNT(CustomerID) > 1)
    AND s.CustomerID NOT IN (SELECT CustomerID
                             FROM Sales.SalesOrderHeader
                             WHERE YEAR(OrderDate) IN (2012, 2013)
                             GROUP BY CustomerID
                             HAVING COUNT(CustomerID) > 1)
GROUP BY
    s.CustomerID, p.LastName, p.FirstName, s.OrderDate

Results:

CustomerID     LastName    FirstName    OrderDate
---------------------------------------------------------------
11001          Young       Amber        2011-06-17 00:00:00.000
11001          Young       Amber        2013-06-18 00:00:00.000
11001          Young       Amber        2014-05-12 00:00:00.000
11017          Clark       Chloe        2011-06-14 00:00:00.000
11017          Clark       Chloe        2013-06-03 00:00:00.000
11017          Clark       Chloe        2014-03-16 00:00:00.000
11018          Mehta       Joe          2011-06-19 00:00:00.000
11018          Mehta       Joe          2013-06-18 00:00:00.000
11018          Mehta       Joe          2014-03-26 00:00:00.000

Body:
You can use a combination of IN and NOT EXISTS.

If I use your example output, for example:

--Your sample output
DECLARE @Person TABLE (BusinessEntityID int, FirstName varchar(100), LastName varchar(100))
DECLARE @Sales TABLE (OrderID int IDENTITY(1,1),CustomerID int, OrderDate date)

INSERT INTO @Person VALUES (11001, 'Amber', 'Young'),(11017, 'Chloe', 'Clark')
                          ,(11018, 'Joe', 'Mehta')

INSERT INTO @Sales (CustomerID, OrderDate)
VALUES (11001, '2014-03-26'),(11001, '2013-06-18'),(11001, '2011-06-18')
      ,(11017, '2014-03-16'),(11017, '2013-06-03'),(11017, '2011-06-14')
      ,(11001, '2014-05-12'),(11001, '2013-06-18'),(11001, '2011-06-17')

SELECT DISTINCT S.CustomerID, P.LastName, P.FirstName
  FROM @Sales S INNER JOIN @Person P ON S.CustomerID = P.BusinessEntityID
 WHERE YEAR(S.OrderDate) IN (2011, 2014)
   AND NOT EXISTS (SELECT *
                     FROM @Sales S2
                    WHERE S2.CustomerID = S.CustomerID
                      AND YEAR(S.OrderDate) IN (2012, 2013)
                  )

Produces output:

CustomerID  LastName    FirstName   OrderDate
11001       Young       Amber       2011-06-17
11001       Young       Amber       2011-06-18
11001       Young       Amber       2014-03-26
11001       Young       Amber       2014-05-12
11017       Clark       Chloe       2011-06-14
11017       Clark       Chloe       2014-03-16


问:
How to 'queue' piece of code in javascript
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

```<code>  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }
</code>```

答:
Timeouts are not the way to solve this problem.

You want to set up a callback function alongside the request so that the object handling the request knows what to do when the response comes in.

It is unclear from your code what framework you're using (I can't make any sense of getBlueprint, which seems to be the call that initializes the remote request), so if you could provide more information on this, we can provide more customized help.

ContentLicense: CC BY-SA 2.5

Body:
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }


问:
Xcode 9 - "Fixed Width Constraints May Cause Clipping" and Other Localization Warnings
I downloaded the new Xcode and in Interface Builder I'm having a ton of problems with warnings that say things like:

Fixed Width Constraints May Cause Clipping

It looks like this:

I do have localization for several languages and I understand the warning that in another language a label's size may change, but my app doesn't have this problem. I ran and tested it in Xcode 8 yesterday, it was fine. I don't want to spend hours and hours adding pointless new constraints.

Any suggested solutions?

答:
I had the same problem, but when I changing to >= it automatically set the constant to 0, if I choose 60 for instance, the warning appears again. So I was in a loop with the problem.

I could fix embedding my Label in a View

```<code>Editor > Embed In > View
</code>```

In Label I set Top, Bottom, Leading and Trailing with constant = 0

In View I set the constraints that I was expecting before.

Body:
I had the same problem, but when I changing to >= it automatically set the constant to 0, if I choose 60 for instance, the warning appears again. So I was in a loop with the problem.

I could fix embedding my Label in a View

Editor > Embed In > View

In Label I set Top, Bottom, Leading and Trailing with constant = 0

In View I set the constraints that I was expecting before.


问:
ReactJS - Components - Best Practices
I'm relative new to react and I need to create a character counter component (CharacterCounter) for a input field.

This question is not specific to this component (character counter) - but is a generic question about components best practices in general.

I can implement in two ways (as far I know - if there are better ways I'm happy to hear about it):

1) Wrapping the component and have the input field as a child - The component will insert the span (for showing the counter) after the input field

```<code><CharacterCounter maxLength={50}>
    <input type="text">
  </CharacterCounter>
</code>```

and

```<code>const input = this.container.firstChild
input.addEventListener('keyup', function() { ... });
</code>```

advantage: I can have multiple components for the same input - if I need extra functionality (components) for this input.

disadvantage: If the input for some reason stop being the first child of this component - stop working/ fragile

2) To create a generic component which will render the input and the counter on the render() function

like:

```<code><CharacterCounter />

render() {
    return (
        <input type="text">
        <span>{this.state.count}</span>
    )
</code>```

advantage: Not fragile - not relying on the first child

disadvantage: Not sure is possible to have other component for the same input - let's say I need another component for tracking every time the user type/ or focus/ or blur the field

What is the best practices?

答:
Surely the second approach is better as it is not directly interfering with DOM elements.

If you wanted to have access to DOM elements, still it's better to use refs.

disadvantage: Not sure is possible to have other component for the
  same input - let's say I need another component for tracking every
  time the user type/ or focus/ or blur the field

You will get around that easily just with props.

Title: ReactJS - Components - Best Practices

Body:
I'm relative new to react and I need to create a character counter component (CharacterCounter) for a input field.

This question is not specific to this component (character counter) - but is a generic question about components best practices in general.

I can implement in two ways (as far I know - if there are better ways I'm happy to hear about it):

1) Wrapping the component and have the input field as a child - The component will insert the span (for showing the counter) after the input field

<CharacterCounter maxLength={50}>
    <input type="text">
  </CharacterCounter>

and

const input = this.container.firstChild
input.addEventListener('keyup', function() { ... });

advantage: I can have multiple components for the same input - if I need extra functionality (components) for this input.

disadvantage: If the input for some reason stop being the first child of this component - stop working/ fragile

2) To create a generic component which will render the input and the counter on the render() function

like:

<CharacterCounter />

render() {
    return (
        <input type="text">
        {this.state.count}
    )

advantage: Not fragile - not relying on the first child

disadvantage: Not sure is possible to have other component for the same input - let's say I need another component for tracking every time the user type/ or focus/ or blur the field

What is the best practices?


问:
Export named variable in foreach loop
I have a large data.table (+12M rows) that I need to convert this way :

Collapse each row with same first column value (let's call it BookId) into 1 row, and merge other columns into a big "data" field.
This table contains 2.7M unique BookId's

Ie :

```
BookId    Col1      Col2     ...      ColN
B001      Author    Bob      ...      ...
B002      Author    Marc     ...      ...
B002      Editor    Bob Inc  ...      ...
B001      Editor    MyBooks  ...      ...
```

Expeted result :

```BookId    data
B001      Bob,MyBooks, ...
B002      Marc,Bob Inc, ...
```

For now, I've been able to reproduce this structure using subsets, but this is really slow, it takes up to 300ms to build a row, which means it will take up to 9 days to achieve the process.

So I decided to use a parallel foreach loop to speed up the process.

My first approch was to loop over the bookId List, but it would only devide global overall time by the number of cores which is not satisfying (8 cores means +1 day). Also, that means each process will auto-export a very large amount of data as they all need the whole data.table object.

I found another approach to improve the process by splitting the primary data.table into independant subsets based on bookId list, then make each cluster works on that subsets (less rows means faster subsets generation).
Unfortunatly, I'm unable to export my subsets to clusters as they have a "dynamic" name.
I tried ".export" param but I guess it isn't aware of the current "i" value when evaluated.
How can I achieve this ? Is it even possible ?

I'm new to R, I have been told that there was always many ways to achieve the same thing, did I choose the best approach to achieve this ?

Here is my code :

```<code># Create cluster based on available cores
cores = detectCores()
cl <- makeCluster(cores)
registerDoParallel(cl)

# Load datas and generate BookId lists
books <- fread("books.tab")
bookId.unique.list <- unique(books$BookId)
bookId.list <- books$BookId

# Split datatable into "equals" subsets
subset.length = ceiling(length(book.unique.list)/cores)
for (i in 1:(cores)) {
    start = (i-1)*subset.length
    end = (i)*subset.length
    list = book.unique.list[start:end]
    assign(paste("books",i,sep=""), books[books$BookId %in% list])
    assign(paste("book.list",i,sep=""), list )
}

# Prepare resulting DT
res = data.table(BookId = character(0), data = character(0))

# Parallel loop
res  <- foreach(i = 1:cores, .combine = rbind, .export = paste0("book", i),  .packages = c("data.table")) %dopar% {

    #Try to get the named subset corresponding to the current iteration (i)
    # IE : Books1, Books2...
    BookSubset = get(paste0("book", i))
    Book.list.subset = unique(BookSubset$BookId)

    temp = data.table(BookId = character(0), data = character(0))

    for (i in 1:length(Book.list.subset)) {
        bookId = Book.list.subset[i]

        subset <- BookSubset[which(Book.list.subset ==bookId)]
        output = capture.output(write.table(subset, stdout()quote=FALSE, row.names=FALSE,col.names=FALSE)

      temp <- rbind(hist, data.table(zkf_BOOK = c(bookId), data = c(output)))
    }
    temp
}
</code>```

Here is the result of dput[head(books)):

```<code>structure(list(BookId = c("BOOKXXXX774051532082", "BOOKXXXX776514515608",
    "BOOKXXXX776287821289", "BOOKXXXX776514515608", "BOOKXXXX774051532082",
    "BOOKXXXX774051532082"), V2 = c("ZUSRXXXX842901236553",
    "ZUSRXXXX371255229634",
     "ZUSRXXXX656080986411", "ZUSRXXXX371255229634", "ZUSRXXXX842901236553",
    "ZUSRXXXX842901236553"), V3 = c("BOOKEVTX776757835463",
    "BOOKEVTX776762775464",
    "BOOKEVTX776772854465", "BOOKEVTX776773643466", "", "BOOKEVTX776995487467"
    ), V4 = c("ZACTIONX215229995154", "ZACTIONX533300043134",
    "ZACTIONX533300043134",
    "ZACTIONX533300043134", "", "ZACTIONX215229995154"), V5 = c("",
    "", "", "", "", ""), V6 = c("", "", "", "", "MAILOUTX776774376684",
    ""), V7 = c("", "", "", "", "", ""), V8 = c("", "", "", "", "",
    ""), V9 = c("", "", "", "", "", ""), V10 = c("", "", "", "",
    "", ""), V11 = c("", "", "", "", "", "")), .Names = c("zkf_BOOK",
    "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11"), class =
    c("data.table",
    "data.frame"), row.names = c(NA, -6L))
</code>```

Here is a sample of my "real" data input:

```<code>BOOKXXXX774051532082    ZUSRXXXX842901236553    BOOKEVTX776757835463    ZACTIONX215229995154
BOOKXXXX776514515608    ZUSRXXXX371255229634    BOOKEVTX776762775464    ZACTIONX533300043134
BOOKXXXX776287821289    ZUSRXXXX656080986411    BOOKEVTX776772854465    ZACTIONX533300043134
BOOKXXXX776514515608    ZUSRXXXX371255229634    BOOKEVTX776773643466    ZACTIONX533300043134
BOOKXXXX774051532082    ZUSRXXXX842901236553                MAILOUTX776774376684
BOOKXXXX774051532082    ZUSRXXXX842901236553    BOOKEVTX776995487467    ZACTIONX215229995154
BOOKXXXX776287821289    ZUSRXXXX656080986411    BOOKEVTX777107387468    ZACTIONX533300043134
</code>```

and the expected output

```<code>BOOKXXXX774051532082    ZUSRXXXX842901236553|BOOKEVTX776757835463|ZACTIONX215229995154|||||||;ZUSRXXXX842901236553||||MAILOUTX776774376684|||||;ZUSRXXXX842901236553|BOOKEVTX776995487467|ZACTIONX215229995154|||||||
BOOKXXXX776514515608    ZUSRXXXX371255229634|BOOKEVTX776762775464|ZACTIONX533300043134|||||||;ZUSRXXXX371255229634|BOOKEVTX776773643466|ZACTIONX533300043134|||||||
BOOKXXXX776287821289    ZUSRXXXX656080986411|BOOKEVTX776772854465|ZACTIONX533300043134|||||||;ZUSRXXXX656080986411|BOOKEVTX777107387468|ZACTIONX533300043134|||||||
</code>```

答:
The OP has requested two collapse operations:

For each row, collapse all columns (except the id column zkf_BOOK) into one data field separated by |.

For each zkf_BOOK group, collapse the rows separated by ;

Collapsing within the columns is done by a call to Reduce() while collapsing across rows is done groupwise using paste(). With data.table, the columns in the by = parameter are not included in operations on .SD.

```<code>library(data.table)
setDT(books)[, paste(Reduce(function(x, y) paste(x, y, sep = "|"), .SD), collapse = ";"),
             by = zkf_BOOK]
</code>```

```<code>               zkf_BOOK
1: BOOKXXXX774051532082
2: BOOKXXXX776514515608
3: BOOKXXXX776287821289
                                                                                V1
1: ZUSRXXXX842901236553|BOOKEVTX776757835463|ZACTIONX215229995154|||||||;ZUSRXXXX842901236553||||MAILOUTX776774376684|||||;ZUSRXXXX842901236553|BOOKEVTX776995487467|ZACTIONX215229995154|||||||
2:                                                   ZUSRXXXX371255229634|BOOKEVTX776762775464|ZACTIONX533300043134|||||||;ZUSRXXXX371255229634|BOOKEVTX776773643466|ZACTIONX533300043134|||||||
3:                                                                                ZUSRXXXX656080986411|BOOKEVTX776772854465|ZACTIONX533300043134|||||||
</code>```

Note that the discrepancy to the expected result is due to dput[head(books)) returning only 6 rows while the printed data input and expected output are based on 7 rows (or more).

Title: Export named variable in foreach loop

Body:
I have a large data.table (+12M rows) that I need to convert this way :

Collapse each row with same first column value (let's call it BookId) into 1 row, and merge other columns into a big "data" field.
This table contains 2.7M unique BookId's

Ie :

BookId    Col1      Col2     ...      ColN
B001      Author    Bob      ...      ...
B002      Author    Marc     ...      ...
B002      Editor    Bob Inc  ...      ...
B001      Editor    MyBooks  ...      ...

Expeted result :

BookId    data
B001      Bob,MyBooks, ...
B002      Marc,Bob Inc, ...

For now, I've been able to reproduce this structure using subsets, but this is really slow, it takes up to 300ms to build a row, which means it will take up to 9 days to achieve the process.

So I decided to use a parallel foreach loop to speed up the process.

My first approch was to loop over the bookId List, but it would only devide global overall time by the number of cores which is not satisfying (8 cores means +1 day). Also, that means each process will auto-export a very large amount of data as they all need the whole data.table object.

I found another approach to improve the process by splitting the primary data.table into independant subsets based on bookId list, then make each cluster works on that subsets (less rows means faster subsets generation).
Unfortunatly, I'm unable to export my subsets to clusters as they have a "dynamic" name.
I tried ".export" param but I guess it isn't aware of the current "i" value when evaluated.
How can I achieve this ? Is it even possible ?

I'm new to R, I have been told that there was always many ways to achieve the same thing, did I choose the best approach to achieve this ?

Here is my code :

# Create cluster based on available cores
cores = detectCores()
cl <- makeCluster(cores)
registerDoParallel(cl)

# Load datas and generate BookId lists
books <- fread("books.tab")
bookId.unique.list <- unique(books$BookId)
bookId.list <- books$BookId

# Split datatable into "equals" subsets
subset.length = ceiling(length(book.unique.list)/cores)
for (i in 1:(cores)) {
    start = (i-1)*subset.length
    end = (i)*subset.length
    list = book.unique.list[start:end]
    assign(paste("books",i,sep=""), books[books$BookId %in% list])
    assign(paste("book.list",i,sep=""), list )
}

# Prepare resulting DT
res = data.table(BookId = character(0), data = character(0))

# Parallel loop
res  <- foreach(i = 1:cores, .combine = rbind, .export = paste0("book", i),  .packages = c("data.table")) %dopar% {

    #Try to get the named subset corresponding to the current iteration (i)
    # IE : Books1, Books2...
    BookSubset = get(paste0("book", i))
    Book.list.subset = unique(BookSubset$BookId)

    temp = data.table(BookId = character(0), data = character(0))

    for (i in 1:length(Book.list.subset)) {
        bookId = Book.list.subset[i]

        subset <- BookSubset[which(Book.list.subset ==bookId)]
        output = capture.output(write.table(subset, stdout()quote=FALSE, row.names=FALSE,col.names=FALSE)

      temp <- rbind(hist, data.table(zkf_BOOK = c(bookId), data = c(output)))
    }
    temp
}

Here is the result of dput[head(books)):

structure(list(BookId = c("BOOKXXXX774051532082", "BOOKXXXX776514515608",
    "BOOKXXXX776287821289", "BOOKXXXX776514515608", "BOOKXXXX774051532082",
    "BOOKXXXX774051532082"), V2 = c("ZUSRXXXX842901236553",
    "ZUSRXXXX371255229634",
     "ZUSRXXXX656080986411", "ZUSRXXXX371255229634", "ZUSRXXXX842901236553",
    "ZUSRXXXX842901236553"), V3 = c("BOOKEVTX776757835463",
    "BOOKEVTX776762775464",
    "BOOKEVTX776772854465", "BOOKEVTX776773643466", "", "BOOKEVTX776995487467"
    ), V4 = c("ZACTIONX215229995154", "ZACTIONX533300043134",
    "ZACTIONX533300043134",
    "ZACTIONX533300043134", "", "ZACTIONX215229995154"), V5 = c("",
    "", "", "", "", ""), V6 = c("", "", "", "", "MAILOUTX776774376684",
    ""), V7 = c("", "", "", "", "", ""), V8 = c("", "", "", "", "",
    ""), V9 = c("", "", "", "", "", ""), V10 = c("", "", "", "",
    "", ""), V11 = c("", "", "", "", "", "")), .Names = c("zkf_BOOK",
    "V2", "V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11"), class =
    c("data.table",
    "data.frame"), row.names = c(NA, -6L))

Here is a sample of my "real" data input:

BOOKXXXX774051532082    ZUSRXXXX842901236553    BOOKEVTX776757835463    ZACTIONX215229995154
BOOKXXXX776514515608    ZUSRXXXX371255229634    BOOKEVTX776762775464    ZACTIONX533300043134
BOOKXXXX776287821289    ZUSRXXXX656080986411    BOOKEVTX776772854465    ZACTIONX533300043134
BOOKXXXX776514515608    ZUSRXXXX371255229634    BOOKEVTX776773643466    ZACTIONX533300043134
BOOKXXXX774051532082    ZUSRXXXX842901236553                MAILOUTX776774376684
BOOKXXXX774051532082    ZUSRXXXX842901236553    BOOKEVTX776995487467    ZACTIONX215229995154
BOOKXXXX776287821289    ZUSRXXXX656080986411    BOOKEVTX777107387468    ZACTIONX533300043134

and the expected output

BOOKXXXX774051532082    ZUSRXXXX842901236553|BOOKEVTX776757835463|ZACTIONX215229995154|||||||;ZUSRXXXX842901236553||||MAILOUTX776774376684|||||;ZUSRXXXX842901236553|BOOKEVTX776995487467|ZACTIONX215229995154|||||||
BOOKXXXX776514515608    ZUSRXXXX371255229634|BOOKEVTX776762775464|ZACTIONX533300043134|||||||;ZUSRXXXX371255229634|BOOKEVTX776773643466|ZACTIONX533300043134|||||||
BOOKXXXX776287821289    ZUSRXXXX656080986411|BOOKEVTX776772854465|ZACTIONX533300043134|||||||;ZUSRXXXX656080986411|BOOKEVTX777107387468|ZACTIONX533300043134|||||||

Body:
The OP has requested two collapse operations:

For each row, collapse all columns (except the id column zkf_BOOK) into one data field separated by |.

For each zkf_BOOK group, collapse the rows separated by ;

Collapsing within the columns is done by a call to Reduce() while collapsing across rows is done groupwise using paste(). With data.table, the columns in the by = parameter are not included in operations on .SD.

library(data.table)
setDT(books)[, paste(Reduce(function(x, y) paste(x, y, sep = "|"), .SD), collapse = ";"),
             by = zkf_BOOK]

               zkf_BOOK
1: BOOKXXXX774051532082
2: BOOKXXXX776514515608
3: BOOKXXXX776287821289
                                                                                V1
1: ZUSRXXXX842901236553|BOOKEVTX776757835463|ZACTIONX215229995154|||||||;ZUSRXXXX842901236553||||MAILOUTX776774376684|||||;ZUSRXXXX842901236553|BOOKEVTX776995487467|ZACTIONX215229995154|||||||
2:                                                   ZUSRXXXX371255229634|BOOKEVTX776762775464|ZACTIONX533300043134|||||||;ZUSRXXXX371255229634|BOOKEVTX776773643466|ZACTIONX533300043134|||||||
3:                                                                                ZUSRXXXX656080986411|BOOKEVTX776772854465|ZACTIONX533300043134|||||||

Note that the discrepancy to the expected result is due to dput[head(books)) returning only 6 rows while the printed data input and expected output are based on 7 rows (or more).


问:
Split string every nth character from the right?
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

```<code>import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))
</code>```

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

```<code>'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])
</code>```

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

```<code>ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))
</code>```

答:
Then if you got a solution for the direction left to right, why not simply reverse the input and output ?

```<code>str = '1234567890'
str[::-1]
</code>```

Output:

```<code>'0987654321'
</code>```

You can use the solution you found for left to right and then, you simply need to reverse it again.

Body:
I have different very large sets of files which I'd like to put in different subfolders. I already have an consecutive ID for every folder I want to use.
I want to split the ID from the right to always have 1000 folders in the deeper levels.

Example:

id: 100243 => resulting_path: './100/243'

id: 1234567890 => resulting path: '1/234/567/890'

I found Split string every nth character?, but all solutions are from left to right and I also did not want to import another module for one line of code.

My current (working) solution looks like this:

import os

base_path = '/home/made'
n=3    # take every 'n'th from the right
max_id = 12345678900
test_id = 24102442

# current algorithm
str_id = str(test_id).zfill(len(str(max_id)))
ext_path = list(reversed([str_id[max(i-n,0):i] for i in range(len(str_id),0,-n)]))
print(os.path.join(base_path, *ext_path))

Output is: /home/made/00/024/102/442

The current algorithm looks awkward and complicated for the simple thing I want to do.
I wonder if there is a better solution. If not it might help others, anyway.

Update:

I really like Joe Iddons solution. Using .join and mod makes it faster and more readable.

In the end I decided that I never want to have a /in front. To get rid of the preceeding /in case len(s)%3is zero, I changed the line to

'/'.join([s[max(0,i):i+3] for i in range(len(s)%3-3*(len(s)%3 != 0), len(s), 3)])

Thank you for your great help!

Update 2:

If you are going to use os.path.join (like in my previous code) its even simpler since os.path.jointakes care of the format of the args itself:

ext_path = [s[0:len(s)%3]] + [s[i:i+3] for i in range(len(s)%3, len(s), 3)]
print(os.path.join('/home', *ext_path))

Body:
Then if you got a solution for the direction left to right, why not simply reverse the input and output ?

str = '1234567890'
str[::-1]

Output:

'0987654321'

You can use the solution you found for left to right and then, you simply need to reverse it again.


问:
Currency regular expression for GBP/USD/EUR
Need some help with creating a regular expression that satisfies the following rules. Any suggestions would be greatly appreciated.

(1a.) Optionally start with:
    £, $, €

1b. Currency value must start with one to three digits

2a. Before a comma: There must be one to three digits

2b. After a comma: There must be three digits

2c. After a decimal point: There can only be digits

3a. Currency value must end with one or many digits

[3b.] Value may be followed by:
    tn/Tn/Trillion/trillion, bn/Bn/Billion/billion, m/Million/million.

(3c.) Optionally end with:
    p/P/Pence/pence, c/C/Cents/cents, €/Euro(s)/euro(s), Dollars/dollars, Pounds/pounds.

Rule 1a and 3c are mutually exclusive, however one of them must be used:

$1 dollar ✘
1 ✘
$1 ✓
1 dollar ✓
```

<p><strong>Rule 3b may be used with Rule 1a or 3c</strong>, but does not need to be used:</p>

<pre class="lang-none prettyprint-override"><code>$1 trillion ✓
1 trillion dollars ✓
$1 ✓
</code>```

Rule 2a/2b may be used zero or many times:

$1 ✓
$1,000,000,000,000 ✓
```

<p><strong>Rule 2c may only be used once or zero times:</strong></p>

<pre class="lang-none prettyprint-override"><code>$1 ✓
$1.000 ✓
</code>```

Expected Result:

$1 dollar ✘
1 ✘
$1,00000.000,000 ✘
1,000.00 ✘

$1 ✓
1 dollar ✓
$1 trillion ✓
1 trillion dollars ✓
$1,000,000,000,000 ✓
$1.000 ✓
$1,000,000,000,000.000000 ✓
```

<p>Here's what I have so far:</p>

```[£€$]?[0-9]+[,.]?[0-9][pcm][ euros| euro]*
```

答:
The following regex doesn't rely on the values being on separate lines but will also grab them from within a sentence.

It also assumes that the units "cents", "dollars" and "pounds" can be singular.

Plus it allows unlimited whitespace between the words and the number, and also no whitespace between the number and the following value word or unit.

Explanation:

The following is the basic structure of the regex with sub-expressions represented by values surrounded by two @s:

```<code>(@Prefix@)?(?=(@Value@)(\s*@Postfix@)?)(?(1)\2(?!\3)|(?<!@Prefix@)\2\3)
|________|    |_______||____________|  |______________________________|
    |             |           |                       |
 Group 1       Group 2    Group 3          Prefix-Postfix Selector
</code>```

Group 1 optionally matches the prefix.

Group 2 and Group 3 are captured inside a look-ahead so that when Prefix-Postfix Selector is executed, only Group 1 is part of the overall match.

Prefix-Postfix Selector is a conditional statement that does the following:

If Group 1 (Prefix) is matched, then add Group 2 (Value) to the overall match iff there is no Group 3 (Postfix) following it.

If no Prefix is matched, then set the overall match to Value followed by Postfix iff there is no Prefix preceding Value.

The sub-expressions are fairly self-explanatory. The \bs make sure that entire words are matched. Similarly, the negative look-ahead (?![\d.,]) after the number makes sure that that no digits, commas and decimal points are left over.

@Prefix@:

```<code>[£€$]
</code>```

@Value@:

```<code>\d{1,3}(?:,\d{3})*(?:\.\d+)?(?![\d.,])(?:\s*(?:[tTbB]n|m|(?:[tT]r|[bBmM])illion)\b)?
|_____||_________||________||        ||                                            |
|__________________________||________||____________________________________________|
             |                   |                          |
   Number, e.g. 12,345.6         |    [[Whitespace] + Value Word, e.g. Tn or Billion]
                                 |
           Makes sure "1000" is not matched, for example
</code>```

@Postfix@:

```<code>\s*(?:[pP](?:ence)?|[cC](?:ents?)?|€|[eE]uros?|[dD]ollars?|[pP]ounds?)\b
</code>```

Solution:

Replacing the placeholders with the sub-expressions leads to this full regex:

```<code>([£€$])?(?=(\d{1,3}(?:,\d{3})*(?:\.\d+)?(?![\d.,])(?:\s*(?:[tTbB]n|m|(?:[tT]r|[bBmM])illion)\b)?)(\s*(?:[pP](?:ence)?|[cC](?:ents?)?|€|[eE]uros?|[dD]ollars?|[pP]ounds?)\b)?)(?(1)\2(?!\3)|(?<![£€$])\2\3)
</code>```

Demo

Caveats:

A value like "$1" appearing in a sentence followed by a comma or full stop will not be matched. (For example, only $2 is matched in the sentence This sentence is worth $1, $2 or $3..)

A value consisting of a number with commas and/or a decimal point and a value word is allowed, e.g. "1,000,000 million".

Body:
Need some help with creating a regular expression that satisfies the following rules. Any suggestions would be greatly appreciated.

(1a.) Optionally start with:
    £, $, €

1b. Currency value must start with one to three digits

2a. Before a comma: There must be one to three digits

2b. After a comma: There must be three digits

2c. After a decimal point: There can only be digits

3a. Currency value must end with one or many digits

[3b.] Value may be followed by:
    tn/Tn/Trillion/trillion, bn/Bn/Billion/billion, m/Million/million.

(3c.) Optionally end with:
    p/P/Pence/pence, c/C/Cents/cents, €/Euro(s)/euro(s), Dollars/dollars, Pounds/pounds.

Rule 1a and 3c are mutually exclusive, however one of them must be used:

$1 dollar ✘
1 ✘
$1 ✓
1 dollar ✓

Rule 3b may be used with Rule 1a or 3c, but does not need to be used:

$1 trillion ✓
1 trillion dollars ✓
$1 ✓

Rule 2a/2b may be used zero or many times:

$1 ✓
$1,000,000,000,000 ✓

Rule 2c may only be used once or zero times:

$1 ✓
$1.000 ✓

Expected Result:

$1 dollar ✘
1 ✘
$1,00000.000,000 ✘
1,000.00 ✘

$1 ✓
1 dollar ✓
$1 trillion ✓
1 trillion dollars ✓
$1,000,000,000,000 ✓
$1.000 ✓
$1,000,000,000,000.000000 ✓

Here's what I have so far:

[£€$]?[0-9]+[,.]?[0-9][pcm][ euros| euro]*

Body:
The following regex doesn't rely on the values being on separate lines but will also grab them from within a sentence.

It also assumes that the units "cents", "dollars" and "pounds" can be singular.

Plus it allows unlimited whitespace between the words and the number, and also no whitespace between the number and the following value word or unit.

Explanation:

The following is the basic structure of the regex with sub-expressions represented by values surrounded by two @s:

(@Prefix@)?(?=(@Value@)(\s*@Postfix@)?)(?(1)\2(?!\3)|(?<!@Prefix@)\2\3)
|________|    |_______||____________|  |______________________________|
    |             |           |                       |
 Group 1       Group 2    Group 3          Prefix-Postfix Selector

Group 1 optionally matches the prefix.

Group 2 and Group 3 are captured inside a look-ahead so that when Prefix-Postfix Selector is executed, only Group 1 is part of the overall match.

Prefix-Postfix Selector is a conditional statement that does the following:

If Group 1 (Prefix) is matched, then add Group 2 (Value) to the overall match iff there is no Group 3 (Postfix) following it.

If no Prefix is matched, then set the overall match to Value followed by Postfix iff there is no Prefix preceding Value.

The sub-expressions are fairly self-explanatory. The \bs make sure that entire words are matched. Similarly, the negative look-ahead (?![\d.,]) after the number makes sure that that no digits, commas and decimal points are left over.

@Prefix@:

[£€$]

@Value@:

\d{1,3}(?:,\d{3})*(?:\.\d+)?(?![\d.,])(?:\s*(?:[tTbB]n|m|(?:[tT]r|[bBmM])illion)\b)?
|_____||_________||________||        ||                                            |
|__________________________||________||____________________________________________|
             |                   |                          |
   Number, e.g. 12,345.6         |    [[Whitespace] + Value Word, e.g. Tn or Billion]
                                 |
           Makes sure "1000" is not matched, for example

@Postfix@:

\s*(?:[pP](?:ence)?|[cC](?:ents?)?|€|[eE]uros?|[dD]ollars?|[pP]ounds?)\b

Solution:

Replacing the placeholders with the sub-expressions leads to this full regex:

([£€$])?(?=(\d{1,3}(?:,\d{3})*(?:\.\d+)?(?![\d.,])(?:\s*(?:[tTbB]n|m|(?:[tT]r|[bBmM])illion)\b)?)(\s*(?:[pP](?:ence)?|[cC](?:ents?)?|€|[eE]uros?|[dD]ollars?|[pP]ounds?)\b)?)(?(1)\2(?!\3)|(?<![£€$])\2\3)

Demo

Caveats:

A value like "$1" appearing in a sentence followed by a comma or full stop will not be matched. (For example, only $2 is matched in the sentence This sentence is worth $1, $2 or $3..)

A value consisting of a number with commas and/or a decimal point and a value word is allowed, e.g. "1,000,000 million".


问:
How do I read this text file and Insert into MySQL?
sample

```<code>user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane
</code>```

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

答:
LOAD DATA INFILE

Example:

NOTE: if you run this from Windows you need to escape the forward slashes in the file path.

EXAMPLE:

```<code>C:\\path\to\file.txt
</code>```

Looks like:

```<code>C:\\\\path\\to\\file.txt
</code>```

Here is the query:

```<code>LOAD DATA INFILE '/path/to/sample.txt'
INTO TABLE `database_name`.`table_name`
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(
user_id, user_name
)
</code>```

Body:
sample

user id  User Name
   U456      Mathew
   U457      Leon
   U458      Cris
   U459      Yancy
   U460      Jane

and so on up to 500k.

I need to read this text file and insert to MySQL  in two columns say User ID and User Name. How do I do this in PHP?

Body:
LOAD DATA INFILE

Example:

NOTE: if you run this from Windows you need to escape the forward slashes in the file path.

EXAMPLE:

C:\\path\to\file.txt

Looks like:

C:\\\\path\\to\\file.txt

Here is the query:

LOAD DATA INFILE '/path/to/sample.txt'
INTO TABLE `database_name`.`table_name`
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(
user_id, user_name
)


问:
Format String to add \n before showing it in alert?
I have the following String which is coming from the backend and I need to format the string before showing it in the alert message.

How we can do that using Apex code or using JavaScript code? How we can put \n for each ., • and o?

Try adding the above to your web page, then load the page and see if it works. If it doesn't, you probably have a bug. Specifically, please:  • Be sure you typed everything exactly as it appears,:    o Third Party Details   • Upload the following documents in the Requestor Required Documentation section:    o Proposal    o Relevant Documentation

I am using Visualforce pages and Controller.

```<code>    <!DOCTYPE html>
    <html>
    <body>

    <h2>JavaScript Alert</h2>

    <button onclick="myFunction()">Try it</button>

    <script>
    function myFunction() {
        alert("Try adding the above to your web page, then load the page and see if it works.
If it doesn't, you probably have a bug.\n Specifically, please:\n
• Be sure you typed everything exactly as it appears,:\n
o Third Party Details   \n• Upload the following documents in the Requestor
Required Documentation section:      \no Proposal     \no Relevant Documentation");
    }
    </script>

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

I have already formatted code using object.field.stripHtmlTags();

Shown alert should be like below. But how to split String for ., • and o and add \n using apex?

答:
Try this

alert("Try adding the above to your web page, then load the page and see if it works. If it doesn 't, you probably have a bug.\n\n Specifically, please:\n\no Be sure you typed everything exactly as it appears,: \no Third Party Details\no Upload the following documents in the Requestor Required Documentation section: \no Proposal\ no Relevant Documentation ");```
</div>
</div>
</p>

<p>Or Try this</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-js lang-js prettyprint-override"><code>alert("Try adding the above to your web page, then load the page and see if it works. If it doesn 't, you probably have a bug." + "\n\n Specifically, please:" + "\n\no Be sure you typed everything exactly as it appears" + "\no Third Party Details" + "\no Upload the following documents in the Requestor Required Documentation section" + "\no Proposal" + "\no Relevant Documentation ");</code>```

This is edited code according to your updated post with image

alert("Try adding the above to your web page, then load the page and see if it works. If it doesn 't, you probably have a bug."+"\n\n Specifically, please:"+"\n\n• Be sure you typed everything exactly as it appears"+ "t\no Third Party Details"+"\n• Upload the following documents in the Requestor Required"+"\n Documentation section" +"\no Proposal"+"\no Relevant Documentation ");```

Body:
I have the following String which is coming from the backend and I need to format the string before showing it in the alert message.

How we can do that using Apex code or using JavaScript code? How we can put \n for each ., • and o?

Try adding the above to your web page, then load the page and see if it works. If it doesn't, you probably have a bug. Specifically, please:  • Be sure you typed everything exactly as it appears,:    o Third Party Details   • Upload the following documents in the Requestor Required Documentation section:    o Proposal    o Relevant Documentation

I am using Visualforce pages and Controller.

    <!DOCTYPE html>

JavaScript Alert

    <button onclick="myFunction()">Try it</button>

I have already formatted code using object.field.stripHtmlTags();

Shown alert should be like below. But how to split String for ., • and o and add \n using apex?

Body:
Try this

alert("Try adding the above to your web page, then load the page and see if it works. If it doesn 't, you probably have a bug.\n\n Specifically, please:\n\no Be sure you typed everything exactly as it appears,: \no Third Party Details\no Upload the following documents in the Requestor Required Documentation section: \no Proposal\ no Relevant Documentation ");

Or Try this

alert("Try adding the above to your web page, then load the page and see if it works. If it doesn 't, you probably have a bug." + "\n\n Specifically, please:" + "\n\no Be sure you typed everything exactly as it appears" + "\no Third Party Details" + "\no Upload the following documents in the Requestor Required Documentation section" + "\no Proposal" + "\no Relevant Documentation ");

This is edited code according to your updated post with image

alert("Try adding the above to your web page, then load the page and see if it works. If it doesn 't, you probably have a bug."+"\n\n Specifically, please:"+"\n\n• Be sure you typed everything exactly as it appears"+ "t\no Third Party Details"+"\n• Upload the following documents in the Requestor Required"+"\n Documentation section" +"\no Proposal"+"\no Relevant Documentation ");


问:
How TO - Include HTML
i want to include HTML Nav Bar, in Index HTML File.
(I prefer to follow suit) I do not know what wrong I did, but it does not show me the Nav bar..</p>

```<code><html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Home Page</title>
        <script src="https://www.w3schools.com/lib/w3.js"></script>
    </head>
    <body>
        <div w3-include-html="navbar.html"></div>

        <script>
            w3.includeHTML();
        </script>
    </body>
</html>
</code>```

答:
You can OR solve this with PHP, as @floreich mentioned, otherwise I see your code is correct but perhaps your path to the file is not correct.

I mean this line of code:

.

Try to navigate to the correct path of your file called 'navbar.html', and it should work. Let me know! :)

This might help:

```<code><div w3-include-html="dir/navbar.html"></div>
</code>```

As you can see 'dir/' is added before 'navbar.html', which is a directory where 'navbar.html' is located.

Perhaps this explanation might help to understand above: https://www.w3schools.com/hTml/html_filepaths.asp

EDIT:

'dir/' is just a name, so change it to YOUR directory name.

Title: How TO - Include HTML

Body:
i want to include HTML Nav Bar, in Index HTML File.
(I prefer to follow suit) I do not know what wrong I did, but it does not show me the Nav bar..

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Home Page</title>

Body:
You can OR solve this with PHP, as @floreich mentioned, otherwise I see your code is correct but perhaps your path to the file is not correct.

I mean this line of code: <div w3-include-html="navbar.html"></div>.

Try to navigate to the correct path of your file called 'navbar.html', and it should work. Let me know! :)

This might help:

<div w3-include-html="dir/navbar.html"></div>

As you can see 'dir/' is added before 'navbar.html', which is a directory where 'navbar.html' is located.

Perhaps this explanation might help to understand above: https://www.w3schools.com/hTml/html_filepaths.asp

EDIT:

'dir/' is just a name, so change it to YOUR directory name.


问:
Generate String Permutations from multiple Set values (Java 8 Streams)
I have two Sets - country and state. I want to create all possible permutations from both.

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");

    Set<String> countryPermutations = new HashSet<>(
        Arrays.asList("United States of america", "USA"));
    Set<String> statePermutations = new HashSet<>(
        Arrays.asList("Texas", "TX"));

    Set<String> stateCountryPermutations = countryPermutations.stream()
        .flatMap(country -> statePermutations.stream()
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());

    Set<String> finalAliases = Optional.ofNullable(stateCountryPermutations)
        .map(Collection::stream).orElse(Stream.empty())
        .map(sc -> "houston " + sc)
        .collect(Collectors.toSet());
    System.out.println(stateCountryPermutationAliases);
  }
}
```
<p>The state or country or both permutations can be null. I still want my code to function.</p>
<p>Requirements</p>
<ol>
<li><p>If state permutation is null, final output should be [Houston USA, Houston United States of America]</p>
</li>
<li><p>If country permutations is null, final output should be [Houston TX, Houston Texas]</p>
</li>
<li><p>If both are null, then no output</p>
</li>
</ol>
<p>I'm changed my code to below</p>
<pre class="lang-java prettyprint-override"><code>Set<String> stateCountryPermutations =
    Optional.ofNullable(countryPermutations)
        .map(Collection::stream)
        .orElse(Stream.empty())
        .flatMap(country -> Optional.ofNullable(statePermutations)
            .map(Collection::stream)
            .orElse(Stream.empty())
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());
</code>```

This satisfies 3. When either permutation is null, 1 & 2 are not satisfied. I get no aliases as response. How do I modify my code?

答:
To rephrase your question, as far as I understood, you have several collections of, let’s call them labels, and create the permutation of all non-null collections, producing an empty stream, if all are null.

This can be done with a straight-forward logic, stream over all collections, filter out the null elements, map them to Streams and reduce them to a single stream using a streamA.stream().flatMap(… -> streamB.map(combiner)) logic, except that streams cannot be used more than once. To solve this, we can implement it by applying the same logic to suppliers of streams. Another detail is that .map(combiner) should be a -> streamB.flatMap(b -> Stream.of(combine a and b, combine b and a)) in your case.

Stream.of(stateLabels, countryLabels) // stream over all collections
      .filter(Objects::nonNull)       // ignore all null elements
      .<Supplier<Stream<String>>>map(c -> c::stream) // map to a supplier of stream
      .reduce((s1,s2) -> // combine them using flatMap and creating a×b and b×a
          () -> s1.get().flatMap(x -> s2.get().flatMap(y -> Stream.of(x+" "+y, y+" "+x))))
      .orElse(Stream::empty) // use supplier of empty stream when all null
      .get() // get the resulting stream
      .map("houston "::concat) // combine all elements with "houston "
      .forEach(System.out::println);
```

<p>To demonstrate with test cases:</p>

<pre class="lang-java prettyprint-override"><code>// testcases
List<Collection<String>> countryLabelTestCases = Arrays.asList(
    Arrays.asList("United States of america", "USA"),
    null
);
List<Collection<String>> stateLabelTestCases = Arrays.asList(
    Arrays.asList("Texas", "TX"),
    null
);
for(Collection<String> countryLabels: countryLabelTestCases) {
    for(Collection<String> stateLabels: stateLabelTestCases) {
        // begin test case
        System.out.println(" *** "+(
            countryLabels==null? stateLabels==null? "both null": "countryLabels null":
                                 stateLabels==null? "stateLabels null": "neither null"
            )+":"
        );

        // actual operation:

        Stream.of(stateLabels, countryLabels)
              .filter(Objects::nonNull)
              .<Supplier<Stream<String>>>map(c -> c::stream)
              .reduce((s1,s2) -> () -> s1.get().flatMap(x ->
                                       s2.get().flatMap(y -> Stream.of(x+" "+y, y+" "+x))))
              .orElse(Stream::empty)
              .get()
              .map("houston "::concat)
              .forEach(System.out::println);

        // end of operation
        System.out.println();
    }
}
</code>```

 *** neither null:
houston Texas United States of america
houston United States of america Texas
houston Texas USA
houston USA Texas
houston TX United States of america
houston United States of america TX
houston TX USA
houston USA TX

 *** stateLabels null:
houston United States of america
houston USA

 *** countryLabels null:
houston Texas
houston TX

 *** both null:
```

<p>If you want to get the permutations as lists rather than strings, create this helper method</p>

<pre class="lang-java prettyprint-override"><code>static <T> List<T> merge(List<T> a, List<T> b) {
    return Stream.concat(a.stream(), b.stream()).collect(Collectors.toList());
}
</code>```

and change the stream operation to

Stream.of(stateLabels, countryLabels)
      .filter(Objects::nonNull)
      .<Supplier<Stream<List<String>>>>map(c ->
          () -> c.stream().map(Collections::singletonList))
      .reduce((s1,s2) -> () -> s1.get().flatMap(x ->
                               s2.get().flatMap(y -> Stream.of(merge(x,y), merge(y,x)))))
      .orElse(Stream::empty)
      .get()
      .map(list -> merge(Collections.singletonList("houston"), list))
      // proceed processing the List<String>s
```

Mind that for supporting more than the two collections, you only have to change Stream.of(stateLabels, countryLabels), inserting the other collections.

ContentLicense: CC BY-SA 4.0

Body:
I have two Sets - country and state. I want to create all possible permutations from both.

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello World");

    Set<String> countryPermutations = new HashSet<>(
        Arrays.asList("United States of america", "USA"));
    Set<String> statePermutations = new HashSet<>(
        Arrays.asList("Texas", "TX"));

    Set<String> stateCountryPermutations = countryPermutations.stream()
        .flatMap(country -> statePermutations.stream()
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());

    Set<String> finalAliases = Optional.ofNullable(stateCountryPermutations)
        .map(Collection::stream).orElse(Stream.empty())
        .map(sc -> "houston " + sc)
        .collect(Collectors.toSet());
    System.out.println(stateCountryPermutationAliases);
  }
}

The state or country or both permutations can be null. I still want my code to function.

Requirements

If state permutation is null, final output should be [Houston USA, Houston United States of America]

If country permutations is null, final output should be [Houston TX, Houston Texas]

If both are null, then no output

I'm changed my code to below

Set<String> stateCountryPermutations =
    Optional.ofNullable(countryPermutations)
        .map(Collection::stream)
        .orElse(Stream.empty())
        .flatMap(country -> Optional.ofNullable(statePermutations)
            .map(Collection::stream)
            .orElse(Stream.empty())
            .flatMap(state -> Stream.of(state + country, country + state)))
        .collect(Collectors.toSet());

This satisfies 3. When either permutation is null, 1 & 2 are not satisfied. I get no aliases as response. How do I modify my code?

Body:
To rephrase your question, as far as I understood, you have several collections of, let’s call them labels, and create the permutation of all non-null collections, producing an empty stream, if all are null.

This can be done with a straight-forward logic, stream over all collections, filter out the null elements, map them to Streams and reduce them to a single stream using a streamA.stream().flatMap(… -> streamB.map(combiner)) logic, except that streams cannot be used more than once. To solve this, we can implement it by applying the same logic to suppliers of streams. Another detail is that .map(combiner) should be a -> streamB.flatMap(b -> Stream.of(combine a and b, combine b and a)) in your case.

Stream.of(stateLabels, countryLabels) // stream over all collections
      .filter(Objects::nonNull)       // ignore all null elements
      .<Supplier<Stream<String>>>map(c -> c::stream) // map to a supplier of stream
      .reduce((s1,s2) -> // combine them using flatMap and creating a×b and b×a
          () -> s1.get().flatMap(x -> s2.get().flatMap(y -> Stream.of(x+" "+y, y+" "+x))))
      .orElse(Stream::empty) // use supplier of empty stream when all null
      .get() // get the resulting stream
      .map("houston "::concat) // combine all elements with "houston "
      .forEach(System.out::println);

To demonstrate with test cases:

// testcases
List<Collection<String>> countryLabelTestCases = Arrays.asList(
    Arrays.asList("United States of america", "USA"),
    null
);
List<Collection<String>> stateLabelTestCases = Arrays.asList(
    Arrays.asList("Texas", "TX"),
    null
);
for(Collection<String> countryLabels: countryLabelTestCases) {
    for(Collection<String> stateLabels: stateLabelTestCases) {
        // begin test case
        System.out.println(" *** "+(
            countryLabels==null? stateLabels==null? "both null": "countryLabels null":
                                 stateLabels==null? "stateLabels null": "neither null"
            )+":"
        );

        // actual operation:

        Stream.of(stateLabels, countryLabels)
              .filter(Objects::nonNull)
              .<Supplier<Stream<String>>>map(c -> c::stream)
              .reduce((s1,s2) -> () -> s1.get().flatMap(x ->
                                       s2.get().flatMap(y -> Stream.of(x+" "+y, y+" "+x))))
              .orElse(Stream::empty)
              .get()
              .map("houston "::concat)
              .forEach(System.out::println);

        // end of operation
        System.out.println();
    }
}

 *** neither null:
houston Texas United States of america
houston United States of america Texas
houston Texas USA
houston USA Texas
houston TX United States of america
houston United States of america TX
houston TX USA
houston USA TX

 *** stateLabels null:
houston United States of america
houston USA

 *** countryLabels null:
houston Texas
houston TX

 *** both null:

If you want to get the permutations as lists rather than strings, create this helper method

static <T> List<T> merge(List<T> a, List<T> b) {
    return Stream.concat(a.stream(), b.stream()).collect(Collectors.toList());
}

and change the stream operation to

Stream.of(stateLabels, countryLabels)
      .filter(Objects::nonNull)
      .<Supplier<Stream<List<String>>>>map(c ->
          () -> c.stream().map(Collections::singletonList))
      .reduce((s1,s2) -> () -> s1.get().flatMap(x ->
                               s2.get().flatMap(y -> Stream.of(merge(x,y), merge(y,x)))))
      .orElse(Stream::empty)
      .get()
      .map(list -> merge(Collections.singletonList("houston"), list))
      // proceed processing the List<String>s

Mind that for supporting more than the two collections, you only have to change Stream.of(stateLabels, countryLabels), inserting the other collections.


问:
Why does Github sort capital letters over lowercase?
Looking in my Github repo, the naming convention goes something like this.

```<code>Repo
  Abc
  Sbc
  Zbc
  abc
</code>```

Why does github have lowercase being sorted differently than uppercase?

答: They names are probably sorted by their natural ASCII ordering. If you look at the ASCII table, the capital letters' values range from 65 ('A') to 90 ('Z'), while the lower case letters' values range from 97 ('a') to 122 ('z').</p>

Body:
Looking in my Github repo, the naming convention goes something like this.

Repo
  Abc
  Sbc
  Zbc
  abc

Why does github have lowercase being sorted differently than uppercase?


答:
You have to attach event handler to the object load completion event. The library you are working with must supply this event. I don't know what a Duk is, or what getBlueprint() does, but you should check the documentation for whatever that class and method is, and see if there is an oncomplete callback. If there is, you'd do something like this:

```<code>$(document).ready(function() {
    d = new Duk('element');
    d.getBlueprint('hud.json', {
        onComplete: function() {
            test = new d.Dialog(d.blueprint.screens.test);
            test.draw();
        }
    });
});
</code>```

Obviously, I just made that up. I don't know if your library has an onComplete method defined like this, but I hope you see what I mean. Without knowing more about the library you are using, I can't give a better example.

Title: How to 'queue' piece of code in javascript

Body:
I've made a class that, when initialized, starts to download a JSON file.

However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.

I could turn async off, but is there another way without freezing the browser?

I'm currently working around it with a setTimeout option, but that seems like an ugly hack.

  var d;
  $(document).ready(function() {
      d = new Duk('element');
      d.getBlueprint('hud.json');
      setTimeout(start, '2000');
  });

  function start(){
      test = new d.Dialog(d.blueprint.screens.test);
      test.draw();
  }

Body:
You have to attach event handler to the object load completion event. The library you are working with must supply this event. I don't know what a Duk is, or what getBlueprint() does, but you should check the documentation for whatever that class and method is, and see if there is an oncomplete callback. If there is, you'd do something like this:

$(document).ready(function() {
    d = new Duk('element');
    d.getBlueprint('hud.json', {
        onComplete: function() {
            test = new d.Dialog(d.blueprint.screens.test);
            test.draw();
        }
    });
});

Obviously, I just made that up. I don't know if your library has an onComplete method defined like this, but I hope you see what I mean. Without knowing more about the library you are using, I can't give a better example.


问:
Symfony authentication with guard always return "Username could not be found."
I know there are a lot of threads on this subject, but none of them helped me...

I am working on an application on which you have to send an access token in the headers for each request.
I manage this security with Guard.

For my tests, when I send a false token, or when I do not send it, the start() or onAuthenticationFailure() method must be called as appropriate.
But it does not work. I have the same error every time.
Looks like these methods are never called.

No authorization sent

```<code>GET /BileMo/web/app_dev.php/api/products/2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json

{
     "message": "Username could not be found."
}
</code>```

Invalid access token

```<code>GET /BileMo/web/app_dev.php/api/products/2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json
Authorization: *Fake Facebook Token*

{
     "message": "Username could not be found."
}
</code>```

instead of:

```<code>{
       "message": "Authorization required"
}
</code>```

or

```<code>{
       "message": "The facebook access token is wrong!"
}
</code>```

With a correct access token, requests are returned to the user correctly.

Example of a request :

```<code>GET /BileMo/web/app_dev.php/api/products/2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json
Authorization: *Facebook Token*
</code>```

Here are the important parts of my code:

security.yml

```<code>security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_USER

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

        api_key_user_provider:
            entity:
                class: FacebookTokenBundle:User
                property: facebook_access_token

    firewalls:
        api:
            pattern: ^/api
            stateless: true
            anonymous: false
            guard:
                authenticators:
                    - AppBundle\Security\FacebookAuthenticator

        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                login_path: /login
                check_path: /login_check

            oauth:
                resource_owners:
                    facebook:           "/login/check-facebook"
                login_path:        /login
                failure_path:      /login

                oauth_user_provider:
                    #this is my custom user provider, created from FOSUBUserProvider - will manage the
                    #automatic user registration on your site, with data from the provider (facebook. google, etc.)
                    service: my_user_provider
            logout:       true
            anonymous:    true

        login:
            pattern:  ^/login$
            security: false

            remember_me:
                secret: "%secret%"
                lifetime: 31536000 # 365 days in seconds
                path: /
                domain: ~ # Defaults to the current domain from $_SERVER

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }
        - { path: ^/api, role: ROLE_USER }
</code>```

FacebookAuthenticator.php

```<code>namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class FacebookAuthenticator extends AbstractGuardAuthenticator
{
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * Called when authentication is needed, but it's not sent
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        $data = array(
            // you might translate this message
            'message' => 'Authentication Required'
        );

        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
    }
    /**
     * Called on every request. Return whatever credentials you want to
     * be passed to getUser(). Returning null will cause this authenticator
     * to be skipped.
     */
    public function getCredentials(Request $request)
    {
        if (!$token = $request->headers->get('Authorization')) {
            // No token?
            $token = null;
        }

        // What you return here will be passed to getUser() as $credentials
        return array(
            'token' => $token,
        );
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $user = $this->em->getRepository('FacebookTokenBundle:User')
            ->findOneBy(array('facebook_access_token' => $credentials));
        return $user;

    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        if ($user->getFacebookAccessToken() === $credentials['token']) {
            return true;
        }
            return new JsonResponse(array('message' => 'The facebook access token is wrong!', Response::HTTP_FORBIDDEN));
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // on success, let the request continue
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $data = array(
            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

            // or to translate this message
            // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
        );

        return new JsonResponse($data, Response::HTTP_FORBIDDEN);
    }

    public function supportsRememberMe()
    {
        return false;
    }
}
</code>```

答:
This behaviour is expected. AbstractGuardAuthenticator has too generic interface, and you need to tailor it to your needs, if you want.

For example, to have error "Authorization required" - you may throw AuthenticationException inside getCredentials() methods. Exception will be catch in symfony core and method start() will be called finally.

```<code>public function getCredentials(Request $request)
{
    if (!$request->headers->has('Authorization')) {
        throw new AuthenticationException();
    }
    ...
}
</code>```

Method onAuthenticationFailure() is usually used to redirect user to login page in case of wrong credentials. In case of API key in header this functionality is not needed. Also in current implementation how to separate, when "API key not correct" and when "user is not found"?

Body:
I know there are a lot of threads on this subject, but none of them helped me...

I am working on an application on which you have to send an access token in the headers for each request.
I manage this security with Guard.

For my tests, when I send a false token, or when I do not send it, the start() or onAuthenticationFailure() method must be called as appropriate.
But it does not work. I have the same error every time.
Looks like these methods are never called.

No authorization sent

GET /BileMo/web/app_dev.php/api/products/2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json

{
     "message": "Username could not be found."
}

Invalid access token

GET /BileMo/web/app_dev.php/api/products/2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json
Authorization: *Fake Facebook Token*

{
     "message": "Username could not be found."
}

instead of:

{
       "message": "Authorization required"
}

or

{
       "message": "The facebook access token is wrong!"
}

With a correct access token, requests are returned to the user correctly.

Example of a request :

GET /BileMo/web/app_dev.php/api/products/2 HTTP/1.1
Host: localhost:8888
Content-Type: application/json
Authorization: *Facebook Token*

Here are the important parts of my code:

security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_USER

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

        api_key_user_provider:
            entity:
                class: FacebookTokenBundle:User
                property: facebook_access_token

    firewalls:
        api:
            pattern: ^/api
            stateless: true
            anonymous: false
            guard:
                authenticators:
                    - AppBundle\Security\FacebookAuthenticator

        dev:
            pattern:  ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            pattern: ^/
            form_login:
                provider: fos_userbundle
                csrf_token_generator: security.csrf.token_manager
                login_path: /login
                check_path: /login_check

            oauth:
                resource_owners:
                    facebook:           "/login/check-facebook"
                login_path:        /login
                failure_path:      /login

                oauth_user_provider:
                    #this is my custom user provider, created from FOSUBUserProvider - will manage the
                    #automatic user registration on your site, with data from the provider (facebook. google, etc.)
                    service: my_user_provider
            logout:       true
            anonymous:    true

        login:
            pattern:  ^/login$
            security: false

            remember_me:
                secret: "%secret%"
                lifetime: 31536000 # 365 days in seconds
                path: /
                domain: ~ # Defaults to the current domain from $_SERVER

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/, role: ROLE_ADMIN }
        - { path: ^/api, role: ROLE_USER }

FacebookAuthenticator.php

namespace AppBundle\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\User\UserProviderInterface;

class FacebookAuthenticator extends AbstractGuardAuthenticator
{
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * Called when authentication is needed, but it's not sent
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        $data = array(
            // you might translate this message
            'message' => 'Authentication Required'
        );

        return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
    }
    /**
     * Called on every request. Return whatever credentials you want to
     * be passed to getUser(). Returning null will cause this authenticator
     * to be skipped.
     */
    public function getCredentials(Request $request)
    {
        if (!$token = $request->headers->get('Authorization')) {
            // No token?
            $token = null;
        }

        // What you return here will be passed to getUser() as $credentials
        return array(
            'token' => $token,
        );
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $user = $this->em->getRepository('FacebookTokenBundle:User')
            ->findOneBy(array('facebook_access_token' => $credentials));
        return $user;

    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        if ($user->getFacebookAccessToken() === $credentials['token']) {
            return true;
        }
            return new JsonResponse(array('message' => 'The facebook access token is wrong!', Response::HTTP_FORBIDDEN));
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        // on success, let the request continue
        return null;
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        $data = array(
            'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

            // or to translate this message
            // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
        );

        return new JsonResponse($data, Response::HTTP_FORBIDDEN);
    }

    public function supportsRememberMe()
    {
        return false;
    }
}

Body:
This behaviour is expected. AbstractGuardAuthenticator has too generic interface, and you need to tailor it to your needs, if you want.

For example, to have error "Authorization required" - you may throw AuthenticationException inside getCredentials() methods. Exception will be catch in symfony core and method start() will be called finally.

public function getCredentials(Request $request)
{
    if (!$request->headers->has('Authorization')) {
        throw new AuthenticationException();
    }
    ...
}

Method onAuthenticationFailure() is usually used to redirect user to login page in case of wrong credentials. In case of API key in header this functionality is not needed. Also in current implementation how to separate, when "API key not correct" and when "user is not found"?


问:
build Go with gccgo - fork/exec no such file or directory
I am trying to run a simple helloworld.go on RHEL 6.8.

```<code>% cat helloworld.go
package main
import "fmt"
func main() {
    fmt.Println("hello world")
}
</code>```

The GC compiler works ok

```<code>%  go build -compiler gccgo helloworld.go
go build command-line-arguments: : fork/exec : no such file or directory
</code>```

For some reason, instead, I need to compile with gccgo, but could never get it to compile. Let alone to eventually compile it statically.

```<code>% go build -compiler gccgo -gccgoflags '-static' helloworld.go
go build command-line-arguments: : fork/exec : no such file or directory
% go build -compiler gccgo -gccgoflags '-static-libgo' helloworld.go
go build command-line-arguments: : fork/exec : no such file or directory

% go version
go version go1.7 linux/amd64
% gcc --version
gcc (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)
</code>```

Insights on what the problem is would be appreciated?

答:
You should install gccgo compiler first. On my Fedora 26 desktop, run dnf install gcc-go to install.

$ which gccgo
/usr/bin/gccgo
go build --compiler gccgo -x
WORK=/tmp/go-build848309745
mkdir -p $WORK/_/home/sam/sandbox/go/src/hello/_obj/
mkdir -p $WORK/_/home/sam/sandbox/go/src/hello/_obj/exe/
cd /home/sam/sandbox/go/src/hello
/usr/bin/gccgo -I $WORK -c -g -m64 -fgo-relative-import-path=_/home/sam/sandbox/go/src/hello -o $WORK/_/home/sam/sandbox/go/src/hello/_obj/_go_.o ./helloworld.go
ar rc $WORK/_/home/sam/sandbox/go/src/libhello.a $WORK/_/home/sam/sandbox/go/src/hello/_obj/_go_.o
cd .
/usr/bin/gccgo -o $WORK/_/home/sam/sandbox/go/src/hello/_obj/exe/a.out $WORK/_/home/sam/sandbox/go/src/hello/_obj/_go_.o -Wl,-( -m64 -Wl,--whole-archive -Wl,--no-whole-archive -Wl,-)
cp $WORK/_/home/sam/sandbox/go/src/hello/_obj/exe/a.out hello

If you need to link static, package glibc-static and libgo-static are required to be installed too. After installed them, compile using gccgo and link statically by

$ go build -compiler gccgo -x --gccgoflags "-static"
WORK=/tmp/go-build815863722
mkdir -p $WORK/_/home/sam/sandbox/go/src/hello/_obj/
mkdir -p $WORK/_/home/sam/sandbox/go/src/hello/_obj/exe/
cd /home/sam/sandbox/go/src/hello
/usr/bin/gccgo -I $WORK -c -g -m64 -fgo-relative-import-path=_/home/sam/sandbox/go/src/hello -o $WORK/_/home/sam/sandbox/go/src/hello/_obj/_go_.o -static ./helloworld.go
ar rc $WORK/_/home/sam/sandbox/go/src/libhello.a $WORK/_/home/sam/sandbox/go/src/hello/_obj/_go_.o
cd .
/usr/bin/gccgo -o $WORK/_/home/sam/sandbox/go/src/hello/_obj/exe/a.out $WORK/_/home/sam/sandbox/go/src/hello/_obj/_go_.o -Wl,-( -m64 -Wl,--whole-archive -Wl,--no-whole-archive -Wl,-) -static
cp $WORK/_/home/sam/sandbox/go/src/hello/_obj/exe/a.out hello

Body:
I am trying to run a simple helloworld.go on RHEL 6.8.

% cat helloworld.go
package main
import "fmt"
func main() {
    fmt.Println("hello world")
}

The GC compiler works ok

%  go build -compiler gccgo helloworld.go
go build command-line-arguments: : fork/exec : no such file or directory

For some reason, instead, I need to compile with gccgo, but could never get it to compile. Let alone to eventually compile it statically.

% go build -compiler gccgo -gccgoflags '-static' helloworld.go
go build command-line-arguments: : fork/exec : no such file or directory
% go build -compiler gccgo -gccgoflags '-static-libgo' helloworld.go
go build command-line-arguments: : fork/exec : no such file or directory

% go version
go version go1.7 linux/amd64
% gcc --version
gcc (GCC) 4.9.2 20150212 (Red Hat 4.9.2-6)

Insights on what the problem is would be appreciated?