问:
If N is positive then output all values from N down to and excluding 0. If N is negative, then output every value from N up to and excluding 0
As I said before I'm a beginner trying to learn Python in a college course, but what they teach us, doesn't always apply to the real world, and when I try to research a solution, there's nothing to be found. Anyway my latest problem is:

```<code>This is a tricky challenge for you.

We will pass in a value N. N can be positive or negative.

If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.

and the starting code is:

# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = 0
while counter <= N:
print(counter)
counter = counter + 1
elif counter >= N:
print(N+counter)
counter = counter - 1

My solution produced an error:

SyntaxError: unexpected EOF while parsing
There is an error is your program.
</code>```

And I honestly don't know where to start, as our textbook doesn't cover these challenges. Thanks in advance for any assistance rendered in this matter. BTW my code is inputted in Codio, and must pass in Codio's IDE.

答:
```<code># Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
if N > 0:
    for x in range(N, 0, -1):
        print x
if N < 0:
    for x in range(N, 0):
        print x
</code>```

While Loops Version

```<code># Your code goes here
if N > 0:
    while N > 0:
        print N
        N -= 1
if N < 0:
    while N < 0:
        print N
        N += 1
</code>```

Body:
As I said before I'm a beginner trying to learn Python in a college course, but what they teach us, doesn't always apply to the real world, and when I try to research a solution, there's nothing to be found. Anyway my latest problem is:

This is a tricky challenge for you.

We will pass in a value N. N can be positive or negative.

If N is positive then output all values from N down to and excluding 0.
If N is negative, then output every value from N up to and excluding 0.

and the starting code is:

# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
counter = 0
while counter <= N:
print(counter)
counter = counter + 1
elif counter >= N:
print(N+counter)
counter = counter - 1

My solution produced an error:

SyntaxError: unexpected EOF while parsing
There is an error is your program.

And I honestly don't know where to start, as our textbook doesn't cover these challenges. Thanks in advance for any assistance rendered in this matter. BTW my code is inputted in Codio, and must pass in Codio's IDE.

Body:
# Get N from the command line
import sys
N = int(sys.argv[1])

# Your code goes here
if N > 0:
    for x in range(N, 0, -1):
        print x
if N < 0:
    for x in range(N, 0):
        print x

While Loops Version

# Your code goes here
if N > 0:
    while N > 0:
        print N
        N -= 1
if N < 0:
    while N < 0:
        print N
        N += 1


来源: stackexchange

问:
How to find a number with link
As below picture, I "crtl+H" want to find "Table 2", but can't find this word because "2" with a link.

II try use vba code

```<code>selection.find.clearformatting
with selection.find .text="Table 2"
   .wrap = wdfindcontinue
   .forward = true
   .font.bold = true
   .replacement.text = "ss"
   .execute replace:=wdreplaceAll
   end with
</code>```

but can't find this "table 2".

答: I got the answer in the other people, this number is "Field", May be because the field braces are not generally entered from the keyboard curly braces, just to indicate the start and end of a domain-wide flag, so the search function does not can find this.</p>

ContentLicense: CC BY-SA 3.0

Title: How to find a number with link

Body:
As below picture, I "crtl+H" want to find "Table 2", but can't find this word because "2" with a link.

II try use vba code

selection.find.clearformatting
with selection.find .text="Table 2"
   .wrap = wdfindcontinue
   .forward = true
   .font.bold = true
   .replacement.text = "ss"
   .execute replace:=wdreplaceAll
   end with

but can't find this "table 2".


问:
Require a form to be filled out to download a .pdf?
Can I dynamically make a page with download links for PDF files and require user fill out HTML form before able to download the .PDF files?</p>

答:
Yes, it is possible. There are many ways. You could simply hide the download button using jQuery until the form has been submited and show it after.

Or if the person enters their email send them an email containing a URL with a unique string that you generate (E.g. www.yourwebsite.com/pdf.php?s=h4jbsj5623v6) and also save this string to your database.

Than create a PHP file that generates a pdf document using TCPDF library or any other similar PHP library that is capable of generating a .pdf file.

When the person visits the download URL check in your database if their unique string, that is passed as a GET parameter exists. And if it does display them the pdf document using previously mentioned library.

Hope this helps...


问:
jwplayer v7.xx _.getVideoData is not a function issue
From today I have the following issue on youtube hosted videos when I want to change dynamically the video on my site.

_.getVideoData is not a function

```<code>Uncaught TypeError: _.getVideoData is not a function
at M (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at load (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.a (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.<anonymous>
(ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at P (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at K.f.I (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:66)
at W.f.l (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:114)
at W.f.J (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:127)
at S.g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:143)
at g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:95)
</code>```

Until today it worked fine. (The jwplayer 8 version show the same issue)

答:
Tried the patch plugin but get anerror: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient

UPDATE:

If you compile from source/git v7.12;

In src/js/providers/youtube.js

Replace:

```<code>var videoData = _youtubePlayer.getVideoData();
var currentVideoId = videoData && videoData.video_id;
</code>```

With:

```<code>var videoData = _youtubePlayer.getVideoUrl();
videoData = videoData.split('=');
var currentVideoId = videoData[1];
</code>```

Body:
From today I have the following issue on youtube hosted videos when I want to change dynamically the video on my site.

_.getVideoData is not a function

Uncaught TypeError: _.getVideoData is not a function
at M (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at load (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.a (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at l.<anonymous>
(ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at P (ssl.p.jwpcdn.com/player/v/7.12.11/provider.youtube.js:1)
at K.f.I (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:66)
at W.f.l (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:114)
at W.f.J (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:127)
at S.g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:143)
at g (s.ytimg.com/yts/jsbin/www-widgetapi-vflnzpyZ4/www-
widgetapi.js:95)

Until today it worked fine. (The jwplayer 8 version show the same issue)

Body:
Tried the patch plugin but get anerror: Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://www.youtube.com') does not match the recipient

UPDATE:

If you compile from source/git v7.12;

In src/js/providers/youtube.js

Replace:

var videoData = _youtubePlayer.getVideoData();
var currentVideoId = videoData && videoData.video_id;

With:

var videoData = _youtubePlayer.getVideoUrl();
videoData = videoData.split('=');
var currentVideoId = videoData[1];


问:
Canvas with HTML and JavaScript
In w3schools there is a basic game and I can't figure out how to make the piece or object a circle. I'm so confused and have tried everything but it didn't work. How can I use fill circle or another method for this? I'm new to canvas.</p>

```<code><!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
    border:1px solid #d3d3d3;
    background-color: #f1f1f1;
}
</style>
</head>
<body onload="startGame()">
<script>

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120);
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40,
     "text");
    myGameArea.start();
}

var myGameArea = {
    canvas : document.createElement("canvas"),
    start : function() {
        this.canvas.width = 480;
        this.canvas.height = 270;
        this.context = this.canvas.getContext("2d");
        document.body.insertBefore(this.canvas,
       document.body.childNodes[0]);
        this.frameNo = 0;
        this.interval = setInterval(updateGameArea, 20);
        },
    clear : function() {
        this.context.clearRect(0, 0, this.canvas.width,
    this.canvas.height);
    }
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        if (this.type == "text") {
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else {
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
        otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}

  function updateGameArea() {
    var x, height, gap, minHeight, maxHeight, minGap, maxGap;
    for (i = 0; i < myObstacles.length; i += 1) {
        if (myGamePiece.crashWith(myObstacles[i])) {
            return;
        }
    }
    myGameArea.clear();
    myGameArea.frameNo += 1;
    if (myGameArea.frameNo == 1 || everyinterval(150)) {
        x = myGameArea.canvas.width;
        minHeight = 20;
        maxHeight = 200;
        height = Math.floor(Math.random()*(maxHeight-
        minHeight+1)+minHeight);
        minGap = 50;
        maxGap = 200;
        gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
        myObstacles.push(new component(10, height, "green", x, 0));
        myObstacles.push(new component(10, x - height - gap, "green", x,
height + gap));
    }
    for (i = 0; i < myObstacles.length; i += 1) {
        myObstacles[i].x += -1;
        myObstacles[i].update();
    }
    myScore.text="SCORE: " + myGameArea.frameNo;
    myScore.update();
    myGamePiece.newPos();
    myGamePiece.update();
}

function everyinterval(n) {
    if ((myGameArea.frameNo / n) % 1 == 0) {return true;}
    return false;
}

function accelerate(n) {
    myGamePiece.gravity = n;
}
</script>
<br>
<button onmousedown="accelerate(-0.2)"
onmouseup="accelerate(0.05)">ACCELERATE</button>
<p>Use the ACCELERATE button to stay in the air</p>
    <p>How long can you stay alive?</p>
    </body>
    </html>
</code>```

答:
Change your function component() and startGame() to this one.
You can draw cirlce with arc method.

Details: https://www.w3schools.com/tags/canvas_arc.asp

```<code>function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120, "player");
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40,
     "text");
    myGameArea.start();
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        if (this.type == "text") { // text
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else if (this.type == "player") { // player
            ctx.beginPath();
            ctx.arc(this.x, this.y, 35,0,2*Math.PI);
            ctx.fill();
            ctx.stroke();
        } else { // wall
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
        otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}
</code>```

Title: Canvas with HTML and JavaScript

Body:
In w3schools there is a basic game and I can't figure out how to make the piece or object a circle. I'm so confused and have tried everything but it didn't work. How can I use fill circle or another method for this? I'm new to canvas.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<button onmousedown="accelerate(-0.2)"
onmouseup="accelerate(0.05)">ACCELERATE</button>

Use the ACCELERATE button to stay in the air

How long can you stay alive?

Body:
Change your function component() and startGame() to this one.
You can draw cirlce with arc method.

Details: https://www.w3schools.com/tags/canvas_arc.asp

function startGame() {
    myGamePiece = new component(30, 30, "red", 10, 120, "player");
    myGamePiece.gravity = 0.05;
    myScore = new component("30px", "Consolas", "black", 280, 40,
     "text");
    myGameArea.start();
}

function component(width, height, color, x, y, type) {
    this.type = type;
    this.score = 0;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.x = x;
    this.y = y;
    this.gravity = 0;
    this.gravitySpeed = 0;
    this.update = function() {
        ctx = myGameArea.context;
        ctx.fillStyle = color;
        if (this.type == "text") { // text
            ctx.font = this.width + " " + this.height;
            ctx.fillStyle = color;
            ctx.fillText(this.text, this.x, this.y);
        } else if (this.type == "player") { // player
            ctx.beginPath();
            ctx.arc(this.x, this.y, 35,0,2*Math.PI);
            ctx.fill();
            ctx.stroke();
        } else { // wall
            ctx.fillStyle = color;
            ctx.fillRect(this.x, this.y, this.width, this.height);
        }
    }
    this.newPos = function() {
        this.gravitySpeed += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY + this.gravitySpeed;
        this.hitBottom();
    }
    this.hitBottom = function() {
        var rockbottom = myGameArea.canvas.height - this.height;
        if (this.y > rockbottom) {
            this.y = rockbottom;
            this.gravitySpeed = 0;
        }
    }
    this.crashWith = function(otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) || (mytop > otherbottom) || (myright <
        otherleft) || (myleft > otherright)) {
            crash = false;
        }
        return crash;
    }
}


问:
jQuery Get Selected Option From Dropdown
Usually I use $("#id").val() to return the value of the selected option, but this time it doesn't work.
The selected tag has the id aioConceptName

html code

```<code><label for="name">Name</label>
<input type="text" name="name" id="name" />

<label for="aioConceptName">AIO Concept Name</label>
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>
</code>```

答:
try to this one</p>

```<code>$(document).ready(function() {

    $("#name option").filter(function() {
        return $(this).val() == $("#firstname").val();
    }).attr('selected', true);

    $("#name").live("change", function() {

        $("#firstname").val($(this).find("option:selected").attr("value"));
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name">
<option value="">Please select...</option>
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>

<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Usually I use $("#id").val() to return the value of the selected option, but this time it doesn't work.
The selected tag has the id aioConceptName

html code

Name
<input type="text" name="name" id="name" />

AIO Concept Name
<select id="aioConceptName">
    <option>choose io</option>
    <option>roma</option>
    <option>totti</option>
</select>

Body:
try to this one

$(document).ready(function() {

    $("#name option").filter(function() {
        return $(this).val() == $("#firstname").val();
    }).attr('selected', true);

    $("#name").live("change", function() {

        $("#firstname").val($(this).find("option:selected").attr("value"));
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<select id="name" name="name">
<option value="">Please select...</option>
<option value="Elvis">Elvis</option>
<option value="Frank">Frank</option>
<option value="Jim">Jim</option>
</select>

<input type="text" id="firstname" name="firstname" value="Elvis" readonly="readonly">


问:
Correctly passing parameters to setTimeout
I am working on a Node.js project, and I am having issues wrapping a Promise function with a setTimeout function.

My original Promise function:

I want to wrap this function in a call to setTimeout() but am having trouble passing in the Promise object. I need the Promise object and the data object available inside the setTimeout() function, but when I pass them into setTimeout() as parameters i still get the following error:

TypeError: Cannot read property 'then' of undefined

My code:

```<code>return Promise.props(data).then(function (data) {
    data.companies = data.order && data.order.companies;
    if (!data.companies) {
        data.companies = {};
        data.companies[data.company.id] = data.company;
    }

    if (data.order) {
        if (data.order.contactentry) {
            data.order.pointofcontact = data.order.contactentry + ' ' + phone(data.order.contactentryphone);
        } else if (data.order.borrowername) {
            data.order.pointofcontact = data.order.borrowername + ' ' + phone(data.order.borrowerphone);
        } else if (data.order.lockboxcode) {
            data.order.pointofcontact = 'Lockbox ' + data.order.lockboxcode
        }
    }

    if (data.part && data.order && data.part.vendor) {
        var oid = data.order && data.order.id;
        var vid = data.part && data.part.vendor && data.part.vendor.id;
        if (!oid || !vid) {
            var e = new Error('Could not assemble vendor accept url, order id or part vendor id are missing')
            log.error({
                error: e,
                data,
            }, e.message);
            throw e;
        }
    }

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

The data object is available inside the function when passed in as a parameter, but the Promise object is not.
How can I properly pass in the Promise object to make it available inside setTimeout()?

答:
I would forget about using the arguments/return value of setTimeout, and just make use of new Promise

Delaying before Promise.props is called:

```<code>return new Promise(function (resolve) {
  window.setTimeout(function () {
    resolve(Promise.props(data));
  }, 1000);
});
</code>```

Or, delaying the result of Promise.props:

```<code>return Promise.props(data).then(function (data) {
  return new Promise(function (resolve) {
    window.setTimeout(function () {
      resolve(data);
    }, 1000);
  });
});
</code>```

Edit: If you're using Bluebird it looks like they have delay operators built in:

http://bluebirdjs.com/docs/api/delay.html

http://bluebirdjs.com/docs/api/promise.delay.html

Body:
I am working on a Node.js project, and I am having issues wrapping a Promise function with a setTimeout function.

My original Promise function:

I want to wrap this function in a call to setTimeout() but am having trouble passing in the Promise object. I need the Promise object and the data object available inside the setTimeout() function, but when I pass them into setTimeout() as parameters i still get the following error:

TypeError: Cannot read property 'then' of undefined

My code:

return Promise.props(data).then(function (data) {
    data.companies = data.order && data.order.companies;
    if (!data.companies) {
        data.companies = {};
        data.companies[data.company.id] = data.company;
    }

    if (data.order) {
        if (data.order.contactentry) {
            data.order.pointofcontact = data.order.contactentry + ' ' + phone(data.order.contactentryphone);
        } else if (data.order.borrowername) {
            data.order.pointofcontact = data.order.borrowername + ' ' + phone(data.order.borrowerphone);
        } else if (data.order.lockboxcode) {
            data.order.pointofcontact = 'Lockbox ' + data.order.lockboxcode
        }
    }

    if (data.part && data.order && data.part.vendor) {
        var oid = data.order && data.order.id;
        var vid = data.part && data.part.vendor && data.part.vendor.id;
        if (!oid || !vid) {
            var e = new Error('Could not assemble vendor accept url, order id or part vendor id are missing')
            log.error({
                error: e,
                data,
            }, e.message);
            throw e;
        }
    }

    return data;
});

The data object is available inside the function when passed in as a parameter, but the Promise object is not.
How can I properly pass in the Promise object to make it available inside setTimeout()?

Body:
I would forget about using the arguments/return value of setTimeout, and just make use of new Promise

Delaying before Promise.props is called:

return new Promise(function (resolve) {
  window.setTimeout(function () {
    resolve(Promise.props(data));
  }, 1000);
});

Or, delaying the result of Promise.props:

return Promise.props(data).then(function (data) {
  return new Promise(function (resolve) {
    window.setTimeout(function () {
      resolve(data);
    }, 1000);
  });
});

Edit: If you're using Bluebird it looks like they have delay operators built in:

http://bluebirdjs.com/docs/api/delay.html

http://bluebirdjs.com/docs/api/promise.delay.html


问:
Javascript element.display = "none" still shows div
So I'm building a website where I create elements with javascript and give content to them stored in array that I get from database, which I was able to successfully accomplish. However, I want to not display the div parent that contains all other elements added through javascript when a user clicks on a button within the div that I want not to display. However, I noticed two problems that I want to figured out why it's worked as it is. First, when I click on the button, and I apply display none to its parent, it always applies display none on the last created div instead of the corresponding div parent of the element it was clicked. Also, even though the display none is applied to the last div (though like I said, I want it to apply display none to the parent of the clicked button), the last div is still displayed on the page though it's display is none.

I need help figuring out these two problems. Any help will be appreciated. Thanks. Btw, please don't mark duplicate because I did look up for similar problems but none of the solutions apply to the problem I'm having.

Here is the javascript code:

```<code>var j = 0;
for (var i = 0; i < array.length; i++) {

    var mydiv = document.createElement('div');
    var element = document.createElement('p');
    var element2 = document.createElement('p');
    var raiseRating = document.createElement('button');
    var lowerRating = document.createElement('button');
    var rating = document.createElement('h1');
    var flag = document.createElement('button');

    // Index is set to hold the id so it can be used to identify the quotations whose button was clicked
    index[i] = array[i][j+3];

    //raiseRating.id = "raiseRating";
    raiseRating.innerHTML = "+";
   // lowerRating.id = "lowerRating";
    lowerRating.innerHTML = "-";
    flag.innerHTML = "flag"

    rating.innerHTML = array[i][j+2];

    element.innerHTML = '\"' + array[i][j] + '\"';
    element2.innerHTML = '\--' + array[i][j+1];
    mydiv.appendChild(element);
    mydiv.appendChild(element2);
    mydiv.appendChild(raiseRating);
    mydiv.appendChild(rating);
    mydiv.appendChild(lowerRating);
    mydiv.appendChild(flag);

   if (document.body.appendChild(mydiv)) {
       flag.addEventListener("click", function(){
           console.log("this should print");
           mydiv.style.display = "none";
           //console.log(mydiv);
       });
   }

}
</code>```

UPDATE: Here is the html since someone asked for it

```<code><!doctype html>
<html lang="en">

<head>
<title>Quotation Service</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Cookie"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet">
</head>

<body>
<div class="top-bar">
    <h1>Quotes</h1>
    <a href="register.php" >Register</a>
    <a href="login.php">Login</a>
    <a href="addQuotes.php">Add Quote</a>

</div>
</body>

</html>
</code>```

答:
I did not know what var array was so I just removed.This should point you in the right direction. The problem is your closures. I commented so you could notice. Read about them!

var j = 0;
            for (var i = 0; i < 10; i++) {

                var mydiv = document.createElement('div');
                var element = document.createElement('p');
                var element2 = document.createElement('p');
                var raiseRating = document.createElement('button');
                var lowerRating = document.createElement('button');
                var rating = document.createElement('h1');
                var flag = document.createElement('button');

                // Index is set to hold the id so it can be used to identify the quotations whose button was clicked

                //raiseRating.id = "raiseRating";
                raiseRating.innerHTML = "+";
               // lowerRating.id = "lowerRating";
                lowerRating.innerHTML = "-";
                flag.innerHTML = "flag"

                mydiv.appendChild(element);
                mydiv.appendChild(element2);
                mydiv.appendChild(raiseRating);
                mydiv.appendChild(rating);
                mydiv.appendChild(lowerRating);
                mydiv.appendChild(flag);

                /** CLOSURE STARTS **/
                (function(flag, node){

               if (document.body.appendChild(node)) {
                   flag.addEventListener("click", function(){
                       console.log("this should print");
                       node.style.display = "none";

                   });
               }
       }(flag, mydiv));
              /**CLOSURE ENDS **/
            }```

Body:
So I'm building a website where I create elements with javascript and give content to them stored in array that I get from database, which I was able to successfully accomplish. However, I want to not display the div parent that contains all other elements added through javascript when a user clicks on a button within the div that I want not to display. However, I noticed two problems that I want to figured out why it's worked as it is. First, when I click on the button, and I apply display none to its parent, it always applies display none on the last created div instead of the corresponding div parent of the element it was clicked. Also, even though the display none is applied to the last div (though like I said, I want it to apply display none to the parent of the clicked button), the last div is still displayed on the page though it's display is none.

I need help figuring out these two problems. Any help will be appreciated. Thanks. Btw, please don't mark duplicate because I did look up for similar problems but none of the solutions apply to the problem I'm having.

Here is the javascript code:

var j = 0;
for (var i = 0; i < array.length; i++) {

    var mydiv = document.createElement('div');
    var element = document.createElement('p');
    var element2 = document.createElement('p');
    var raiseRating = document.createElement('button');
    var lowerRating = document.createElement('button');
    var rating = document.createElement('h1');
    var flag = document.createElement('button');

    // Index is set to hold the id so it can be used to identify the quotations whose button was clicked
    index[i] = array[i][j+3];

    //raiseRating.id = "raiseRating";
    raiseRating.innerHTML = "+";
   // lowerRating.id = "lowerRating";
    lowerRating.innerHTML = "-";
    flag.innerHTML = "flag"

    rating.innerHTML = array[i][j+2];

    element.innerHTML = '\"' + array[i][j] + '\"';
    element2.innerHTML = '\--' + array[i][j+1];
    mydiv.appendChild(element);
    mydiv.appendChild(element2);
    mydiv.appendChild(raiseRating);
    mydiv.appendChild(rating);
    mydiv.appendChild(lowerRating);
    mydiv.appendChild(flag);

   if (document.body.appendChild(mydiv)) {
       flag.addEventListener("click", function(){
           console.log("this should print");
           mydiv.style.display = "none";
           //console.log(mydiv);
       });
   }

}

UPDATE: Here is the html since someone asked for it

<!doctype html>

<title>Quotation Service</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Cookie"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet">

Quotes

    Register
    Login
    Add Quote


问:
react-native No bundle URL present
I get the following error when trying to do react-native run-ios (see screenshot below).  I have checked this answer as well as the github thread but neither were helpful.

Any ideas on what to look at or how to make this work? The problem seems to be isolated to ios, as the android emulator works ok.  Looks like maybe it's some sort of bug with the facebook code.

答:
I also got this error when developing. Try this solution in the simulator:

Hold down shift + cmd + H twice to bring up running apps

Then swipe up on your the app you would like to get rid of.

Click on your app.

This worked for me, after looking through countless solutions this was all I actually needed to do! Hope this helps.

Title: react-native No bundle URL present


问:
Google App Maker User Picker and how to return all values from the Directory model
I am using the User Picker for Google App Maker and it only seems to return the email address.  Before using the User Picker, you need to add the Directory model into your app, which I have done already.

My question is, Is there a way to use that selected email as the key and grab the corresponding record in the Directory model?

I have some code which returns undefined for the 3 values (userFullname, userPhone, and userAddress) I am looking for.

Server Script Code:

```<code>function getUserInfoByEmail(email) {

    var userFullname;
    var userPhone;
    var userAddress;

    console.log("serverCode - getUserInfoByEmail: " + email);

    var query = app.models.Directory.newQuery();

    query.filters.PrimaryEmail._equals = email;
    var records = query.run();
    if (records === null) {
        console.log("serverCode - getUserByEmail() - records is null");
    }
    console.log("serverCode - getUserByEmail() - " + records.length);

    for (var user in records) {

        if (user === null) {
            console.log("serverCode - getUserByEmail() - user is null");
        }

        console.log("serverCode - getUserByEmail() - user: " + user);
        userFullname = user.FullName;
        userPhone = user.PrimaryPhone;
        userAddress = user.PrimaryAddress;

        console.log("serverCode - getUserInfoByEmail - userPhone: " + userPhone);
        console.log("serverCode - getUserInfoByEmail - userAddress: " + userAddress);
        console.log("serverCode - getUserInfoByEmail - userFullname: " + userFullname);

    }
}
</code>```

The null checks do not return null, there are no errors.

Here is the output from the console:

```<code>Tue Nov 14 15:22:17 GMT-700 2017 clientCode - newValue: myemail@this.eml
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail: myemail@this.eml
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserByEmail() - 1
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserByEmail() - user: 0
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail - userPhone: undefined
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail - userAddress: undefined
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail - userFullname: undefined
</code>```

Appreciate any direction and help.

答:
Actually, there are two questions

I am using the User Picker for Google App Maker and it only seems to return the email address.

If you want User Picker to provide you with Directory record, then you can check valueIsRecord checkbox. After that you'll be able to access Directory record through widget.value:

code which returns undefined for the 3 values

You cannot iterate through Array using for...in(learn more) loop in javascript(this construction will give you keys, but not values). You can use forEach(learn more) or old school for loop(learn more).

There is a third option: for...of(learn more), but it is not supported by App Script's javascript implementation.

Body:
I am using the User Picker for Google App Maker and it only seems to return the email address.  Before using the User Picker, you need to add the Directory model into your app, which I have done already.

My question is, Is there a way to use that selected email as the key and grab the corresponding record in the Directory model?

I have some code which returns undefined for the 3 values (userFullname, userPhone, and userAddress) I am looking for.

Server Script Code:

function getUserInfoByEmail(email) {

    var userFullname;
    var userPhone;
    var userAddress;

    console.log("serverCode - getUserInfoByEmail: " + email);

    var query = app.models.Directory.newQuery();

    query.filters.PrimaryEmail._equals = email;
    var records = query.run();
    if (records === null) {
        console.log("serverCode - getUserByEmail() - records is null");
    }
    console.log("serverCode - getUserByEmail() - " + records.length);

    for (var user in records) {

        if (user === null) {
            console.log("serverCode - getUserByEmail() - user is null");
        }

        console.log("serverCode - getUserByEmail() - user: " + user);
        userFullname = user.FullName;
        userPhone = user.PrimaryPhone;
        userAddress = user.PrimaryAddress;

        console.log("serverCode - getUserInfoByEmail - userPhone: " + userPhone);
        console.log("serverCode - getUserInfoByEmail - userAddress: " + userAddress);
        console.log("serverCode - getUserInfoByEmail - userFullname: " + userFullname);

    }
}

The null checks do not return null, there are no errors.

Here is the output from the console:

Tue Nov 14 15:22:17 GMT-700 2017 clientCode - newValue: myemail@this.eml
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail: myemail@this.eml
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserByEmail() - 1
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserByEmail() - user: 0
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail - userPhone: undefined
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail - userAddress: undefined
Tue Nov 14 15:22:18 GMT-700 2017 serverCode - getUserInfoByEmail - userFullname: undefined

Appreciate any direction and help.


问:
How to use redux-persist v5?
I started to learn redux and try to use redux-persist to store data. Since redux-persist was update to v5 now and recommend to use PersistGate. But I could found few documents about PersistGate. I write some code but this error occured PersistGate(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. This is my code:

store.js

```<code>import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import { createStore, applyMiddleware, compose } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import reducer from '../reducers'

const loggerMiddleware = createLogger()

const middleware = [thunk, loggerMiddleware]

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const configureStore = composeEnhancers(
  applyMiddleware(...middleware),
)(createStore)

const config = {
  key: 'root',
  storage,
}

const combinedReducer = persistCombineReducers(config, reducer)

const createAppStore = () => {
  let store = configureStore(combinedReducer)
  let persistor = persistStore(store)

  return { persistor, store }
}

export default createAppStore
</code>```

index.js

```<code>import React from 'react'
import ReactDOM from 'react-dom'
import './assets/css/index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import { Provider } from 'react-redux'
import createAppStore from './store'
import { PersistGate } from 'redux-persist/es/integration/react'

const { persistor, store } = createAppStore()

ReactDOM.render(
  <Provider store={store}>
    <PersistGate persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root'))
registerServiceWorker()
</code>```

compiler throws error in render(). Error message as above.
Would you please tell me how to use PersistGate correctly? Or where could I find more documents or examples? Thank you very much!

答:
If add loading state <Loading /> (which is ur component like spinner or greeking component, it defines the way the app looks when loading data from storage) in PersistGate still not working.

Please confirm that your reducer
import reducer from '../reducers', should be the raw reducer (javascript object), do not apply combineReducers (redux), if you already applied it, then in ur store.js, you should use persistReducer instead of persistCombineReducers as follows

```<code>import { persistReducer } from 'redux-persist'
...
...
const combinedReducer = persistReducer(config, reducer)
...
...
</code>```

Probably it will help fix the problem, if not, please leave a message

Title: How to use redux-persist v5?

Body:
I started to learn redux and try to use redux-persist to store data. Since redux-persist was update to v5 now and recommend to use PersistGate. But I could found few documents about PersistGate. I write some code but this error occured PersistGate(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null. This is my code:

store.js

import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import { createStore, applyMiddleware, compose } from 'redux'
import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage'
import reducer from '../reducers'

const loggerMiddleware = createLogger()

const middleware = [thunk, loggerMiddleware]

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose

const configureStore = composeEnhancers(
  applyMiddleware(...middleware),
)(createStore)

const config = {
  key: 'root',
  storage,
}

const combinedReducer = persistCombineReducers(config, reducer)

const createAppStore = () => {
  let store = configureStore(combinedReducer)
  let persistor = persistStore(store)

  return { persistor, store }
}

export default createAppStore

index.js

import React from 'react'
import ReactDOM from 'react-dom'
import './assets/css/index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import { Provider } from 'react-redux'
import createAppStore from './store'
import { PersistGate } from 'redux-persist/es/integration/react'

const { persistor, store } = createAppStore()

ReactDOM.render(
  <Provider store={store}>
    <PersistGate persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root'))
registerServiceWorker()

compiler throws error in render(). Error message as above.
Would you please tell me how to use PersistGate correctly? Or where could I find more documents or examples? Thank you very much!

Body:
If add loading state <Loading /> (which is ur component like spinner or greeking component, it defines the way the app looks when loading data from storage) in PersistGate still not working.

Please confirm that your reducer
import reducer from '../reducers', should be the raw reducer (javascript object), do not apply combineReducers (redux), if you already applied it, then in ur store.js, you should use persistReducer instead of persistCombineReducers as follows

import { persistReducer } from 'redux-persist'
...
...
const combinedReducer = persistReducer(config, reducer)
...
...

Probably it will help fix the problem, if not, please leave a message


问:
vector.size() returns 1 even though there are more than 1 elements in it?
So I am new to vectors in C++, my goal is to read a line from file store it in a string vector, transform it to integers and push it to an int vector. I came across the problem that when I transform char to int I loose leading 0s. I want to retain the leading 0s (The file is a matrix file). I am storing the final file in a 2D int vector. When I run temp.size() I get the result as 1, I know this is something to do with how I converted the string to integers and so I believe there is only 1 number being stored in the vector.

```<code>std::vector< std::vector<int> > data;
std::vector< std::vector<int> > res;
std::ifstream f("input.txt", ios::binary);
string line;
int count;
while(std::getline(f,line))
{
  std::vector<string> line_data;
  std::vector<int> temp;
  std::istringstream iss(line);
  std::string value;
  while(iss >> value)
    {

        line_data.push_back(value);
        std::transform(line_data.begin(), line_data.end(),
                    std::back_inserter(temp),
                    [](std::string &s) {    return std::stoi(s); } );

    count = value.length();

    count = count - temp.size(); // temp.size() returns 1, why is that and how can I fix it?
        cout << count <<endl;
        temp.insert(temp.begin(),count,0);
  data.push_back(temp);

}
</code>```

My input is a Boolean square matrix of unknown length. say for example :

```<code>00101
10101
10100
00101
01111
</code>```

EDIT:

when getting an output from int vector data:

```<code>101
10101
10100
101
1111
</code>```

lost leading 0s

so I tried to calculate the difference in lengths of value and temp and insert the 0's manually.

答:
Why are you using binary mode for text data? Simplified it a little bit, so it comes to:

```<code>#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

int main()
{
    std::ifstream f("input.txt");
    std::vector< std::vector<int> > data;
    std::string line;

    // fill data
    while (std::getline(f, line))
    {
        std::vector<int> temp;
        std::transform(line.begin(), line.end(),
            std::back_inserter(temp),
            [](char c) {  return std::stoi(std::string(&c, 1)); });

        data.push_back(temp);
    }

    // print data
    for (std::vector<int> x : data)
    {
        for (int y : x)
            std::cout << y;

        std::cout << std::endl;
    }

    return 0;
}
</code>```

Prints:

```<code>00101
10101
10100
00101
01111
</code>```

Body:
So I am new to vectors in C++, my goal is to read a line from file store it in a string vector, transform it to integers and push it to an int vector. I came across the problem that when I transform char to int I loose leading 0s. I want to retain the leading 0s (The file is a matrix file). I am storing the final file in a 2D int vector. When I run temp.size() I get the result as 1, I know this is something to do with how I converted the string to integers and so I believe there is only 1 number being stored in the vector.

std::vector< std::vector<int> > data;
std::vector< std::vector<int> > res;
std::ifstream f("input.txt", ios::binary);
string line;
int count;
while(std::getline(f,line))
{
  std::vector<string> line_data;
  std::vector<int> temp;
  std::istringstream iss(line);
  std::string value;
  while(iss >> value)
    {

        line_data.push_back(value);
        std::transform(line_data.begin(), line_data.end(),
                    std::back_inserter(temp),
                    [](std::string &s) {    return std::stoi(s); } );

    count = value.length();

    count = count - temp.size(); // temp.size() returns 1, why is that and how can I fix it?
        cout << count <<endl;
        temp.insert(temp.begin(),count,0);
  data.push_back(temp);

}

My input is a Boolean square matrix of unknown length. say for example :

00101
10101
10100
00101
01111

EDIT:

when getting an output from int vector data:

101
10101
10100
101
1111

lost leading 0s

so I tried to calculate the difference in lengths of value and temp and insert the 0's manually.

Body:
Why are you using binary mode for text data? Simplified it a little bit, so it comes to:

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

int main()
{
    std::ifstream f("input.txt");
    std::vector< std::vector<int> > data;
    std::string line;

    // fill data
    while (std::getline(f, line))
    {
        std::vector<int> temp;
        std::transform(line.begin(), line.end(),
            std::back_inserter(temp),
            [](char c) {  return std::stoi(std::string(&c, 1)); });

        data.push_back(temp);
    }

    // print data
    for (std::vector<int> x : data)
    {
        for (int y : x)
            std::cout << y;

        std::cout << std::endl;
    }

    return 0;
}

Prints:

00101
10101
10100
00101
01111


问:
Loop through words in a string
I've seen a lot of javascript stack questions around this, but nothing specifically related to SQL Server.

What I need to do is accept a string value and do a loop over the string multiple times to get back all the individual words so I can do calculations on them.

A rough idea is shown below. Anyone know how this can be achieved?

```<code>Declare @String nvarchar(50) = 'Mary had a little lamb'
Declare @word nvarchar(50)

Start Loop 1 to 5
    Set @word = 'Mary' (1)
    Set @word = 'had' (2)
    Set @word = 'a' (3)
    Set @word = 'little' (4)
    Set @word = 'lamb' (5)
End Loop
</code>```

答:
This looks to do the job. </p>

```<code>DECLARE @tags NVARCHAR(400) = 'mary had a little lamb'

SELECT value
FROM STRING_SPLIT(@tags, ' ')
</code>```

Title: Loop through words in a string

Body:
I've seen a lot of javascript stack questions around this, but nothing specifically related to SQL Server.

What I need to do is accept a string value and do a loop over the string multiple times to get back all the individual words so I can do calculations on them.

A rough idea is shown below. Anyone know how this can be achieved?

Declare @String nvarchar(50) = 'Mary had a little lamb'
Declare @word nvarchar(50)

Start Loop 1 to 5
    Set @word = 'Mary' (1)
    Set @word = 'had' (2)
    Set @word = 'a' (3)
    Set @word = 'little' (4)
    Set @word = 'lamb' (5)
End Loop

Body:
This looks to do the job.

DECLARE @tags NVARCHAR(400) = 'mary had a little lamb'

SELECT value
FROM STRING_SPLIT(@tags, ' ')


问:
Angular Material SideNav Content Strategy
I have a standard sidenav layout along the lines of this

```<code><mat-sidenav-container>

   <mat-toolbar></mat-toolbar>

   <router-outlet></router-outlet>

   <mat-sidenav></mat-sidenav>
   <mat-sidenav position="end"></mat-sidenav>

</mat-sidenav-container>
</code>```

I want to use that second sidenav as a content area.

On this project, all of the active routes are simply Components with a Canvas Region and some basic information about the "Experiment". Perhaps some basic form sliders or controls.

```<code><div>
   Some Content
<div>
<canvas>
</canvas>
</code>```

Basically I want the content div to go in the second sidenav container. Only the Canvas is a child of the actual component visually.

```<code><mat-sidenav-container>

   <mat-toolbar></mat-toolbar>

   <router-outlet>
        <canvas-component>
             <canvas></canvas>
        </canvas-component>
   </router-outlet>

   <mat-sidenav></mat-sidenav>
   <mat-sidenav position="end">
       <div>
            Some Content
       <div>
   </mat-sidenav>

</mat-sidenav-container>
</code>```

This seems crazy, i don't think a child should be reaching out this way and depending on a parents structure. I get that. The inverse, of having the Component add a sidenav would be much better but the sidenav has to belong to a sidenav container and so this is still outside the boundaries of the component.

So what is the best strategy instead? I can't seem to get my head around it.  Would you see this as 2 components , requiring 2 outer outlets and needing a shared service so they can talk to each other?  Is there a better way?

答:
If I understand correctly:

Only the "canvas" sidenav should have the <router-outlet>.

If the "canvas" sidenav depends on any other component for its data, you need to extract that logic into a separate service. This way, your "canvas" sidenav could independently get its data from it.

If you still need two different outlets in your template, you should use aux routing, BUT - if your main content area (the homepage) is static - you don't need a route to display it, use the "home" component in your template and keep the <router-outlet> only in your "canvas" sidenav

Hope this helps!

Body:
I have a standard sidenav layout along the lines of this

<mat-sidenav-container>

   <mat-toolbar></mat-toolbar>

   <router-outlet></router-outlet>

   <mat-sidenav></mat-sidenav>
   <mat-sidenav position="end"></mat-sidenav>

</mat-sidenav-container>

I want to use that second sidenav as a content area.

On this project, all of the active routes are simply Components with a Canvas Region and some basic information about the "Experiment". Perhaps some basic form sliders or controls.

   Some Content

<canvas>
</canvas>

Basically I want the content div to go in the second sidenav container. Only the Canvas is a child of the actual component visually.

<mat-sidenav-container>

   <mat-toolbar></mat-toolbar>

   <router-outlet>
        <canvas-component>
             <canvas></canvas>
        </canvas-component>
   </router-outlet>

   <mat-sidenav></mat-sidenav>
   <mat-sidenav position="end">

            Some Content

   </mat-sidenav>

</mat-sidenav-container>

This seems crazy, i don't think a child should be reaching out this way and depending on a parents structure. I get that. The inverse, of having the Component add a sidenav would be much better but the sidenav has to belong to a sidenav container and so this is still outside the boundaries of the component.

So what is the best strategy instead? I can't seem to get my head around it.  Would you see this as 2 components , requiring 2 outer outlets and needing a shared service so they can talk to each other?  Is there a better way?


问:
Is there any way to add a letter to the bottom left area of a UIKeyboardType.NumberPad?
The UIKeyboardType.NumberPad looks like this:

What I want it to look like is this:

Is there a way to overlay a view in just that corner when the keyboard is up to add this single key? Is this possible with Swift 4?

The reason I want to do this is for easy ISBN number input for users, and some ISBN numbers (10 digits) have an X in them.

答:
There is no way to modify the keyboard and any attempt to position a button in the correct spot will be a hack you want to avoid.

Probably the cleanest solution is to create a toolbar and set the toolbar as the text field's inputAccessoryView. On the toolbar, add a button for your X and maybe some other buttons such as a keyboard dismiss button, a Next button, or a Done button, etc.


问:
Code Style Testing for Chef using Jenkins and GitHub organizations
Currently, we commit Chef cookbooks to individual repos within our GitHub organization.  We are configuring a Jenkins job per repo / cookbook which will execute cookstyle first when a commit occurs, and if cookstyle passes with no issues, it will execute Test Kitchen. We have a template Jenkins job we copy and configure for each cookbook we create.

Does anyone know if it's possible to have GitHub hooks in Jenkins to listen for commit events across the entire organization, and then execute cookstyle on a repo where a commit occurred that contain a Chef cookbook?  I'd like to have one central job handling the lint testing for our organization.

答: You wouldn't generally use a single job for this. You would use the GitHub Organization support to scan for all repositories and build them when they change. You can use webhooks to ping individual repos.</p>


问:
Place text under an image without moving the image(s)?
I've got a couple of images lined up next to each other, that part works fine. However, I want to place text under each of the images, but when i try to do so (by using 'br' or by creating its own 'div') the image creates its own row and pushes the other images down. I understand why it does that but I find it difficult to fix the issue. Here is my code:

```<code><div class="container-team">
    <div class="team">
        <h2>Our team</h2>
        <div class="team-members">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
            <img src="test1.png">
        </div>
    </div>
</div>

.container-team {
    background-color: #eee;
    display:block;
    overflow:auto;
    width: 100%;
}

.team {
    margin:0 auto;
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
}

.team h2 {
    color: #0E8DBD;
    padding-top: 40px;
    padding-left: 5%;
    padding-bottom: 100px;
    font-size: 32px;
    text-transform: uppercase;
}

.team-members {
    background: #eee;
    width: 100%;
    display:block;
    overflow:auto;
    margin: 0 auto;
    text-align: center;
}

.team-members img {
    width: 180px;
    height: 180px;
    margin: 20px;
}
</code>```

Here are also 2 images to make it more clear of what's happening:

This is what it currently looks like

This is what happens when I give an image its own 'div'

any help is appreciated, thank you for your time.

答:
The display property of div elements are block by default. Try something like this:

```<code><div class="team-member">
  <img src="image.png">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

.team-member {
  display: inline-block;
  width: 180px;
}
</code>```

Take a look at this working example. Hope this is the result you want to achieve: https://fiddle.jshell.net/ogocx9s5/

Body:
I've got a couple of images lined up next to each other, that part works fine. However, I want to place text under each of the images, but when i try to do so (by using 'br' or by creating its own 'div') the image creates its own row and pushes the other images down. I understand why it does that but I find it difficult to fix the issue. Here is my code:

Our team

.container-team {
    background-color: #eee;
    display:block;
    overflow:auto;
    width: 100%;
}

.team {
    margin:0 auto;
    width: 100%;
    padding-left: 30px;
    padding-right: 30px;
}

.team h2 {
    color: #0E8DBD;
    padding-top: 40px;
    padding-left: 5%;
    padding-bottom: 100px;
    font-size: 32px;
    text-transform: uppercase;
}

.team-members {
    background: #eee;
    width: 100%;
    display:block;
    overflow:auto;
    margin: 0 auto;
    text-align: center;
}

.team-members img {
    width: 180px;
    height: 180px;
    margin: 20px;
}

Here are also 2 images to make it more clear of what's happening:

This is what it currently looks like

This is what happens when I give an image its own 'div'

any help is appreciated, thank you for your time.

Body:
The display property of div elements are block by default. Try something like this:

<div class="team-member">
  <img src="image.png">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>

.team-member {
  display: inline-block;
  width: 180px;
}

Take a look at this working example. Hope this is the result you want to achieve: https://fiddle.jshell.net/ogocx9s5/


问:
ImportError: No module named 'spacy.en'
I'm working on a codebase that uses Spacy. I installed spacy using:

```<code>sudo pip3 install spacy
</code>```

and then

```<code>sudo python3 -m spacy download en
</code>```

At the end of this last command, I got a message:

```<code>    Linking successful
/home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm -->
/home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en

You can now load the model via spacy.load('en')
</code>```

Now, when I try running my code, on the line:

```<code>    from spacy.en import English
</code>```

it gives me the following error:

```<code>ImportError: No module named 'spacy.en'
</code>```

I've looked on Stackexchange and the closest is:  Import error with spacy: "No module named en"
which does not solve my problem.

Any help would be appreciated. Thanks.

Edit: I might have solved this by doing the following:

```<code> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spacy
>>> spacy.load('en')
<spacy.lang.en.English object at 0x7ff414e1e0b8>
</code>```

and then using:

```<code>from spacy.lang.en import English
</code>```

I'm still keeping this open in case there are any other answers.

答:
Yes, I can confirm that your solution is correct. The version of spaCy you downloaded from pip is v2.0, which includes a lot of new features, but also a few changes to the API. One of them is that all language data has been moved to a submodule spacy.lang to keep thing cleaner and better organised. So instead of using spacy.en, you now import from spacy.lang.en.

```<code>- from spacy.en import English
+ from spacy.lang.en import English
</code>```

However, it's also worth mentioning that what you download when you run spacy download en is not the same as spacy.lang.en. The language data shipped with spaCy includes the static data like tokenization rules, stop words or lemmatization tables. The en package that you can download is a shortcut for the statistical model en_core_web_sm. It includes the language data, as well as binary weight to enable spaCy to make predictions for part-of-speech tags, dependencies and named entities.

Instead of just downloading en, I'd actually recommend using the full model name, which makes it much more obvious what's going on:

python -m spacy download en_core_web_sm
```

<pre class="lang-py prettyprint-override"><code>nlp = spacy.load("en_core_web_sm")
</code>```

When you call spacy.load, spaCy does the following:

Find the installed model named "en_core_web_sm" (a package or shortcut link).

Read its meta.json and check which language it's using (in this case, spacy.lang.en), and how its processing pipeline should look (in this case, tagger, parser and ner).

Initialise the language class and add the pipeline to it.

Load in the binary weights from the model data so pipeline components (like the tagger, parser or entity recognizer) can make predictions.

See this section in the docs for more details.

Title: ImportError: No module named 'spacy.en'

Body:
I'm working on a codebase that uses Spacy. I installed spacy using:

sudo pip3 install spacy

and then

sudo python3 -m spacy download en

At the end of this last command, I got a message:

    Linking successful
/home/rayabhik/.local/lib/python3.5/site-packages/en_core_web_sm -->
/home/rayabhik/.local/lib/python3.5/site-packages/spacy/data/en

You can now load the model via spacy.load('en')

Now, when I try running my code, on the line:

    from spacy.en import English

it gives me the following error:

ImportError: No module named 'spacy.en'

I've looked on Stackexchange and the closest is:  Import error with spacy: "No module named en"
which does not solve my problem.

Any help would be appreciated. Thanks.

Edit: I might have solved this by doing the following:

 Python 3.5.2 (default, Sep 14 2017, 22:51:06)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import spacy
>>> spacy.load('en')
<spacy.lang.en.English object at 0x7ff414e1e0b8>

and then using:

from spacy.lang.en import English

I'm still keeping this open in case there are any other answers.

Body:
Yes, I can confirm that your solution is correct. The version of spaCy you downloaded from pip is v2.0, which includes a lot of new features, but also a few changes to the API. One of them is that all language data has been moved to a submodule spacy.lang to keep thing cleaner and better organised. So instead of using spacy.en, you now import from spacy.lang.en.

- from spacy.en import English
+ from spacy.lang.en import English

However, it's also worth mentioning that what you download when you run spacy download en is not the same as spacy.lang.en. The language data shipped with spaCy includes the static data like tokenization rules, stop words or lemmatization tables. The en package that you can download is a shortcut for the statistical model en_core_web_sm. It includes the language data, as well as binary weight to enable spaCy to make predictions for part-of-speech tags, dependencies and named entities.

Instead of just downloading en, I'd actually recommend using the full model name, which makes it much more obvious what's going on:

python -m spacy download en_core_web_sm

nlp = spacy.load("en_core_web_sm")

When you call spacy.load, spaCy does the following:

Find the installed model named "en_core_web_sm" (a package or shortcut link).

Read its meta.json and check which language it's using (in this case, spacy.lang.en), and how its processing pipeline should look (in this case, tagger, parser and ner).

Initialise the language class and add the pipeline to it.

Load in the binary weights from the model data so pipeline components (like the tagger, parser or entity recognizer) can make predictions.

See this section in the docs for more details.


问:
Branch And Bound Implementation for TSP in Java
I wonder if there is a useful Java implementation of a Branch And Bound algorithm for the TSP or in general a OR framework which includes a BnB for TSP.

Thanks for your help!

Marco

答:
BnB typically interacts with a complete sub-problem solver:

```<code>best_cost_soln_so_far = +inf
while (better_cost_soln = search_for_soln_cheaper_than(best_cost_soln_so_far))
{
    best_cost_soln_so_far = better_cost_soln
    backtrack_into_search
}
</code>```

That is, your sub-problem search will backtrack whenever the cost of any partial solution it is exploring exceeds the bound set by best_cost_soln_so_far.  If the sub-problem search does find a better solution, best_cost_soln_so_far is updated, and the search continues from where it left off, looking for a still better solution.  It's pretty easy to implement.

That said, I doubt very much that you want to tackle large TSPs using complete search because of the huge search spaces involved; you may do better with approximate techniques such as simulated annealing.

ContentLicense: CC BY-SA 2.5

Body:
BnB typically interacts with a complete sub-problem solver:

best_cost_soln_so_far = +inf
while (better_cost_soln = search_for_soln_cheaper_than(best_cost_soln_so_far))
{
    best_cost_soln_so_far = better_cost_soln
    backtrack_into_search
}

That is, your sub-problem search will backtrack whenever the cost of any partial solution it is exploring exceeds the bound set by best_cost_soln_so_far.  If the sub-problem search does find a better solution, best_cost_soln_so_far is updated, and the search continues from where it left off, looking for a still better solution.  It's pretty easy to implement.

That said, I doubt very much that you want to tackle large TSPs using complete search because of the huge search spaces involved; you may do better with approximate techniques such as simulated annealing.


问:
How to map multiple fields into one destination field using modelmapper
How to map/merge multiple fields into one field? Like concatenate a firstname and lastname to the destination fullname?

```<code>public class ModelMapperConfigTest {

    @Test
    public void should_validate() {
        new ModelMapperConfig().modelMapper().validate();
    }

    @Data
    public static class Person {
        private String firstname;
        private String lastname;
    }

    @Data
    public static class PersonDto {
        private String firstname;
        private String lastname;
        private String fullname;
    }

    // Test data

    @Test
    public void should_map_multiple_fields_into_one() {

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        // TODO: Configure modelmapper to merge the two fields

        // test that all fields are mapped
        modelMapper.validate();

        // test that the age is calculated
        Person person = new Person();
        person.setFirstname("Marilyn");
        person.setLastname("Monroe");
        PersonDto personDto = modelMapper.map(person, PersonDto.class);
        assertEquals(personDto.fullname, "Marilyn Monroe");
    }

    // This method should be used for mapping. In real, this could be a service call
    private String generateFullname(String firstname, String lastname) {
        return firstname + " " + lastname;
    }
}
</code>```

答:
You can use a Converter within a PropertyMap for this.

Just configure your mapper like this:

```<code>@Test
public void should_map_multiple_fields_into_one() {

    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

    modelMapper.createTypeMap(Person.class, PersonDto.class)
            .addMappings(
                    new PropertyMap<Person, PersonDto>() {
                        @Override
                        protected void configure() {
                            // define a converter that takes the whole "person"
                            using(ctx -> generateFullname(
                                    ((Person) ctx.getSource()).getFirstname(),
                                    ((Person) ctx.getSource()).getLastname())
                            )
                            // Map the compliete source here
                            .map(source, destination.getFullname());
                        }
                    });

    // test that all fields are mapped
    modelMapper.validate();

    // test that the age is calculated
    Person person = new Person();
    person.setFirstname("Marilyn");
    person.setLastname("Monroe");
    PersonDto personDto = modelMapper.map(person, PersonDto.class);
    assertEquals(personDto.fullname, "Marilyn Monroe");
}

// This method should be used for mapping. In real, this could be a service call
private String generateFullname(String firstname, String lastname) {
    return firstname + " " + lastname;
}
</code>```

Body:
How to map/merge multiple fields into one field? Like concatenate a firstname and lastname to the destination fullname?

public class ModelMapperConfigTest {

    @Test
    public void should_validate() {
        new ModelMapperConfig().modelMapper().validate();
    }

    @Data
    public static class Person {
        private String firstname;
        private String lastname;
    }

    @Data
    public static class PersonDto {
        private String firstname;
        private String lastname;
        private String fullname;
    }

    // Test data

    @Test
    public void should_map_multiple_fields_into_one() {

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        // TODO: Configure modelmapper to merge the two fields

        // test that all fields are mapped
        modelMapper.validate();

        // test that the age is calculated
        Person person = new Person();
        person.setFirstname("Marilyn");
        person.setLastname("Monroe");
        PersonDto personDto = modelMapper.map(person, PersonDto.class);
        assertEquals(personDto.fullname, "Marilyn Monroe");
    }

    // This method should be used for mapping. In real, this could be a service call
    private String generateFullname(String firstname, String lastname) {
        return firstname + " " + lastname;
    }
}

Body:
You can use a Converter within a PropertyMap for this.

Just configure your mapper like this:

@Test
public void should_map_multiple_fields_into_one() {

    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

    modelMapper.createTypeMap(Person.class, PersonDto.class)
            .addMappings(
                    new PropertyMap<Person, PersonDto>() {
                        @Override
                        protected void configure() {
                            // define a converter that takes the whole "person"
                            using(ctx -> generateFullname(
                                    ((Person) ctx.getSource()).getFirstname(),
                                    ((Person) ctx.getSource()).getLastname())
                            )
                            // Map the compliete source here
                            .map(source, destination.getFullname());
                        }
                    });

    // test that all fields are mapped
    modelMapper.validate();

    // test that the age is calculated
    Person person = new Person();
    person.setFirstname("Marilyn");
    person.setLastname("Monroe");
    PersonDto personDto = modelMapper.map(person, PersonDto.class);
    assertEquals(personDto.fullname, "Marilyn Monroe");
}

// This method should be used for mapping. In real, this could be a service call
private String generateFullname(String firstname, String lastname) {
    return firstname + " " + lastname;
}


问:
Building a Transition Matrix using words in Python/Numpy
Im trying to build a 3x3 transition matrix with this data

```<code>days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']
</code>```

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

```<code>self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix
</code>```

for every type of weather I need to calculate the probability for the next day

答:
Convert the reports from the days into index codes.

Iterate through the array, grabbing the codes for yesterday's weather and today's.

Use those indices to tally the combination in your 3x3 matrix.

Here's the coding set-up to get you started.

```<code>report = [
  'rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

weather_dict = {"sun":0, "clouds":1, "rain": 2}
weather_code = [weather_dict[day] for day in report]
print weather_code

for n in range(1, len(weather_code)):
    yesterday_code = weather_code[n-1]
    today_code     = weather_code[n]

# You now have the indicies you need for your 3x3 matrix.
</code>```

Body:
Im trying to build a 3x3 transition matrix with this data

days=['rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

Currently, Im doing it with some temp dictionaries and some list that calculates the probability of each weather separately. Its not a pretty solution. Can someone please guide me with a more reasonable solution to this problem?

self.transitionMatrix=np.zeros((3,3))

#the columns are today
sun_total_count = 0
temp_dict={'sun':0, 'clouds':0, 'rain':0}
total_runs = 0
for (x, y), c in Counter(zip(data, data[1:])).items():
    #if column 0 is sun
    if x is 'sun':
        #find the sum of all the numbers in this column
        sun_total_count +=  c
        total_runs += 1
        if y is 'sun':
            temp_dict['sun'] = c
        if y is 'clouds':
            temp_dict['clouds'] = c
        if y is 'rain':
            temp_dict['rain'] = c

        if total_runs is 3:
            self.transitionMatrix[0][0] = temp_dict['sun']/sun_total_count
            self.transitionMatrix[1][0] = temp_dict['clouds']/sun_total_count
            self.transitionMatrix[2][0] = temp_dict['rain']/sun_total_count

return self.transitionMatrix

for every type of weather I need to calculate the probability for the next day

Body:
Convert the reports from the days into index codes.

Iterate through the array, grabbing the codes for yesterday's weather and today's.

Use those indices to tally the combination in your 3x3 matrix.

Here's the coding set-up to get you started.

report = [
  'rain', 'rain', 'rain', 'clouds', 'rain', 'sun', 'clouds', 'clouds',
  'rain', 'sun', 'rain', 'rain', 'clouds', 'clouds', 'sun', 'sun',
  'clouds', 'clouds', 'rain', 'clouds', 'sun', 'rain', 'rain', 'sun',
  'sun', 'clouds', 'clouds', 'rain', 'rain', 'sun', 'sun', 'rain',
  'rain', 'sun', 'clouds', 'clouds', 'sun', 'sun', 'clouds', 'rain',
  'rain', 'rain', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds', 'sun',
  'clouds', 'clouds', 'sun', 'clouds', 'rain', 'sun', 'sun', 'sun',
  'clouds', 'sun', 'rain', 'sun', 'sun', 'sun', 'sun', 'clouds',
  'rain', 'clouds', 'clouds', 'sun', 'sun', 'sun', 'sun', 'sun', 'sun',
  'clouds', 'clouds', 'clouds', 'clouds', 'clouds', 'sun', 'rain',
  'rain', 'rain', 'clouds', 'sun', 'clouds', 'clouds', 'clouds', 'rain',
  'clouds', 'rain', 'sun', 'sun', 'clouds', 'sun', 'sun', 'sun', 'sun',
  'sun', 'sun', 'rain']

weather_dict = {"sun":0, "clouds":1, "rain": 2}
weather_code = [weather_dict[day] for day in report]
print weather_code

for n in range(1, len(weather_code)):
    yesterday_code = weather_code[n-1]
    today_code     = weather_code[n]

# You now have the indicies you need for your 3x3 matrix.


问:
sed - how to replace line based on pattern?
I have a Macros file which has, amongst other things, variable definitions like these:

```<code>SLIBS+=# USERDEFINED $(shell $(NETCDF_PATH)/bin/nc-config --flibs)

CFLAGS:= -gopt -Mlist -time
</code>```

and I am trying to replace the contents of both SLIBS+= and CFLAGS:= using sed.

For example, I am trying to replace

```<code>SLIBS+=# USERDEFINED $(shell $(NETCDF_PATH)/bin/nc-config --flibs)
</code>```

with

```<code>SLIBS+= -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -lnetcdff -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -L/sw/arcts/centos7/hdf5/1.8.16-pgi-16.4/lib -lnetcdf -lnetcdf -llapack -lblas
</code>```

by using this command:

```<code>sed -i "s:SLIBS+=:SLIBS+= -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -lnetcdff -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -L/sw/arcts/centos7/hdf5/1.8.16-pgi-16.4/lib -lnetcdf -lnetcdf -llapack -lblas:g" Macros
</code>```

but the new content is being appended to the old content, instead of replacing the old content.

What am I doing wrong?

Also, how could I do the same with the CFLAGS variable, replacing

```<code>CFLAGS:= -gopt -Mlist -time
</code>```

with

```<code>CFLAGS:= -gopt -Mlist -time -I/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/include -I/sw/arcts/centos7/hdf5/1.8.16-pgi-16.4/include
</code>```

?

答:
You're just missing a regex subexpression to capture "whatever else is on the line after SLIBS+=". As a result, only exactly SLIBS+= is being replaced, and the text after that is remaining (so looks like its been appended).

Replacing your sed command with eg.

```<code>sed -i 's:SLIBS+=.*:SLIBS+= ... :g' Macros
</code>```

should do the trick (note the added .* to match any number of other characters and the ' to prevent the shell escaping *).

This approach should work for your CFLAGS as well.

Body:
I have a Macros file which has, amongst other things, variable definitions like these:

SLIBS+=# USERDEFINED $(shell $(NETCDF_PATH)/bin/nc-config --flibs)

CFLAGS:= -gopt -Mlist -time

and I am trying to replace the contents of both SLIBS+= and CFLAGS:= using sed.

For example, I am trying to replace

SLIBS+=# USERDEFINED $(shell $(NETCDF_PATH)/bin/nc-config --flibs)

with

SLIBS+= -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -lnetcdff -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -L/sw/arcts/centos7/hdf5/1.8.16-pgi-16.4/lib -lnetcdf -lnetcdf -llapack -lblas

by using this command:

sed -i "s:SLIBS+=:SLIBS+= -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -lnetcdff -L/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/lib -L/sw/arcts/centos7/hdf5/1.8.16-pgi-16.4/lib -lnetcdf -lnetcdf -llapack -lblas:g" Macros

but the new content is being appended to the old content, instead of replacing the old content.

What am I doing wrong?

Also, how could I do the same with the CFLAGS variable, replacing

CFLAGS:= -gopt -Mlist -time

with

CFLAGS:= -gopt -Mlist -time -I/sw/arcts/centos7/netcdf/4.4.1/pgi-16.4-hdf5-1.8.16/include -I/sw/arcts/centos7/hdf5/1.8.16-pgi-16.4/include

?

Body:
You're just missing a regex subexpression to capture "whatever else is on the line after SLIBS+=". As a result, only exactly SLIBS+= is being replaced, and the text after that is remaining (so looks like its been appended).

Replacing your sed command with eg.

sed -i 's:SLIBS+=.*:SLIBS+= ... :g' Macros

should do the trick (note the added .* to match any number of other characters and the ' to prevent the shell escaping *).

This approach should work for your CFLAGS as well.


问:
Import tests from one Unit test target into another
We started to split our swift iOS app into multiple frameworks to speed up our TDD feedback cycle. Each of these framework is a project with it's own unit test target. All of these are part of a larger workspace.

The issue is we can't run multiple test targets with our current CI setup. I was wondering if it's possible to bundle together all of our test targets into one for CI but keep them separated for development (maybe by importing/running tests from all the different targets into a "CI unit test target")?

答:
You could certainly add another target and add REFERENCES to the files for the unit tests. They may more may not need modification of the module import names. A file may be referenced in multiple projects, and this could even be automated, as there are tools such as PBXProj for python to allow reading/writing of the Xcode project.

Alternatively, but I am not sure, it may be possible to create an aggregate target with the other items added - this is just speculation.

Perhaps a better question is why can't multiple test targets be run? Surely a script or fast lane could help?


问:
How to AddHandler to Multiple Items and Properly Reference Said Handler
I'm writing a program wherein I need to create GotFocus and LostFocus event handlers for every text box.

What I have now creates an error whenever any text box in the form is clicked on:

```<code>Private Sub lblTotalWeight_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each cnt In Me.Controls.OfType(Of TextBox)
            AddHandler cnt.GotFocus, AddressOf txtBox_GotFocus
        Next

    End Sub

    Private Sub txtBox_GotFocus(sender As System.Object, e As System.EventArgs)
        Dim textBox As TextBox = Me.Controls.OfType(Of TextBox)
        textBox.ForeColor = Color.White
        textBox.BackColor = Color.LightGray
    End Sub
</code>```

I'm getting an error with the Dim textBox as TextBox = Me.Controls.OfType(Of TextBox), and I have no idea why or how to fix it.

There will be another Private Sub for a lost focus event that will be nearly identical, if it helps.

Any help would be appreciated

答:
Me.Controls.OfType(Of TextBox) returns a list of controls that are textboxes. It works great in your AddHandler call, but in your event handler you need to use sender as Textbox instead.

```<code> Dim textBox As TextBox = DirectCast(sender, Textbox)
</code>```

Body:
I'm writing a program wherein I need to create GotFocus and LostFocus event handlers for every text box.

What I have now creates an error whenever any text box in the form is clicked on:

Private Sub lblTotalWeight_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For Each cnt In Me.Controls.OfType(Of TextBox)
            AddHandler cnt.GotFocus, AddressOf txtBox_GotFocus
        Next

    End Sub

    Private Sub txtBox_GotFocus(sender As System.Object, e As System.EventArgs)
        Dim textBox As TextBox = Me.Controls.OfType(Of TextBox)
        textBox.ForeColor = Color.White
        textBox.BackColor = Color.LightGray
    End Sub

I'm getting an error with the Dim textBox as TextBox = Me.Controls.OfType(Of TextBox), and I have no idea why or how to fix it.

There will be another Private Sub for a lost focus event that will be nearly identical, if it helps.

Any help would be appreciated

Body:
Me.Controls.OfType(Of TextBox) returns a list of controls that are textboxes. It works great in your AddHandler call, but in your event handler you need to use sender as Textbox instead.

 Dim textBox As TextBox = DirectCast(sender, Textbox)


问:
How to change Bootstrap navbar collapse breakpoint
Currently when the browser width drops below 768px, the navbar changes to collapsed mode. I want to change this width to 1000px so when the browser is below 1000px the navbar changes to collapsed mode. I want to do this without using LESS, I am using stylus not LESS.

My issue is the same as in this question: Bootstrap 3 Navbar Collapse

But all the answers in that questions explain how to do it by changing LESS variable. I haven't been dealing with LESS, I am using stylus so I want to know how this can be done using stylus or another method.

Thanks!

答:
This worked for me Bootstrap3

```<code>@media (min-width: 768px) {
    .navbar-header {
          float: none;
      }
      .navbar-toggle {
          display: block;
      }
      .navbar-collapse {
          border-top: 1px solid transparent;
          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
      }
      .navbar-collapse.collapse {
          display: none!important;
      }
      .navbar-collapse.collapse.in {
          display: block!important;
      }
      .navbar-nav {
          float: none!important;
          margin: 7.5px -15px;
      }
      .navbar-nav>li {
          float: none;
      }
      .navbar-nav>li>a {
          padding-top: 10px;
          padding-bottom: 10px;
      }
}
</code>```

Took a while to figure these two out:

```<code>.navbar-collapse.collapse {
   display: none!important;
}
.navbar-collapse.collapse.in {
   display: block!important;
}
</code>```

Body:
This worked for me Bootstrap3

@media (min-width: 768px) {
    .navbar-header {
          float: none;
      }
      .navbar-toggle {
          display: block;
      }
      .navbar-collapse {
          border-top: 1px solid transparent;
          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
      }
      .navbar-collapse.collapse {
          display: none!important;
      }
      .navbar-collapse.collapse.in {
          display: block!important;
      }
      .navbar-nav {
          float: none!important;
          margin: 7.5px -15px;
      }
      .navbar-nav>li {
          float: none;
      }
      .navbar-nav>li>a {
          padding-top: 10px;
          padding-bottom: 10px;
      }
}

Took a while to figure these two out:

.navbar-collapse.collapse {
   display: none!important;
}
.navbar-collapse.collapse.in {
   display: block!important;
}


问:
Check create duplicate for soft delete
I had a database table named country. Each country has name and removed column. When user create a new country with name, a new row with name together with removed default 0 will be created. I had created unique index for name and removed columns.

What I want right now is able to create new row with name and removed 0 uniquely and also update with replace into where removed 1 or update the existing row where removed 0.

```<code>INSERT INTO country (name, removed) VALUES ('United State',0) ON DUPLICATE KEY UPDATE name = VALUES(name), removed = 1
SELECT name FROM country WHERE removed = 1
</code>```

Condition

```<code>// If name doesn't exists in db, create new row with new name and removed 0
// If name exists in db, check for removed 1 for existing name:
            // If found, replace the new one with that removed 1 with removed 0
       // else replace the new one with that removed 0 (Works like upsert)
</code>```

答: You seem to have UNIQUE(name, removed).  But that means that you can have 2 rows for each country??  Perhaps you want only PRIMARY KEY(name).  This would allow IODKU (aka Upsert) based just on name.

Title: Check create duplicate for soft delete

Body:
I had a database table named country. Each country has name and removed column. When user create a new country with name, a new row with name together with removed default 0 will be created. I had created unique index for name and removed columns.

What I want right now is able to create new row with name and removed 0 uniquely and also update with replace into where removed 1 or update the existing row where removed 0.

INSERT INTO country (name, removed) VALUES ('United State',0) ON DUPLICATE KEY UPDATE name = VALUES(name), removed = 1
SELECT name FROM country WHERE removed = 1

Condition

// If name doesn't exists in db, create new row with new name and removed 0
// If name exists in db, check for removed 1 for existing name:
            // If found, replace the new one with that removed 1 with removed 0
       // else replace the new one with that removed 0 (Works like upsert)


答:
This code:

```<code>Me.Controls.OfType(Of TextBox)
</code>```

returns an IEnumerable(Of TextBox).  It's not a single Textbox so you can't assign it to a TextBox variable.  You need to access the TextBox that raised the event:

```<code>Dim textBox As TextBox = DirectCast(sender, TextBox)
</code>```

In an event handler, the sender parameter is always the object that raised the event.

Title: How to AddHandler to Multiple Items and Properly Reference Said Handler

Body:
This code:

Me.Controls.OfType(Of TextBox)

returns an IEnumerable(Of TextBox).  It's not a single Textbox so you can't assign it to a TextBox variable.  You need to access the TextBox that raised the event:

Dim textBox As TextBox = DirectCast(sender, TextBox)

In an event handler, the sender parameter is always the object that raised the event.


问:
Swift UITableView how to retain edited values on scroll
I am following this link https://medium.com/ios-os-x-development/ios-how-to-build-a-table-view-with-multiple-cell-types-2df91a206429 to generate dynamic fields in a uitableview by reading a JSON array , what I am changing in that example is instead of just displaying the data I am making the labels as editable making it a UITextField, I understand that a tableview regenerates each cell that goes on and off the view. I would like to understand how to retain the edited values in each cell.</p>

答:
Basically, the table view is supposed to present the data of a data source.

In your case (in the medium example) the data source is of type ProfileViewModel which holds an array of items of type ProfileViewModelItem. Every cell presents the data of a single ProfileViewModelItem .

The way to retain the edited values is to change the item which is presented by the cell who's text field is being edited.

So every time a user types in a text field , you should change the data in the item (ProfileViewModelItem) which is holding the text that is being shown by the text field. That way the text field and the item are in sync and if the cell goes away , when it comes back on the screen , the text field will show the same text that is in the item , which is the same text that last appeared on the text field when the cell was last on screen.


问:
Position elements on webpage via CSS or Bootstrap

What is the best way or how do I position elements as shown in the diagram on a webpage to look like this. I tried absolute positioning but I dont know if that would work in a responsive environment and bootstrap seems not able to do this. Any ideas on how to do this positioning and layout?

答:
This could easily be done using both, and take full advantage of bootstraps responsive framework.

Just style the columns as needed and absolutely position circles.


问:
Future Proof DALs
We are in the beginning of a really long development project with several sub projects. Basically each sub-project will take several months to develop. The code itself will be split up into several C# projects, but the physical database will be shared by all projects.

The problem is maintainability. If we add a column to a table, or split a table into two smaller tables, we'll have to go back and modify our C# DAL to support these changes. This is not acceptable, as we'll constantly be adapting the DB conform to the needs of the company as a whole, and not just the needs of a single program. Constantly changing old code would be a neverending task.

Our DB people suggested a different view. We do all our CRUD through stored procedures, and use Linq across several tables to perform our SELECT statements. Then if we restructure the DB several years from now, we can simply supply the same stored procs and views and not have to modify our older code.

The question we have, is what ORM should be used for something like this? EF seems a bit overkill (maybe it's not). Would something like SubSonic with it's T4 templating allow for a simpiler (and perhaps faster) DAL?

Or perhaps someone has an idea on how to make this entire process less painful? We'd rather not add another layer to our application, but neither do we want to go back and modify code everytime we make a db change.

Edit 1:
So when I said "I don't really want to add more layers". This is mostly because we already have several layers. We have Silverlight views, view-models, BLL objects (via CSLA) then we have the DAL, and finally the SQL tables themseleves.

答: How long can you work without the database? If it is a problem, introduce it late. And yes, that probably means you add a layer.</p>

Title: Future Proof DALs


问:
How can I make an iteration then iterate the same object again after a break in Blade PHP (Laravel)
In my controller, I'm passing a Collection of 8 items:

```<code>$data['items'] = Item::orderBy('id','desc')->take(8)->get();
</code>```

to the view. Using Blade, I want to break the collection in half and render each half in different positions:

@foreach($items as $item)
  // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items as $item)
  // iterate the rest 4 items from the same object $items
@endforeach
```

How can I do this?

答:
See the Chunk() method:

The chunk method breaks the collection into multiple, smaller
  collections of a given size:

```<code>$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]
</code>```

This method is especially useful in views when working with a grid
  system such as Bootstrap. Imagine you have a collection of Eloquent
  models you want to display in a grid:

```<code>@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach
</code>```

In your specific situation, you can do this:

```<code>@foreach($items->chunk(4)->toArray[1] as $item)
  //iterate "n" times (4 for example)
@endforeach

some <html>

@foreach($items->chunk(4)->toArray[2] as $item)
  //iterate the rest 4 items from the same object $items
@endforeach
</code>```

Body:
In my controller, I'm passing a Collection of 8 items:

$data['items'] = Item::orderBy('id','desc')->take(8)->get();

to the view. Using Blade, I want to break the collection in half and render each half in different positions:

@foreach($items as $item)
  // iterate "n" times (4 for example)
@endforeach

// some html...

@foreach($items as $item)
  // iterate the rest 4 items from the same object $items
@endforeach

How can I do this?

Body:
See the Chunk() method:

The chunk method breaks the collection into multiple, smaller
  collections of a given size:

$collection = collect([1, 2, 3, 4, 5, 6, 7]);

$chunks = $collection->chunk(4);

$chunks->toArray();

// [[1, 2, 3, 4], [5, 6, 7]]

This method is especially useful in views when working with a grid
  system such as Bootstrap. Imagine you have a collection of Eloquent
  models you want to display in a grid:

@foreach ($products->chunk(3) as $chunk)
    <div class="row">
        @foreach ($chunk as $product)
            <div class="col-xs-4">{{ $product->name }}</div>
        @endforeach
    </div>
@endforeach

In your specific situation, you can do this:

@foreach($items->chunk(4)->toArray[1] as $item)
  //iterate "n" times (4 for example)
@endforeach

some <html>

@foreach($items->chunk(4)->toArray[2] as $item)
  //iterate the rest 4 items from the same object $items
@endforeach